<!-- 开箱验收管理 基本信息 -->
<script name="ResumeUnpackApproveBasic" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../unpack-interface'
import type { dictType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
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 { addResumeUnpackList, failUpdateResumeUnpackList, getInfo, submit, updateResumeUnpackList } from '@/api/equipment/resume/unpack'
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: '', // 实验室代码
  logNo: '', // 记录表编号
  logName: '', // 记录表名称
  createUserId: '', // 验收人id
  createUserName: '', // 验收人
  receiveTime: '', // 验收时间
  equipmentName: '', // 设备名称
  model: '', // 规格型号
  manufacturer: '', // 生产厂家
  manufactureNo: '', // 出厂编号
  arrivalTime: '', // 到货时间
  price: '', // 价值
  submitter: '', // 交验者
  submitDate: '', // 交验日期
  mainPerformanceIndex: '', // 主要性能指标
  acceptSuggest: '', // 验收意见
})

const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id
const rules = ref<FormRules>({ // 校验规则
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
  receiveTime: [{ 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'] }],
  arrivalTime: [{ required: true, message: '到货时间不能为空', trigger: ['blur', 'change'] }],
  price: [{ required: true, message: '价值不能为空', trigger: ['blur', 'change'] }],
  submitter: [{ required: true, message: '交验者不能为空', trigger: ['blur', 'change'] }],
  submitDate: [{ required: true, message: '交验日期不能为空', trigger: ['blur', 'change'] }],
  mainPerformanceIndex: [{ required: true, message: '主要性能指标不能为空', trigger: ['blur', 'change'] }],
  acceptSuggest: [{ required: true, message: '验收意见不能为空', trigger: ['blur', 'change'] }],
})
// ------------------------------------------字典----------------------------------------------
const labCodeList = ref<dictType[]>([]) // 实验室代码
const groupCodeList = ref<dictType[]>([]) // 组别代码
function getDict() {
  // 实验室代码
  getDictByCode('bizLabCode').then((response) => {
    labCodeList.value = response.data
  })
  // 组别代码
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })
}
// ----------------------------------------------主附件信息----------------------------------------
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,
              logId: infoId.value,
            }
          }),
          processId: props.processId,
        }
        if (props.pageType === 'add') { // 新建
          addResumeUnpackList(params).then((res) => {
            loading.close()
            form.value.logNo = res.data.logNo // 计划表编号
            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 === '全部') {
            updateResumeUnpackList(params).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateResumeUnpackList(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.UNPACKING_INSPECTING_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.logName = '开箱验收记录表' // 记录表名称
  form.value.receiveTime = dayjs().format('YYYY-MM-DD HH:mm:ss')// 验收时间
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

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

<template>
  <detail-block v-loading="loading" 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="applyNo">
            <el-input v-model="form.logNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="记录表名称:" prop="logName">
            <el-input v-model="form.logName" :disabled="pageType === 'detail'" :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="receiveTime">
            <el-date-picker
              v-model="form.receiveTime"
              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.trim="form.equipmentName"
              :placeholder="pageType === 'detail' ? '' : '请输入设备名称'"
              :disabled="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="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="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="arrivalTime">
            <el-date-picker
              v-model="form.arrivalTime"
              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="price">
            <el-input
              v-model.trim="form.price"
              :placeholder="pageType === 'detail' ? '' : '请输入价值'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交验者:" prop="submitter">
            <el-input
              v-model.trim="form.submitter"
              :placeholder="pageType === 'detail' ? '' : '请输入交验者'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交验日期:" prop="submitDate">
            <el-date-picker
              v-model="form.submitDate"
              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="16">
          <el-form-item label="主要性能指标:" prop="mainPerformanceIndex">
            <el-input
              v-model="form.mainPerformanceIndex"
              class="full-width-input"
              autosize
              type="textarea"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="验收意见:" prop="acceptSuggest">
            <el-input
              v-model="form.acceptSuggest"
              class="full-width-input"
              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>
</template>
