<!-- 分包方 名录 编辑 -->
<script lang="ts" setup name="SubpackageDirectoryEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import personTable from './personTable.vue'
import capacityTable from './capacityTable.vue'
import certificateTable from './certificateTable.vue'
import ApprovalDialog from './ApprovalDialog.vue'
import showPhoto from '@/views/tested/device/info/components/showPhoto.vue'
import { delTextBtn, editBtn, submitBtn } from '@/utils/applyBtns'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import { uploadApi } from '@/api/system/notice'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { cancelDirectory, deleteDirectory, editDirectory, getDetail, submitDirectory } from '@/api/eqpt/subpackage/directory'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const submitId = ref('') // 提交id-保存接口获取
const ruleFormRef = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
// 表单
const ruleForm = ref({
  address: '',
  approvalStatus: '',
  attachments: '',
  bankAccount: '',
  bankName: '',
  bankNumber: '',
  businessContent: '',
  businessScale: '',
  companyName: '',
  companySimpleName: '',
  contactNumber: '',
  createDeptId: '',
  createDeptName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  decisionItem: '',
  directorName: '',
  email: '',
  fax: '',
  id: '',
  invoiceAddress: '',
  overallEvaluation: '',
  performanceRating: '',
  postcode: '',
  processId: '',
  remark: '',
  scale: '',
  subcontractorNo: '',
  taskId: '',
  taxNumber: '',
  telephone: '',
  testAbility: '',
  updateTime: '',
  webAddress: '',
})
// 人员列表

const personRef = ref()
const personList = ref()
// 能力列表
const capacityList = ref()
const capacityRef = ref()
// 证书列表
const certificateRef = ref()
const certificateList = ref()
const radio = ref('基本信息')
// 表单1验证规则
const checkPhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/^1[3456789]\d{9}$/.test(value))) {
    callback(new Error('请输入正确手机号'))
  }
  else {
    callback()
  }
}
const checkEmail = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/.test(value))) {
    callback(new Error('请输入正确邮箱'))
  }
  else {
    callback()
  }
}
const checkPostcode = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/^[1-9]\d{5}$/.test(value))) {
    callback(new Error('请输入正确邮编'))
  }
  else {
    callback()
  }
}
const checkFax = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/^(\d{3,4}-)?\d{7,8}$/.test(value))) {
    callback(new Error('请输入正确传真'))
  }
  else {
    callback()
  }
}
const checkBankNumber = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/^(\d{3,4}-)?\d{7,8}$/.test(value))) {
    callback(new Error('请输入正确传真'))
  }
  else {
    callback()
  }
}
const rules = ref<FormRules>({
  subcontractorNo: [{ required: true, message: '分包方编号必填', trigger: ['blur', 'change'] }],
  companyName: [{ required: true, message: '单位名称必填', trigger: ['blur', 'change'] }],
  // companySimpleName: [{ required: true, message: '单位简称必填', trigger: ['blur', 'change'] }],
  // businessContent: [{ required: true, message: '业务内容必填', trigger: ['blur', 'change'] }],
  // scale: [{ required: true, message: '规模必选', trigger: ['blur', 'change'] }],
  // businessScale: [{ required: true, message: '业务规模必选', trigger: ['blur', 'change'] }],
  // performanceRating: [{ required: true, message: '履约评级必选', trigger: ['blur', 'change'] }],
  // overallEvaluation: [{ required: true, message: '整体评价必选', trigger: ['blur', 'change'] }],
  // taxNumber: [{ required: true, message: '税号必填', trigger: ['blur', 'change'] }],
  // bankAccount: [{ required: true, message: '银行账户名必填', trigger: ['blur', 'change'] }],
  // bankNumber: [{ required: false, validator: checkEmail, trigger: ['blur', 'change'] }],
  postcode: [{ required: false, validator: checkBankNumber, trigger: ['blur', 'change'] }],
  // directorName: [{ required: true, message: '联系人必填', trigger: ['blur', 'change'] }],
  // contactNumber: [{ required: true, message: '联系电话必填', trigger: ['blur', 'change'] }],
  fax: [{ required: false, validator: checkFax, trigger: ['blur', 'change'] }],
  telephone: [{ required: false, validator: checkPhone, trigger: ['blur', 'change'] }],
  email: [{ required: false, validator: checkEmail, trigger: ['blur', 'change'] }],
  // address: [{ required: true, message: '地址必填', trigger: ['blur', 'change'] }],
  // invoiceAddress: [{ required: true, message: '开票用地址必填', trigger: ['blur', 'change'] }],
  // testAbility: [{ required: true, message: '测试能力必填', trigger: ['blur', 'change'] }],
})

