<!-- 设备借用 基本信息 -->
<script name="ResumeBorrowApproveBasic" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../borrow-interface'
import type { dictType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
import { getUserList } from '@/api/system/user'
import { SCHEDULE } from '@/utils/scheduleDict'
import useUserStore from '@/store/modules/user'
import { useCheckList } from '@/commonMethods/useCheckList'
import type { IAccessory } from '@/views/equipement/info/book/book-interface'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { addResumeBorrowList, failUpdateResumeBorrowList, getInfo, submit, updateResumeBorrowList } from '@/api/equipment/resume/borrow'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    requre: true,
  },
  processId: {
    type: String,
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const user = useUserStore() // 用户信息
const form = ref<IForm>({
  groupCode: '', // 组别代码
  labCode: '', // 实验室代码
  registerNo: '', // 登记表编号
  registerName: '', // 登记表名称
  createUserId: '', // 创建人id
  createUserName: '', // 创建人
  createTime: '', // 创建时间
  equipmentName: '', // 设备名称
  model: '', // 型号
  manufacturer: '', // 生产厂家
  manufactureNo: '', // 出厂编号
  equipmentCompany: '', // 设备所属单位
  deptId: '', // 设备借用部门id
  deptName: '', // 设备借用部门id
  borrowDate: '', // 借用日期
  borrowDeadline: '', // 借用期限
  borrowReason: '', // 借用原因
  equipmentPerformanceStatus: '', // 设备性能状态
  traceSituation: '', // 溯源情况
})

const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id

// 自定义校验规则--借用期限应该比借用日期大
const requireOverTimeValid = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('借用期限不能为空'))
  }
  if (new Date(form.value.borrowDeadline).getTime() < new Date(form.value.borrowDate).getTime()) {
    return callback(new Error('借用期限应不小于借用日期'))
  }
  callback()
}
const rules = ref<FormRules>({ // 校验规则
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
  model: [{ required: true, message: '型号规格不能为空', trigger: ['blur', 'change'] }],
  manufacturer: [{ required: true, message: '生产厂家不能为空', trigger: ['blur', 'change'] }],
  manufactureNo: [{ required: true, message: '出厂编号不能为空', trigger: ['blur', 'change'] }],
  borrowCompany: [{ required: true, message: '借用单位不能为空', trigger: ['blur', 'change'] }],
  borrower: [{ required: true, message: '借用人不能为空', trigger: ['blur', 'change'] }],
  borrowDate: [{ required: true, message: '借用日期不能为空', trigger: ['blur', 'change'] }],
  borrowDeadline: [{ required: true, type: 'date', validator: requireOverTimeValid, trigger: 'change' }],
  equipmentPerformanceStatus: [{ required: true, message: '设备性能状态不能为空', trigger: ['blur', 'change'] }],
  borrowReason: [{ required: true, message: '借用原因不能为空', trigger: ['blur', 'change'] }],
  traceSituation: [{ required: true, message: '溯源情况不能为空', trigger: ['blur', 'change'] }],
})
// ------------------------------------------字典----------------------------------------------
const labCodeList = ref<dictType[]>([]) // 实验室代码
const groupCodeList = ref<dictType[]>([]) // 组别代码
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
function getDict() {
  // 实验室代码
  getDictByCode('bizLabCode').then((response) => {
    labCodeList.value = response.data
  })
  // 组别代码
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })
  // 获取用户列表
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
}
// ----------------------------------------------主附件信息----------------------------------------
const checkoutAttachmentList = ref([]) as any // 主附件表格选中
const attachmentList = ref<IAccessory[]>([]) // 主附件信息
const addAccessoryObj: IAccessory = { // 主附件信息对象
  id: '', // 主键
  name: '', // 名称
  information: '', // 信息
  location: '', // 位置
  editable: true,
}
const accessoryColumns = [ // 主附件信息
  { text: '名称', value: 'name', required: true },
  { text: '信息', value: 'information', required: true },
  { text: '位置', value: 'location', required: true },
]

/**
 * 点击增加行
 * @param val 操作的表格类型
 */
const addRow = (val: string) => {
  if (val === 'accessory') { // 主附件信息
    if (useCheckList(attachmentList.value, accessoryColumns, '主附件信息')) {
      useSetAllRowReadable(attachmentList.value)
      attachmentList.value.push({ ...addAccessoryObj })
    }
  }
}

/**
 * 点击删除行
 * @param val 操作的表格类型 tech技术指标、accessory主附件信息、inspect核查点
 */
const deleteRow = (val: string) => {
  if (val === 'accessory' && checkoutAttachmentList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
    return false
  }
  if (val === 'accessory') { // 主附件信息
    attachmentList.value = attachmentList.value.filter((item: IAccessory) => {
      return !checkoutAttachmentList.value.includes(item)
    })
  }
}

// 主附件信息选中
const handleAccessorySelectionChange = (e: any) => {
  checkoutAttachmentList.value = e
}

// 双击主附件信息
const rowDblclickAccessory = (row: IAccessory) => {
  if (props.pageType !== 'detail') {
    useDoubleClickTableRow(row, attachmentList.value)
  }
}

