<!-- 溯源计划管理 基本信息 -->
<script name="ChangeApproveBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../change-interface'
import type { deptType, 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 { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getStaffList } from '@/api/resource/register'
import selectStandardDialog from '@/views/equipement/standardStateMaintenance/dialog/selectStandardDialog.vue'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { addChangeList, failUpdateChangeList, getInfo, submit, updateChangeList } from '@/api/equipment/source/change'
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>({
  applyNo: '', // 申请单编号
  applyName: '', // 申请单名称
  createUserId: '', // 申请人id
  createUserName: '', // 申请人
  createTime: '', // 申请时间
  standardId: '', // 标准装置id
  standardNo: '', // 标准代码
  standardName: '', // 标准名称
  deptId: '', // 标准所在部门id
  deptName: '', // 标准所在部门名称
  directorId: '', // 负责人id
  directorName: '', // 负责人名字
  certificateDate: '', // 检定日期
  certificateExpireDate: '', // 证书有效期
  manageStatus: '', // 管理状态
  changeTraceCompany: '', // 拟变更溯源单位
  changeTraceIllustrate: '', // 拟变更溯源单位说明
  changeReason: '', // 变更原因
})

const ruleFormRef = ref() // 表单ref
const certFormRef = ref() // 证书要素确认ref
const resultRulesRef = ref() // 结果确认ref
const equipmentRef = ref() // 设备ref
const loading = ref(false) // loading
const infoId = ref('') // id
const rules = ref<FormRules>({ // 校验规则
  standardNo: [{ required: true, message: '标准代码不能为空', trigger: ['blur', 'change'] }],
  changeTraceCompany: [{ required: true, message: '拟变更溯源单位不能为空', trigger: ['blur', 'change'] }],
  changeTraceIllustrate: [{ required: true, message: '拟变更溯源单位说明不能为空', trigger: ['blur', 'change'] }],
  changeReason: [{ required: true, message: '变更原因不能为空', trigger: ['blur', 'change'] }],
})

// -----------------------------------------字典--------------------------------------------------------------
const manageStatusList = ref<dictType[]>([]) // 使用状态
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
// 查询字典
const getDict = async () => {
  // 使用状态
  getDictByCode('bizStandardManagerState').then((response) => {
    manageStatusList.value = response.data
  })
  // 获取部门列表
  getDeptTreeList().then((res) => {
    // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
  // 获取用户列表
  getStaffList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
}

// ---------------------------------------选择标准代码-----------------------------------------
const selectStandardDialogRef = ref() // 选择标准代码组件ref

// 点击选择标准代码
const selectStandard = () => {
  selectStandardDialogRef.value.initDialog()
}

// 选择好标准代码
const confirmSelectStandard = (val: any) => {
  if (val && val.length) {
    form.value.standardId = val[0].id // 标准装置id
    form.value.standardName = val[0].standardName // 标准装置名称
    form.value.standardNo = val[0].standardNo // 标准装置代码
    form.value.deptId = val[0].deptId // 标准所在部门id
    form.value.deptName = val[0].deptName // 标准所在部门名称
    form.value.directorId = val[0].directorId // 标准负责人
    form.value.directorName = val[0].directorName // 标准负责人id
    form.value.certificateDate = val[0].lastReviewDate // 检定日期
    form.value.certificateExpireDate = val[0].certificateExpireDate // 证书有效期
    form.value.manageStatus = val[0].manageStatus // 管理状态
  }
}

// -----------------------------------------------保存----------------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = () => {
  if (!ruleFormRef) { return }
  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)',
        })
        const params = {
          ...form.value,
          id: infoId.value,
          processId: props.processId,
        }
        if (props.pageType === 'add') { // 新建
          addChangeList(params).then((res) => {
            loading.close()
            form.value.applyNo = res.data.applyNo // 申请表编号
            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 === '全部') {
            updateChangeList(params).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateChangeList(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.TRACE_CHANGE_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
  })
}
// ---------------------------------------------钩子----------------------------------------------
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.applyName = '溯源链变更申请表' // 溯源链变更申请表
  form.value.createTime = 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="160"
      label-position="right"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="申请单编号:" prop="confirmNo">
            <el-input v-model="form.applyNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请单名称:" prop="confirmNo">
            <el-input v-model="form.applyName" disabled placeholder="申请单名称" />
          </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"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准代码:" prop="standardNo">
            <el-input
              v-model="form.standardNo"
              :placeholder="pageType === 'detail' ? '' : '请选择标准代码'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectStandard">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准装置名称:" prop="standardName">
            <el-input v-model="form.standardName" disabled placeholder="标准装置名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准所在部门" prop="deptId">
            <dept-select v-model="form.deptId" disabled :data="useDeptList" :placeholder="pageType === 'detail' ? ' ' : '请选择标准所在部门'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准负责人" prop="directorId">
            <el-select
              v-model.trim="form.directorId"
              placeholder="请选择标准负责人"
              filterable
              disabled
              class="full-width-input"
            >
              <el-option v-for="item in userList" :key="item.id" :label="item.staffName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检定日期:" prop="certificateDate">
            <el-date-picker
              v-model="form.certificateDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择检定日期'"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="证书有效期:" prop="certificateExpireDate">
            <el-date-picker
              v-model="form.certificateExpireDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择证书有效期'"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="管理状态:" prop="manageStatus">
            <el-select
              v-model.trim="form.manageStatus"
              clearable
              :placeholder="pageType === 'detail' ? '' : '管理状态'"
              size="default"
              disabled
              class="full-width-input"
            >
              <el-option
                v-for="item in manageStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="拟变更溯源单位:" prop="changeTraceCompany">
            <el-input
              v-model="form.changeTraceCompany"
              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="changeTraceIllustrate">
            <el-input
              v-model="form.changeTraceIllustrate"
              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="changeReason">
            <el-input
              v-model="form.changeReason"
              autosize
              type="textarea"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <detail-block v-loading="loading" title="量值溯源与传递等级关系图">
    <div style="display: flex;justify-content: center;">
      <img
        src="../../../../../assets/images/source.png"
        style="width: 600px;height: 800px;"
      >
    </div>
  </detail-block>
  <!-- 选择标准代码 -->
  <select-standard-dialog ref="selectStandardDialogRef" @confirm="confirmSelectStandard" />
</template>

<style lang="scss" scoped>
.tech-file {
  display: flex;
  align-items: center;
  margin-left: 20px;
  margin-bottom: 10px;

  .file-text {
    white-space: nowrap;
    margin-right: 10px;
    font-size: 14px;
    color: #60627f;
  }
}
</style>
