<!-- 测试、校准或检定工作分包通知书书 基本信息 -->
<script name="SubpackageInformBasic" lang="ts" setup>
import dayjs from 'dayjs'
import type { FormRules } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { Ref } from 'vue'
import type { IForm } from '../inform-interface'
import selectCustomerDialog from '@/views/business/manager/order/dialog/selectCustomer.vue'
import {
  addInform,
  failUpdateInform,
  getInfo,
  submit,
  updateInform,
} from '@/api/business/subpackage/inform'
import { getInfo as getDirectoriesDetail } from '@/api/business/subpackage/directories'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'
import useUserStore from '@/store/modules/user'
import { SCHEDULE } from '@/utils/scheduleDict'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    requre: true,
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const user = useUserStore() // 用户信息
const form: Ref<IForm> = ref({
  createUserId: '', // 申请人id
  createUserName: '', // 申请人名字
  createTime: '', // 申请时间
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  noticeNo: '', // 通知书编号
  noticeName: '', // 通知书名称
  formId: '',
  customerId: '', // 受检单位(委托方)id
  customerName: '', // 受检单位名称
  deviceName: '', // 分包设备名字
  outsourcerName: '', // 分包方名称
  contacts: '', // 联系人
  mobile: '', // 联系电话
})
const ruleFormRef = ref() // 表单ref
const noticeFormRef = 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'] }],
  customerName: [{ required: true, message: '受检单位不能为空', trigger: ['blur', 'change'] }],
  deviceName: [{ required: true, message: '分包设备不能为空', trigger: ['blur', 'change'] }],
  outsourcerName: [{ required: true, message: '分包方不能为空', trigger: ['blur', 'change'] }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '电话不能为空', trigger: 'blur' }],
})
// ------------------------------------------字典----------------------------------------------
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 fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
  })
}

// -----------------------------------------------保存---------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      noticeFormRef.value.validate((validIn: boolean) => {
        if (validIn) {
          // 基本信息表单通过校验
          ElMessageBox.confirm('确认保存吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            const loading = ElLoading.service({
              lock: true,
              text: '加载中...',
              background: 'rgba(255, 255, 255, 0.6)',
            })
            if (props.pageType === 'add') {
              // 新建
              addInform(form.value)
                .then((res) => {
                  loading.close()
                  form.value.noticeNo = res.data.noticeNo // 通知书编号
                  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 === '全部'
              ) {
                updateInform(form.value)
                  .then((res) => {
                    loading.close()
                    emits('addSuccess', infoId.value)
                    ElMessage.success('已保存')
                  })
                  .catch(() => {
                    loading.close()
                  })
              }
              else {
                // '未通过' || '已取消'
                failUpdateInform(form.value)
                  .then((res) => {
                    loading.close()
                    emits('submitSuccess')
                    ElMessage.success('已保存')
                  })
                  .catch(() => {
                    loading.close()
                  })
              }
            }
          })
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id // 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.SUBPACKAGE_NOTICE_APPROVAL,
    processId,
  }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// ------------------------------------------委托方-----------------------------------------------
const selectCustomerRef = ref() // 委托方组件ref
// 点击选择委托方
const selectCustomer = () => {
  selectCustomerRef.value.initDialog()
}
// 选好委托方
const clickConfirmCustomer = (val: any) => {
  // 委托方变化设备清空
  if (val && val.length) {
    form.value.customerId = val[0].deptId // 委托方id、deptId是受检设备系统里的委托方id
    form.value.customerName = val[0].customerName // 委托方名称
  }
}
// ---------------------------------------------钩子----------------------------------------------
watch(
  () => props.id, (newValue) => {
    infoId.value = newValue!
    if (infoId.value) {
      fetchInfo() // 获取详情信息
    }
  },
  { immediate: true },
)

onMounted(async () => {
  await getDict() // 获取字典
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
  if (props.pageType === 'add') {
    form.value.noticeName = '测试、校准或检定工作分包通知书' // 通知书名称
    form.value.createUserId = user.id // 申请人id
    form.value.createUserName = user.name // 申请人名字
    form.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
  }
})

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

<template>
  <div class="inform-basic">
    <detail-block v-loading="loading" title="">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :label-width="130"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24">
          <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="通知书编号:" prop="noticeNo">
              <el-input
                v-model="form.noticeNo"
                :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="通知书名称:" prop="noticeName">
              <el-input
                v-model.trim="form.noticeName"
                :placeholder="pageType === 'detail' ? '' : '通知书名称'"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </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-input v-model="form.createTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>
    <detail-block v-loading="loading" title="" style="letter-spacing: 2px;padding-left: 100px;padding-right: 100px;text-align: justify;line-height: 60px;">
      <h3 style="text-align: center;">
        测试、校准或检定工作分包通知书
      </h3>
      <el-form
        ref="noticeFormRef"
        :model="form"
        :label-width="10"
        label-position="right"
        :rules="rules"
        style="display: flex;flex-wrap: wrap;"
      >
        <el-form-item label="" prop="customerName" style="width: 100%;">
          <div style="display: flex; align-items: center;">
            <el-input
              v-model="form.customerName"
              :placeholder="pageType === 'detail' ? '' : '请选择受检单位'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectCustomer">
                  选择
                </el-button>
              </template>
            </el-input>
            <span style="margin-left: 8px;"> :</span>
          </div>
        </el-form-item>
        <div style="display: flex;flex-wrap: wrap;">
          <span style="text-indent: 42px;">贵单位送到本站测试、校准或检定的</span>
          <el-form-item label="" prop="deviceName">
            <el-input
              v-model="form.deviceName"
              :placeholder="pageType === 'detail' ? '' : '设备'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
          <span>，因能力所限，现决定将</span>
          <el-form-item label="">
            <el-input
              v-model="form.deviceName"
              :placeholder="pageType === 'detail' ? '' : '设备'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
          <span>这部分测试内容分包给</span>
          <el-form-item label="" prop="outsourcerName">
            <el-input
              v-model="form.outsourcerName"
              :placeholder="pageType === 'detail' ? '' : '分包方'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
          <span>。</span>
          <span>本站已对分包方的能力进行过评审，符合要求。贵单位是否同意本站的分包意向，请尽快回复。联系人:</span>

          <el-form-item label="" prop="contacts">
            <el-input
              v-model="form.contacts"
              :placeholder="pageType === 'detail' ? '' : '联系人'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
          <span>，电话:</span>
          <el-form-item label="" prop="mobile">
            <el-input
              v-model="form.mobile"
              :placeholder="pageType === 'detail' ? ' ' : '请输入电话'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
          <span>。</span>
          <span style="width: 100%;text-align: right;">西昌卫星发射中心计量测试站</span>
          <span style="width: 100%;text-align: right;">年ㅤㅤ月ㅤㅤ日</span>
        </div>
      </el-form>
    </detail-block>
  </div>

  <!-- 选择委托方组件 -->
  <select-customer-dialog ref="selectCustomerRef" @confirm="clickConfirmCustomer" />
</template>

