<!-- 测试、校准或检定工作分包协议书 基本信息 -->
<script name="SubpackageAgreementBasic" 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 '../agreement-interface'
import SelectOutsourcerNoDialog from '@/views/business/subpackage/review/dialog/selectOutsourcerNoDialog.vue'
import {
  addAgreement,
  failUpdateAgreement,
  getInfo,
  submit,
  updateAgreement,
} from '@/api/business/subpackage/agreement'
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({
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  protocolNo: '', // 协议书编号
  projectName: '', // 协议书名称
  formId: '',
  outsourcerId: '', // 分包方id
  outsourcerNo: '', // 分包方编号
  outsourcerName: '', // 分包机构名称
  contacts: '', // 联系人
  mobile: '', // 联系电话
  fullAddress: '', // 公司地址-详细地址
  addressArea: '', // 公司地址-区编码
  addressCity: '', // 公司地址-市编码
  addressCountry: '', // 公司地址-国家编码
  addressProvince: '', // 公司地址-省编码
  addressAreaName: '', // 公司地址-区
  addressCityName: '', // 公司地址-市
  addressCountryName: '', // 公司地址-国家
  addressProvinceName: '', // 公司地址-省
  requireDate: '', // 要求完成日期
  outsourceCost: '', // 分包费用(元)
  director: '', // 机构负责人
  item: '', // 分包项目
  requires: '', // 分包要求
  remark: '', // 其他
})
const fullAddress = ref<string[]>([]) // 公司地址
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'] }],
  outsourcerNo: [{ required: true, message: '分包方编号不能为空', trigger: ['blur', 'change'] }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '电话不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '地址不能为空', trigger: ['blur', 'change'] }],
  requireDate: [{ required: true, message: '要求完成日期不能为空', trigger: ['blur', 'change'] }],
  outsourceCost: [{ required: true, message: '分包费用不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '分包费用只能为数字', trigger: ['blur', 'change'] },
  ],
  director: [{ required: true, message: '分包方负责人不能为空', trigger: ['blur', 'change'] }],
  item: [{ required: true, message: '分包项目不能为空', trigger: 'blur' }],
  requires: [{ required: true, message: '分包要求不能为空', trigger: 'blur' }],
  remark: [{ 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 selectOutsourcerNoDialogRef = ref() // 选择分包方组件ref
// 点击选择
const selectOutsourcerNo = () => {
  selectOutsourcerNoDialogRef.value.initDialog()
}

// 确定选择分包方
const confirmSelectOutsourcerNo = (val: any) => {
  console.log(val)
  form.value.outsourcerId = val[0].id // 分包方id
  form.value.outsourcerNo = val[0].outsourcerNo // 分包方编号
  form.value.outsourcerName = val[0].outsourcerName // 分包机构名称
  form.value.director = val[0].director // 机构负责人
  fullAddress.value = [
    val[0].addressCountryName,
    val[0].addressProvinceName,
    val[0].addressCityName,
    val[0].addressAreaName,
    val[0].fullAddress,
  ]
}

// -----------------------------------------其他方法------------------------------------------

// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    // loading.value = false
    form.value = res.data
    getDirectoriesDetail({ id: res.data.outsourcerId }).then((response) => {
      loading.value = false
      fullAddress.value = [response.data.addressCountryName, response.data.addressProvinceName, response.data.addressCityName, response.data.addressAreaName, response.data.fullAddress]
    })
  })
}

// -----------------------------------------------保存---------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  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.6)',
        })
        if (props.pageType === 'add') {
          // 新建
          addAgreement(form.value)
            .then((res) => {
              loading.close()
              form.value.protocolNo = res.data.protocolNo // 协议书编号
              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 === '全部'
          ) {
            updateAgreement(form.value)
              .then((res) => {
                loading.close()
                emits('addSuccess', infoId.value)
                ElMessage.success('已保存')
              })
              .catch(() => {
                loading.close()
              })
          }
          else {
            // '未通过' || '已取消'
            failUpdateAgreement(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_AGREEMENT_APPROVAL,
    processId,
  }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}

// ---------------------------------------------钩子----------------------------------------------
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.projectName = '测试、校准或检定工作分包协议书' // 评审表名称
  }
})

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

<template>
  <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="protocolNo">
            <el-input
              v-model="form.protocolNo"
              :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="协议书名称:" prop="projectName">
            <el-input
              v-model.trim="form.projectName"
              :placeholder="pageType === 'detail' ? '' : '协议书名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包方编号:" prop="outsourcerNo">
            <el-input
              v-model="form.outsourcerNo"
              disabled
              :placeholder="pageType === 'detail' ? '' : '请选择分包方编号'"
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectOutsourcerNo">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包方名称:" prop="outsourcerName">
            <el-input
              v-model="form.outsourcerName"
              :placeholder="pageType === 'detail' ? '' : '分包机构名称'"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包方负责人:" prop="director">
            <el-input
              v-model="form.director"
              :placeholder="pageType === 'detail' ? '' : '分包方负责人'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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>
        </el-col>
        <el-col :span="6">
          <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>
        </el-col>
        <el-col :span="6">
          <el-form-item label="要求完成日期:" prop="requireDate">
            <el-date-picker
              v-model="form.requireDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择要求完成日期'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包费用(元):" prop="outsourceCost">
            <el-input
              v-model="form.outsourceCost"
              placeholder="请输入分包费用"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-form-item label="分包方地址:">
          <address-select :data="fullAddress" :detail="true" />
        </el-form-item>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="分包项目:" prop="item">
            <el-input
              v-model="form.item"
              type="textarea"
              autosize
              :placeholder="
                pageType === 'detail' ? ' ' : '请输入分包项目'
              "
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="分包要求:" prop="requires">
            <el-input
              v-model="form.requires"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? ' ' : '请输入分包要求'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="其他:" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? ' ' : '请输入其他'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <!-- 选择分包方编号 -->
  <select-outsourcer-no-dialog ref="selectOutsourcerNoDialogRef" @confirm="confirmSelectOutsourcerNo" />
</template>
