<!-- 测试、校准或检定合格分包方名录 基本信息 -->
<script name="SubpackageDirectoriesBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { IForm } from '../directories-interface'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import type { dictType } from '@/global'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { addDirectories, failUpdateDirectories, getInfo, submit, updateDirectories } from '@/api/business/subpackage/directories'
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 form: Ref<IForm> = ref({ // 表单
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  outsourcerNo: '', // 分包方编号
  outsourcerName: '', // 公司名称
  outsourcerBriefName: '', // 公司简称
  businessContent: '', // 业务内容
  outsourcerSize: '', // 公司规模
  businessSize: '', // 业务规模-字典code
  grade: '', // 履约评级
  evaluation: '', // 整体评价
  taxNumber: '', // 税号
  bankAccount: '', // 银行账户名
  bankName: '', // 银行名称
  bankAccountNumber: '', // 银行账号
  director: '', // 机构负责人
  postalCode: '', // 邮编
  phone: '', // 联系电话
  fax: '', // 传真
  mobile: '', // 手机
  email: '', // 邮箱
  website: '', // 网址
  fullAddress: '', // 公司地址-详细地址
  addressArea: '', // 公司地址-区编码
  addressCity: '', // 公司地址-市编码
  addressCountry: '', // 公司地址-国家编码
  addressProvince: '', // 公司地址-省编码
  addressAreaName: '', // 公司地址-区
  addressCityName: '', // 公司地址-市
  addressCountryName: '', // 公司地址-国家
  addressProvinceName: '', // 公司地址-省
  invoiceFullAddress: '', // 开票地址-详细地址
  invoiceArea: '', // 开票地址-区编码
  invoiceCity: '', // 开票地址-市编码
  invoiceCountry: '', // 开票地址-国家编码
  invoiceProvince: '', // 开票地址-省编码
  invoiceAreaName: '', // 开票地址-区
  invoiceCityName: '', // 开票地址-市
  invoiceCountryName: '', // 开票地址-国家
  invoiceProvinceName: '', // 开票地址-省
  businessScope: '', // 测试能力
  remark: '', // 备注
  minioFileName: '', // minio存储文件名
})
const fullAddress = ref<string[]>([]) // 公司地址
const invoiceFullAddress = ref<string[]>([]) // 开票地址
const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id
const rules = ref<FormRules>({ // 表单验证规则
  outsourcerName: [{ required: true, message: '单位名称必填', trigger: 'blur' }],
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
})
// -------------------------------------------文件上传--------------------------------------
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// ------------------------------------------字典----------------------------------------------
const companySizeList = ref<dictType[]>([]) // 公司规模列表
const businessSizeList = ref<dictType[]>([]) // 业务规模列表
const gradeList = ref<dictType[]>([]) // 履约评级列表
const evaluationList = ref<dictType[]>([]) // 整体评价列表
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
  })
  // 获取公司规模
  getDictByCode('companySize').then((response) => {
    companySizeList.value = response.data
  })
  // 获取业务规模
  getDictByCode('businessSize').then((response) => {
    businessSizeList.value = response.data
  })
  // 获取履约评级
  getDictByCode('grade').then((response) => {
    gradeList.value = response.data
  })
  // 获取整体评价
  getDictByCode('evaluation').then((response) => {
    evaluationList.value = response.data
  })
}
// -----------------------------------------其他方法------------------------------------------

// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
    if (props.pageType == 'detail') {
      fullAddress.value = [form.value.addressCountryName, form.value.addressProvinceName, form.value.addressCityName, form.value.addressAreaName, form.value.fullAddress]
      invoiceFullAddress.value = [form.value.invoiceCountryName, form.value.invoiceProvinceName, form.value.invoiceCityName, form.value.invoiceAreaName, form.value.invoiceFullAddress]
    }
    else {
      fullAddress.value = [form.value.addressCountry, form.value.addressProvince, form.value.addressCity, form.value.addressArea, form.value.fullAddress]
      invoiceFullAddress.value = [form.value.invoiceCountry, form.value.invoiceProvince, form.value.invoiceCity, form.value.invoiceArea, form.value.invoiceFullAddress]
    }
  })
}

// 公司地址变化后给对象赋值
function fullAddressChange(addressObj: IAddress) {
  form.value.addressCountry = addressObj.country
  form.value.addressProvince = addressObj.province
  form.value.addressCity = addressObj.city
  form.value.addressArea = addressObj.area
  form.value.fullAddress = addressObj.address
  form.value.addressCountryName = addressObj.countryName
  form.value.addressProvinceName = addressObj.provinceName
  form.value.addressCityName = addressObj.cityName
  form.value.addressAreaName = addressObj.areaName
}
// 开票地址发生变化
function invoiceFullAddressChange(addressObj: IAddress) {
  form.value.invoiceCountry = addressObj.country
  form.value.invoiceProvince = addressObj.province
  form.value.invoiceCity = addressObj.city
  form.value.invoiceArea = addressObj.area
  form.value.invoiceFullAddress = addressObj.address
  form.value.invoiceCountryName = addressObj.countryName
  form.value.invoiceProvinceName = addressObj.provinceName
  form.value.invoiceCityName = addressObj.cityName
  form.value.invoiceAreaName = addressObj.areaName
}