// 获取下拉框数据
const companySize = ref<{ id: string; value: string; name: string }[]>() // 规模
const businessSize = ref<{ id: string; value: string; name: string }[]>() // 业务规模
const performance = ref<{ id: string; value: string; name: string }[]>() // 履约评级
const evaluation = ref<{ id: string; value: string; name: string }[]>() // 整体评价
const fetchSelectData = () => {
  // 规模
  getDictByCode('eqptCompanySize').then((res) => {
    companySize.value = res.data
  })
  // 业务规模
  getDictByCode('eqptBusinessSize').then((res) => {
    businessSize.value = res.data
  })
  // 履约评级
  getDictByCode('eqptPerformanceRating').then((res) => {
    performance.value = res.data
  })
  // 整体评价
  getDictByCode('eqptOverallEvaluation').then((res) => {
    evaluation.value = res.data
  })
}
fetchSelectData()

// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string || 'detail'
  ruleFormRef.value?.resetFields()
  if (!$route.path.includes('create')) {
    const data = JSON.parse($route.query.row as string)
    getDetail({ id: data.id }).then((res) => {
      const data = res.data
      ruleForm.value = data.subcontractor
      personList.value = data.staffList
      capacityList.value = data.abilityList
      certificateList.value = data.certificateList
    })
  }
  if ($route.path.includes('create') || $route.path.includes('update')) {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
    ruleForm.value.createDeptId = userStore.deptId
    ruleForm.value.createDeptName = userStore.deptName
    // getUserDept().then((res) => {
    //   ruleForm.value.createDeptId = res.data.id
    //   ruleForm.value.createDeptName = res.data.fullName
    // })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  $router.back()
}

// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  Promise.all([formEl.validate()]).then(() => {
    // 验证表格
    if (capacityRef.value.checkCertificateList() && personRef.value.checkCertificateList()) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        const data = {
          subcontractor: ruleForm.value,
          abilityList: capacityRef.value.list, // 业务能力
          certificateList: [], // 分包证书
          staffList: personRef.value.list, // 分包人员
        }
        editDirectory(data, $route.query.statusName as string).then((res) => {
          submitId.value = res.data
          if (statusName === '已取消' || statusName === '未通过') {
            submitDirectory({ id: submitId.value, formId: SCHEDULE.SUBCONTRACTOR_APPROVAL }).then((res) => {
              ElMessage.success('已提交')
              close()
            })
          }
          if (statusName === '全部' && $route.path.includes('update')) {
            ElMessage.success('保存成功')
            close()
          }
          else {
            ElMessage.success('保存成功')
          }
        })
      })
    }
  })
}
// 提交
const submitForm = () => {
  if (submitId.value === '') {
    ElMessage.warning('请先保存')
    return false
  }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitDirectory({ id: submitId.value, formId: SCHEDULE.SUBCONTRACTOR_APPROVAL }).then((res) => {
      ElMessage.success('已提交')
      close()
    })
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
// 编辑
const editForm = () => {
  $router.push({
    path: '/directorypage/update',
    query: { ...$route.query },
  })
}
// 删除
const delForm = () => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteDirectory({ id: ruleForm.value.id }, $route.query.statusName as string).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
// 取消
const cancelForm = () => {
  ElMessageBox.confirm(
    '确认取消吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelDirectory({ 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 fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.value.attachments = ruleForm.value.attachments ? `${ruleForm.value.attachments},${res.data[0]}` : res.data[0]
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
// 上传
const upload = () => {
  fileRef.value.click()
}
// 删除上传的文件
const deleteFile = (fileName: string) => {
  const data = ruleForm.value.attachments.split(',')
  const filterData = data.filter(item => item !== fileName)
  ruleForm.value.attachments = filterData.length ? filterData.join(',') : ''
}
const print = () => {

}
defineExpose({ ruleForm, apply, editForm, submitForm, saveForm, delForm, print, cancelForm })
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page class="base-info-device" :title="`测试、校准或检定合格分包方名录-${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 !== '未通过' && (statusName === '全部' && $route.path.includes('create'))" type="primary" @click="submitForm()">
          提交
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus)" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </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-radio-group v-model="radio">
        <el-radio-button label="基本信息" />
        <el-radio-button label="分包方人员" />
        <el-radio-button label="业务能力" />
        <el-radio-button v-if="$route.query.statusName === '全部' && $route.path.includes('detail')" label="分包证书" />
        <el-radio-button v-if="$route.query.statusName !== '全部' && $route.query.statusName !== '草稿箱'" label="审批详情" />
      </el-radio-group>
    </detail-block-com>
    <!-- 基本信息 -->
    <div v-show="radio === '基本信息'">
      <detail-block-com>
        <el-form
          ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form"
          :class="[dialogStatus === 'detail' ? 'isDetail' : '']" :disabled="$route.path.includes('detail')"
        >
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="分包方编号" prop="subcontractorNo">
                <el-input v-model.trim="ruleForm.subcontractorNo" placeholder="分包方编号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位名称" prop="companyName">
                <el-input v-model.trim="ruleForm.companyName" placeholder="单位名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位简称" prop="companySimpleName">
                <el-input v-model.trim="ruleForm.companySimpleName" placeholder="单位简称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务内容" prop="businessContent">
                <el-input v-model.trim="ruleForm.businessContent" placeholder="业务内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="规模" prop="scale">
                <el-select v-model="ruleForm.scale" placeholder="选择规模" style="width: 100%;">
                  <el-option v-for="item in companySize" :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="businessScale">
                <el-select v-model="ruleForm.businessScale" placeholder="选择业务规模" style="width: 100%;">
                  <el-option v-for="item in businessSize" :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="performanceRating">
                <el-select v-model="ruleForm.performanceRating" placeholder="选择评级" style="width: 100%;">
                  <el-option v-for="item in performance" :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="overallEvaluation">
                <el-select v-model="ruleForm.overallEvaluation" placeholder="选择评价" style="width: 100%;">
                  <el-option v-for="item in evaluation" :key="item.id" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="税号" prop="taxNumber">
                <el-input v-model.trim="ruleForm.taxNumber" placeholder="请输入税号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行账户名" prop="bankAccount">
                <el-input v-model.trim="ruleForm.bankAccount" placeholder="请输入银行账户名" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行名称" prop="bankName">
                <el-input v-model.trim="ruleForm.bankName" placeholder="请输入银行名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行账号" prop="bankNumber">
                <el-input v-model.trim="ruleForm.bankNumber" placeholder="请输入银行账号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="邮编" prop="postcode">
                <el-input v-model.trim="ruleForm.postcode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="directorName">
                <el-input v-model.trim="ruleForm.directorName" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话" prop="contactNumber">
                <el-input v-model.trim="ruleForm.contactNumber" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="传真" prop="fax">
                <el-input v-model.trim="ruleForm.fax" placeholder="请输入传真" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="6">
              <el-form-item label="手机" prop="telephone">
                <el-input v-model.trim="ruleForm.telephone" placeholder="请输入手机" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model.trim="ruleForm.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="网址" prop="webAddress">
                <el-input v-model.trim="ruleForm.webAddress" placeholder="请输入网址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model.trim="ruleForm.address" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="开票用地址" prop="invoiceAddress">
                <el-input v-model.trim="ruleForm.invoiceAddress" placeholder="请输入开票用地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="测试能力" prop="testAbility">
                <el-input v-model.trim="ruleForm.testAbility" placeholder="请输入测试能力" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model.trim="ruleForm.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="24">
              <el-form-item label="附件" prop="attachments">
                <show-photo :minio-file-name="ruleForm.attachments" @delete="deleteFile" />
                <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
                <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload">
                  上传
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </detail-block-com>
    </div>
    <div v-show="radio === '分包方人员'">
      <person-table ref="personRef" :data="personList" :status="dialogStatus" />
    </div>
    <div v-show="radio === '业务能力'">
      <capacity-table ref="capacityRef" :data="capacityList" :status="dialogStatus" />
    </div>
    <div v-show="radio === '分包证书'">
      <certificate-table ref="certificateRef" :data="certificateList" :status="dialogStatus" />
    </div>
    <div v-if="radio === '审批详情'">
      <approval-record-table :process-id="ruleForm.processId" />
    </div>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      content: "";
      display: none;
    }
  }
}
</style>
