<!-- 设备状态 - 编辑 -->
<script lang="ts" setup name="DeviceStatusEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import annexList from './annexList.vue'
import ApprovalDialog from './ApprovalDialog.vue'
import selectDevice from '@/views/tested/device/group/components/selectDevice.vue'
import useUserStore from '@/store/modules/user'
import { cancelStatus, deleteStatus, detailStatus, editStatus, submitStatus } from '@/api/eqpt/status/index'
import { SCHEDULE } from '@/utils/scheduleDict'
import { delTextBtn, editBtn, submitBtn } from '@/utils/applyBtns'
import { getInfoDetail } from '@/api/eqpt/device/info'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const submitId = ref('') // 提交id-保存接口获取
const ruleFormRef = ref<FormInstance>() // from组件
const ruleFormRef1 = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string // 审批状态
const statusTypeDict = ref<{ [key: string]: string }>({
  1: '封存', // 封存
  2: '启封', // 启封
  3: '禁用', // 禁用
  4: '报废', // 报废
  5: '延用', // 延用
})
const statusTypeNameDict = ref<{ [key: string]: string }>({
  1: 'sealpage', // 封存
  2: 'unsealpage', // 启封
  3: 'disablepage', // 禁用
  4: 'scrappage', // 报废
  5: 'sdelaypage', // 延用
})
const formIdDict = ref<{ [key: string]: string }>({
  1: SCHEDULE.EQUIPMENT_SEALED_APPROVAL,
  2: SCHEDULE.EQUIPMENT_UNSEALED_APPROVAL,
  3: SCHEDULE.EQUIPMENT_DISABLE_APPROVAL,
  4: SCHEDULE.EQUIPMENT_SCRAP_APPROVAL,
  5: SCHEDULE.EQUIPMENT_DELAY_APPROVAL,
})
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
// 表单
const ruleForm = ref({
  approvalAddress: '',
  approvalName: '',
  approvalNo: '',
  approvalReason: '',
  approvalStatus: '',
  approvalStatusName: '',
  approvalTime: '',
  approvalType: '',
  attachments: [],
  companyId: 0,
  companyName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  decisionItem: '',
  delayTime: '',
  deptId: '',
  equipmentId: '',
  equipmentInfo: '' as any,
  equipmentName: '',
  equipmentNo: '',
  equipmentStatus: '',
  id: '',
  model: '',
  performStatus: '',
  processId: '',
  taskId: '',
  updateTime: '',
  productDate: '',
  manufactureNo: '',
  manufacturer: '',
  productCountry: '',
})
// 表单1验证规则
const rules = ref<FormRules>({
  // equipmentNo: [{ required: true, message: '设备必选', trigger: ['blur', 'change'] }],
  equipmentNo: [{ required: true, message: '设备统一编号必选', trigger: ['blur', 'change'] }],
})
const rules1 = ref<FormRules>({
  approvalTime: [{ required: true, message: `${statusTypeDict.value[$route.query.statusType as string]}时间必选`, trigger: ['blur', 'change'] }],
  approvalReason: [{ required: true, message: `${statusTypeDict.value[$route.query.statusType as string]}原因必填`, trigger: ['blur', 'change'] }],
  approvalAddress: [{ required: true, message: `${statusTypeDict.value[$route.query.statusType as string]}地点必填`, trigger: ['blur', 'change'] }],
  performStatus: [{ required: true, message: '设备性能状态必填', trigger: ['blur', 'change'] }],
  equipmentStatus: [{ required: true, message: '启封设备状态必填', trigger: ['blur', 'change'] }],
})
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string || 'detail'
  ruleFormRef.value?.resetFields()
  ruleFormRef1.value?.resetFields()
  if ($route.params.type === 'create') {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.approvalName = `设备${statusTypeDict.value[Number($route.query.statusType as string)]}登记表`
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
    ruleForm.value.approvalType = $route.query.statusType as string
  }
  else {
    const data = JSON.parse($route.query.row as string)
    detailStatus({ id: data.id }).then((res) => {
      ruleForm.value = res.data
      const data = res.data.equipmentInfo
      ruleForm.value.equipmentNo = data.equipmentNo
      ruleForm.value.equipmentName = data.equipmentName
      ruleForm.value.equipmentId = data.id
      ruleForm.value.model = data.model
      ruleForm.value.companyName = data.companyName
      ruleForm.value.productCountry = data.productCountry
      ruleForm.value.manufacturer = data.manufacturer
      ruleForm.value.manufactureNo = data.manufactureNo
      ruleForm.value.productDate = data.productDate
    })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  $router.back()
}
const annexRef = ref()
// 保存
const saveForm = async (formEl: FormInstance | undefined, formEl1: FormInstance | undefined) => {
  if (!formEl || !formEl1) { return }
  Promise.all([formEl.validate(), formEl1.validate()]).then(() => {
    // 验证表格
    if (annexRef.value.checkCertificateList()) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        ruleForm.value.attachments = annexRef.value.list
        ruleForm.value.equipmentInfo = undefined
        editStatus(ruleForm.value).then((res) => {
          submitId.value = res.data
          if (statusName === '已取消' || statusName === '未通过') {
            submitStatus({ id: submitId.value, formId: formIdDict.value[Number($route.query.statusType as string)] }).then((res) => {
              ElMessage.success('已提交')
              close()
            })
          }
          else {
            ElMessage.success('保存成功')
          }
        })
      })
    }
  })
}
// 提交
const submitForm = () => {
  if (submitId.value === '') {
    ElMessage.warning('请先保存')
    return false
  }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitStatus({ id: submitId.value, formId: formIdDict.value[Number($route.query.statusType as string)] }).then((res) => {
      ElMessage.success('已提交')
      close()
    })
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
// 编辑
const editForm = () => {
  $router.push({
    path: `/${statusTypeNameDict.value[$route.query.statusType as string]}/update`,
    query: { ...$route.query },
  })
  initDialog()
}
// 删除
const delForm = () => {
  ElMessageBox.confirm(
    '确认删除设备信息吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteStatus(ruleForm.value.id).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
// 取消
const cancelForm = () => {
  ElMessageBox.confirm(
    '确认取消吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelStatus({ id: ruleForm.value.id, processInstanceId: ruleForm.value.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
// 审批
const approvalDialogRef = ref()
const apply = (type: string) => {
  const data = JSON.parse($route.query.row as string)
  approvalDialogRef.value.initDialog(type, JSON.parse($route.query.row as string).taskId, data.processId, ruleForm.value.id)
}
//  打印
const print = () => {

}
const deviceRef = ref()
const selectDeviceFun = () => {
  deviceRef.value.initDialog()
}
const confirm = (row: any) => {
  const data = row
  ruleForm.value.equipmentNo = data.equipmentNo
  ruleForm.value.equipmentName = data.equipmentName
  ruleForm.value.equipmentId = data.id
  ruleForm.value.model = data.model
  ruleForm.value.companyName = data.companyName
  ruleForm.value.productCountry = data.productCountry
  ruleForm.value.manufacturer = data.manufacturer
  ruleForm.value.manufactureNo = data.manufactureNo
  ruleForm.value.productDate = data.productDate
  ruleForm.value.productDate = data.productDate
  // 获取设备 技术指标信息
  getInfoDetail({ equipmentId: row.id }).then((res) => {
    ruleForm.value.attachments = res.data.attachments
  })
}
defineExpose({ ruleForm, apply, editForm, submitForm, saveForm, delForm, print, cancelForm })
</script>

<template>
  <app-container style="overflow: hidden;">
    <!-- 选择设备弹窗 -->
    <select-device ref="deviceRef" :status-type="$route.query.statusType as string" :need-status="true" @add="confirm" />
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page class="base-info-device" :title="`${statusTypeDict[$route.query.statusType as string]}申请-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="statusName === '待审批'" type="primary" @click="apply('agree')">
          同意
        </el-button>
        <el-button v-if="statusName === '待审批'" type="primary" @click="apply('refuse')">
          拒绝
        </el-button>
        <el-button v-if="editBtn(statusName, dialogStatus)" type="primary" @click="editForm()">
          编辑
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus) && statusName !== '已取消' && statusName !== '未通过'" type="primary" @click="submitForm()">
          提交
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus)" type="primary" @click="saveForm(ruleFormRef, ruleFormRef1)">
          保存
        </el-button>
        <el-button v-if="delTextBtn(statusName)" type="info" @click="delForm()">
          删除
        </el-button>
        <el-button v-if="statusName === '审批中'" type="info" @click="cancelForm()">
          取消
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form label-position="right" label-width="110px" class="form" :disabled="$route.path.includes('detail')">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="登记表编号">
              <el-input v-model.trim="ruleForm.approvalNo" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="登记表名称">
              <el-input v-model.trim="ruleForm.approvalName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人">
              <el-input v-model.trim="ruleForm.createUserName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请时间">
              <el-input v-model.trim="ruleForm.createTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <el-form
        ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form"
        :class="[$route.path.includes('detail') ? 'isDetail' : '']" :disabled="$route.path.includes('detail')"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="统一编号" prop="equipmentNo">
              <el-input v-model.trim="ruleForm.equipmentNo" placeholder="" @focus="selectDeviceFun">
                <template v-if="!$route.path.includes('detail')" #append>
                  <span @click="selectDeviceFun">选择</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model.trim="ruleForm.equipmentName" placeholder="设备名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号" prop="model">
              <el-input v-model.trim="ruleForm.model" placeholder="规格型号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所在单位" prop="companyName">
              <el-input v-model.trim="ruleForm.companyName" placeholder="所在单位" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="生产国家" prop="productCountry">
              <el-input v-model.trim="ruleForm.productCountry" placeholder="生产国家" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model.trim="ruleForm.manufacturer" placeholder="生产厂家" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号" prop="manufactureNo">
              <el-input v-model.trim="ruleForm.manufactureNo" placeholder="出厂编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期" prop="productDate">
              <el-date-picker
                v-model="ruleForm.productDate" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择生产日期" class="normal-date" style="width: 100%;" disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <annex-list ref="annexRef" :data="ruleForm.attachments" :status="$route.params.type as string" />
    </detail-block-com>
    <detail-block-com>
      <el-form ref="ruleFormRef1" :model="ruleForm" :rules="rules1" label-position="right" label-width="110px" class="form" :class="[$route.path.includes('detail') ? 'isDetail' : '']" :disabled="$route.path.includes('detail')">
        <el-row v-if="$route.query.statusType !== '4' && $route.query.statusType !== '5' && $route.query.statusType !== '2'" :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item label="设备性能状态" prop="performStatus">
              <el-input v-model.trim="ruleForm.performStatus" placeholder="设备性能状态" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="$route.query.statusType === '2'" :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item label="启封设备状态" prop="equipmentStatus">
              <el-input v-model.trim="ruleForm.equipmentStatus" placeholder="启封设备状态" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item :label="`${statusTypeDict[$route.query.statusType as string]}原因`" prop="approvalReason">
              <el-input v-model.trim="ruleForm.approvalReason" :placeholder="`${statusTypeDict[$route.query.statusType as string]}原因`" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="$route.query.statusType !== '2' && $route.query.statusType !== '5'" :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item :label="`${statusTypeDict[$route.query.statusType as string]}地点`" prop="approvalAddress">
              <el-input v-model.trim="ruleForm.approvalAddress" :placeholder="`${statusTypeDict[$route.query.statusType as string]}地点`" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="$route.query.statusType !== '2'" :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item :label="`${statusTypeDict[$route.query.statusType as string]}时间`" prop="approvalTime">
              <!-- <el-input v-model.trim="ruleForm.approvalTime" /> -->
              <el-date-picker
                v-model="ruleForm.approvalTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" :placeholder="`${statusTypeDict[$route.query.statusType as string]}时间`" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <approval-record-table v-if="!$route.path.includes('create')" :process-id="JSON.parse($route.query.row as string).processId" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