// -----------------------------------------------保存---------------------------------------
/**
 * 点击保存
 * @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') { // 新建
          addDirectories(form.value).then((res) => {
            loading.close()
            form.value.outsourcerNo = res.data.outsourcerNo // 分包方编号
            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 === '全部') {
            updateDirectories(form.value).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateDirectories(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_DIRECTORIES_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() // 获取详情信息
  }
})

defineExpose({ saveForm, submitForm })
</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="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="outsourcerNo">
            <el-input
              v-model="form.outsourcerNo"
              :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位名称:" prop="outsourcerName">
            <el-input
              v-model.trim="form.outsourcerName"
              :placeholder="pageType === 'detail' ? '' : '请输入单位名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col><el-col :span="6">
          <el-form-item label="单位简称:">
            <el-input
              v-model="form.outsourcerBriefName"
              :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="businessContent">
            <el-input
              v-model.trim="form.businessContent"
              :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="outsourcerSize">
            <el-select v-model="form.outsourcerSize" :placeholder="pageType === 'detail' ? ' ' : '请选择公司规模'" :disabled="pageType === 'detail'" class="full-width-input">
              <el-option v-for="item in companySizeList" :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="businessSize">
            <el-select v-model="form.businessSize" :placeholder="pageType === 'detail' ? ' ' : '请选择业务规模'" :disabled="pageType === 'detail'" class="full-width-input">
              <el-option v-for="item in businessSizeList" :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="grade">
            <el-select v-model="form.grade" :placeholder="pageType === 'detail' ? ' ' : '请选择履约评级'" :disabled="pageType === 'detail'" class="full-width-input">
              <el-option v-for="item in gradeList" :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="evaluation">
            <el-select v-model="form.evaluation" :placeholder="pageType === 'detail' ? ' ' : '请选择整体评价'" :disabled="pageType === 'detail'" class="full-width-input">
              <el-option v-for="item in evaluationList" :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="taxNumber">
            <el-input
              v-model="form.taxNumber"
              :placeholder="pageType === 'detail' ? ' ' : '请输入税号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行账户名:">
            <el-input
              v-model="form.bankAccount"
              :placeholder="pageType === 'detail' ? ' ' : '请输入银行账户名'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行名称:">
            <el-input
              v-model="form.bankName"
              :placeholder="pageType === 'detail' ? ' ' : '请输入银行名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行账号:">
            <el-input
              v-model="form.bankAccountNumber"
              :placeholder="pageType === 'detail' ? ' ' : '请输入银行账号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮编:">
            <el-input
              v-model="form.postalCode"
              :placeholder="pageType === 'detail' ? ' ' : '请输入邮编'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="机构负责人:">
            <el-input
              v-model="form.director"
              :placeholder="pageType === 'detail' ? ' ' : '请输入机构负责人'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话:">
            <el-input
              v-model="form.phone"
              :placeholder="pageType === 'detail' ? ' ' : '请输入联系电话'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="传真:">
            <el-input
              v-model="form.fax"
              :placeholder="pageType === 'detail' ? ' ' : '请输入传真'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机:">
            <el-input
              v-model="form.mobile"
              :placeholder="pageType === 'detail' ? ' ' : '请输入手机'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮箱:">
            <el-input
              v-model="form.email"
              :placeholder="pageType === 'detail' ? ' ' : '请输入邮箱'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="网址:">
            <el-input
              v-model="form.website"
              :placeholder="pageType === 'detail' ? ' ' : '请输入网址'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-form-item label="公司地址:">
          <address-select :data="fullAddress" :detail="pageType === 'detail'" @on-change="fullAddressChange" />
        </el-form-item>
      </el-row>
      <el-row :gutter="5">
        <el-form-item label="开票地址:">
          <address-select :data="invoiceFullAddress" :detail="pageType === 'detail'" @on-change="invoiceFullAddressChange" />
        </el-form-item>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="14">
          <el-form-item label="测试能力:">
            <el-input
              v-model="form.businessScope"
              :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="14">
          <el-form-item label="备注:">
            <el-input
              v-model="form.remark"
              :placeholder="pageType === 'detail' ? '' : '请输入备注'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="附件:">
            <show-photo v-if="form.minioFileName" :minio-file-name="form.minioFileName" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
            <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.minioFileName === '' ? '0px' : '20px' }" @click="upload">
              {{ form.minioFileName === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
</template>