// -----------------------------------------------保存----------------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  if (!useCheckList(attachmentList.value, accessoryColumns, '主附件信息')) {
    return false
  }
  if (!attachmentList.value.length) {
    ElMessage.warning('主附件信息不能为空')
    return false
  }
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.8)',
        })
        console.log('props.processId', props.processId)

        const params = {
          ...form.value,
          id: infoId.value,
          attachmentList: attachmentList.value.map((item) => {
            return {
              ...item,
              lendId: infoId.value,
            }
          }),
          processId: props.processId,
        }
        if (props.pageType === 'add') { // 新建
          addResumeBorrowList(params).then((res) => {
            loading.close()
            form.value.registerNo = res.data.registerNo // 登记表编号
            infoId.value = res.data.id // id
            emits('addSuccess', infoId.value)
            ElMessage.success('已保存')
          }).catch(() => {
            loading.close()
          })
        }
        else if (props.pageType === 'edit') { // 编辑
          console.log(props.approvalStatusName)
          if (props.approvalStatusName === '草稿箱' || props.approvalStatusName === '全部') {
            updateResumeBorrowList(params).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateResumeBorrowList(params).then((res) => {
              loading.close()
              emits('submitSuccess')
              fetchInfo()
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id
 */
const submitForm = (processId: string, id: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({ id, formId: SCHEDULE.EQUIPMENT_BORROW_APPROVAL }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// -----------------------------------------获取详情------------------------------------------
// 获取详情
function fetchInfo() {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
    attachmentList.value = res.data.attachmentList // 设备列表
  })
}
// ---------------------------------------------钩子----------------------------------------------
watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (infoId.value) {
    fetchInfo() // 获取详情信息
  }
}, { immediate: true })

onMounted(() => {
  getDict()
  form.value.createUserId = user.id// 创建人id
  form.value.createUserName = user.name // 创建人名字
  form.value.registerName = '设备借用登记表' // 记录表名称
  form.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')// 创建时间
  form.value.deptId = user.deptId // 借用部门id
  form.value.deptName = user.deptName // 借用部门
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

defineExpose({ saveForm, submitForm, fetchInfo })
</script>

<template>
  <div v-loading="loading">
    <detail-block title="">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :label-width="120"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="登记表编号:" prop="registerNo">
              <el-input v-model="form.registerNo" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="登记表名称:" prop="registerName">
              <el-input v-model="form.registerName" disabled :placeholder="pageType === 'detail' ? ' ' : '登记表名称'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验室代码" prop="labCode">
              <el-select
                v-model="form.labCode"
                :placeholder="pageType === 'detail' ? ' ' : '请选择实验室代码'"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option
                  v-for="item in labCodeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="组别代码" prop="groupCode">
              <el-select
                v-model="form.groupCode"
                :placeholder="pageType === 'detail' ? ' ' : '请选择组别代码'"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option
                  v-for="item in groupCodeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人:">
              <el-input
                v-model="form.createUserName" disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间:" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="pageType === 'detail' ? ' ' : '请选择创建时间'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称:" prop="equipmentName">
              <el-input
                v-model="form.equipmentName"
                :disabled="pageType === 'detail'"
                :class="{ 'detail-input': pageType === 'detail' }"
                :placeholder="pageType === 'detail' ? '' : '请输入设备名称'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号规格" prop="model">
              <el-input
                v-model.trim="form.model"
                placeholder="型号规格"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号:" prop="manufactureNo">
              <el-input
                v-model.trim="form.manufactureNo"
                :placeholder="pageType === 'detail' ? '' : '请输入出厂编号'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家:" prop="manufacturer">
              <el-input
                v-model.trim="form.manufacturer"
                :placeholder="pageType === 'detail' ? '' : '请输入生产厂家'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备所属单位:" prop="equipmentCompany">
              <el-input
                v-model.trim="form.equipmentCompany"
                :placeholder="pageType === 'detail' ? '' : '请输入设备所属单位'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借用部门:" prop="deptName">
              <el-input
                v-model.trim="form.deptName"
                :placeholder="pageType === 'detail' ? '' : '借用单位'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借用日期:" prop="borrowDate">
              <el-date-picker
                v-model="form.borrowDate"
                type="date"
                format="YYYY-MM-DD"
                :placeholder="pageType === 'detail' ? ' ' : '请选择借用日期'"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借用期限:" prop="borrowDeadline">
              <el-date-picker
                v-model="form.borrowDeadline"
                type="date"
                format="YYYY-MM-DD"
                :placeholder="pageType === 'detail' ? ' ' : '请选择借用期限'"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="借用原因:" prop="borrowReason">
              <el-input
                v-model="form.borrowReason"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? ' ' : '请输入借用原因'"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备性能状态:" prop="equipmentPerformanceStatus">
              <el-input
                v-model="form.equipmentPerformanceStatus"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? ' ' : '请选择设备性能状态'"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="溯源情况:" prop="traceSituation">
              <el-input
                v-model="form.traceSituation"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? ' ' : '请输入溯源情况'"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>
    <detail-block title="主附件信息">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="primary" @click="addRow('accessory')">
          增加行
        </el-button>
        <el-button type="info" @click="deleteRow('accessory')">
          删除行
        </el-button>
      </template>
      <el-table
        ref="accessoryRef"
        :data="attachmentList"
        border
        style="width: 100%;"
        @selection-change="handleAccessorySelectionChange"
        @row-dblclick="rowDblclickAccessory"
      >
        <el-table-column v-if="pageType !== 'detail'" type="selection" width="38" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in accessoryColumns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
            <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
  </div>
</template>
