<script name="expertEnroll" setup>
import { getCurrentInstance, ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import BasicInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/basicInfo.vue'
import EduInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/eduInfo.vue'
import JobInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/jobInfo.vue'
import ProfessionalInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/professionalInfo.vue'
import RecommendInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/recommendInfo.vue'
import { expertEdit, expertSignUp, registration } from '@/http/apis/expertManage/expertStore'
import { downloadFileUrl } from '@/utils/uploadAction.js'
import { getExpertDetail } from '@/http/apis/expertManage/expertVerify'
import { getVerificationCode } from '@/http/apis/auth'
import getTimeDiffer from '@/utils/getTimeDiffer'
import ExpertOtherInfo from '@/pages/expertManage/expertStore/addOrEditExpert/components/expertOtherInfo.vue'
const { proxy } = getCurrentInstance(),
  route = useRoute(),
  router = useRouter(),
  formData = ref({
    basicInfo: {
      // isDingUser: false
    }
  }),
  collapseModal = ref(['1', '2', '3', '4', '5', '6']),
  basicInfoRef = ref(), // 基本信息
  eduInfoRef = ref(), // 学历信息
  jobInfoRef = ref(), // 职业信息
  professionalInfoRef = ref(), // 专业信息
  recommendInfoRef = ref(), // 推荐信息
  expertOtherInfoRef = ref(), // 其他信息
  // 提交
  submitForm = async () => {
    const form = []
    form.push(new Promise((resolve, reject) => {
      basicInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    form.push(new Promise((resolve, reject) => {
      eduInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    form.push(new Promise((resolve, reject) => {
      jobInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    form.push(new Promise((resolve, reject) => {
      professionalInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    form.push(new Promise((resolve, reject) => {
      recommendInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    form.push(new Promise((resolve, reject) => {
      expertOtherInfoRef.value.validForm((valid) => {
        if (valid) resolve()
      })
    }))
    Promise.all([...form]).then(async () => {
      saveData()
    }).catch(err => {
      if (err) {
        proxy.$message.warning(err)
      }
    })
  },
  saveData = async () => {
    var data = {
      expertUserId: route.query.id || undefined,
      basicInfo: {
        ...basicInfoRef.value.formData,
        // isDingUser: formData.value.basicInfo.isDingUser,
        avatarUrl: basicInfoRef.value.formData?.avatarFile?.fileId && await downloadFileUrl(basicInfoRef.value.formData.avatarFile.fileId),
        expertIntentionWorkRegions:
              basicInfoRef.value.formData.expertIntentionWorkRegions?.map((i, index) => ({
                regionName: i.unionCode?.join('@@'),
                regionCode: i.unionCode?.slice(-1)[0]?.split('##')[0],
                regionLevel: i.unionCode?.slice(-1)[0]?.split('##')[2]
              })),
        expertRegionInfo: {
          regionName: basicInfoRef.value.formData.expertRegionInfo?.join('@@'),
          regionCode: basicInfoRef.value.formData.expertRegionInfo?.slice(-1)[0].split('##')[0],
          regionLevel: basicInfoRef.value.formData.expertRegionInfo?.slice(-1)[0].split('##')[2]
        },
        political: basicInfoRef.value.formData.political && [basicInfoRef.value.formData.political] || [],
        expertSource: basicInfoRef.value.formData.expertSource && [basicInfoRef.value.formData.expertSource] || [],
        expertType: basicInfoRef.value.formData.expertType && [basicInfoRef.value.formData.expertType] || []
      },
      eduInfo: {
        ...eduInfoRef.value.formData,
        edu: eduInfoRef.value.formData.edu && [eduInfoRef.value.formData.edu],
        degree: eduInfoRef.value.formData.degree && [eduInfoRef.value.formData.degree],
        degreeCertificateFile: eduInfoRef.value.formData.degreeCertificateFile && await Promise.all(
          eduInfoRef.value.formData.degreeCertificateFile && eduInfoRef.value.formData.degreeCertificateFile.map(async i => {
            return {
              fileName: i.name,
              fileId: i.response.data.id,
              url: i.fileUrlById
            }
          })
        ) || [],
        graduationCertificateFile: eduInfoRef.value.formData.graduationCertificateFile && await Promise.all(
          eduInfoRef.value.formData.graduationCertificateFile && eduInfoRef.value.formData.graduationCertificateFile.map(async i => {
            return {
              fileName: i.name,
              fileId: i.response.data.id,
              url: i.fileUrlById
            }
          })
        ) || []
      },
      jobInfo: {
        ...jobInfoRef.value.formData,
        administrativeRank: jobInfoRef.value.formData.administrativeRank && [jobInfoRef.value.formData.administrativeRank] || [],
        jobStatus: jobInfoRef.value.formData.jobStatus && [jobInfoRef.value.formData.jobStatus] || [],
        companyAttribute: jobInfoRef.value.formData.companyAttribute && [jobInfoRef.value.formData.companyAttribute] || []
      },
      professionalInfo: {
        ...professionalInfoRef.value.formData,
        goodAt: professionalInfoRef.value.formData.goodAt && [professionalInfoRef.value.formData.goodAt] || [],
        titleLevel: professionalInfoRef.value.formData.titleLevel && [professionalInfoRef.value.formData.titleLevel] || [],
        titleCertificateFile: professionalInfoRef.value.formData.titleCertificateFile && await Promise.all(
          professionalInfoRef.value.formData.titleCertificateFile && professionalInfoRef.value.formData.titleCertificateFile.map(async i => {
            return {
              fileName: i.name,
              fileId: i.response.data.id,
              url: i.fileUrlById
            }
          })
        ) || [],
        technicalExpertise: professionalInfoRef.value.formData.technicalExpertise && professionalInfoRef.value.formData.technicalExpertise.map(i => {
          return {
            tagCode: i.split('##')[1],
            tagName: i.split('##')[0]
          }
        }),
        industrySector: professionalInfoRef.value.formData.industrySector && professionalInfoRef.value.formData.industrySector.map(i => {
          return {
            tagCode: i.split('##')[1],
            tagName: i.split('##')[0]
          }
        })
      },
      recommendInfo: {
        ...recommendInfoRef.value.formData,
        recommendedWay: recommendInfoRef.value.formData.recommendedWay && [recommendInfoRef.value.formData.recommendedWay] || [],
        recommendationProofFile: recommendInfoRef.value.formData.recommendationProofFile && await Promise.all(
          recommendInfoRef.value.formData.recommendationProofFile && recommendInfoRef.value.formData.recommendationProofFile.map(async i => {
            return {
              fileName: i.name,
              fileId: i.response.data.id,
              url: i.fileUrlById
            }
          })
        ) || []
      },
      expertOtherInfo: {
        ...expertOtherInfoRef.value.formData,
        other: expertOtherInfoRef.value.formData.other && expertOtherInfoRef.value.formData.other.map(i => {
          return {
            tagCode: i.split('##')[1],
            tagName: i.split('##')[0]
          }
        })
      }
    }
    if (route.name === 'expertEnroll') {
      showSmsDiaglog(data)
    } else {
      if (!route.query.id) {
        await expertSignUp(data)
        proxy.$message.success('专家新增成功')
        router.go(-1)
      } else {
        await expertEdit(data)
        proxy.$message.success('专家编辑成功')
        router.go(-1)
      }
    }
  },
  // 专家报名-短信验证
  smsDialogData = reactive({
    visible: false,
    data: {}
  }),
  showSmsDiaglog = (data) => {
    smsDialogData.data = data
    smsDialogData.visible = true
  },
  smsDialogFormRef = ref(),
  smsDialogForm = ref({
    verificationCode: ''
  }),
  smsDialogRules = {
    'verificationCode': [{ required: true, message: '请输入' }]
  },
  smsDialogLoading = ref(false),
  submitSms = async (formEl) => {
    if (!formEl) {
      return
    }
    formEl.validate(async (valid) => {
      if (valid) {
        await registration({
          ...smsDialogData.data,
          verificationCode: smsDialogForm.value.verificationCode
        })
        proxy.$message.success('提交成功')
        router.go(0)
      }
    }
    )
  },
  timer = ref(null),
  count = ref(0),
  getVerificationCodeFunc = async () => {
    await getVerificationCode({ mobile: basicInfoRef.value.formData.phoneNo, verificationType: 'EXPERT_REGISTER' })
    proxy.$message.success('验证码已发送')
    const TIME_COUNT = 60
    if (!timer.value) {
      count.value = TIME_COUNT
      timer.value = setInterval(() => {
        if (count.value > 0 && count.value <= TIME_COUNT) {
          count.value--
        } else {
          clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)
    }
  },
  // 获取详情
  getDetail = async () => {
    const res = await getExpertDetail({ expertUserId: route.query.id })
    basicInfoRef.value.setFormData(res.data.basicInfo)
    eduInfoRef.value.setFormData(res.data.eduInfo)
    jobInfoRef.value.setFormData(res.data.jobInfo)
    professionalInfoRef.value.setFormData(res.data.professionalInfo)
    recommendInfoRef.value.setFormData(res.data.recommendInfo)
    expertOtherInfoRef.value.setFormData(res.data.expertOtherInfo)
  },
  // 是否失效
  isFailure = ref(false),
  getIsFailure = () => {
    const time = window.atob(route.query.time)
    if (getTimeDiffer(new Date(), new Date(time * 1), 'd') > 3) {
      isFailure.value = true
    }
  }
onMounted(() => {
  if (route.query.time) {
    getIsFailure()
    setInterval(() => {
      getIsFailure()
    }, 10000)
  } else {
    isFailure.value = true
  }
  if (route.query.id) {
    getDetail()
  }
})
</script>

<template>
  <div class="expertEnroll footerPage" :class="{ 'relative':route.path === 'expertEnroll'}">
    <div class="top">丽水市信息化专家报名</div>
    <template v-if="!isFailure">
      <div class="px-[107px] mt-[-60px]">
        <el-collapse v-model="collapseModal">
          <el-collapse-item name="1" class="mb-16">
            <template #title>
              <div class="collapse-title">基本信息</div>
            </template>
            <div class="pb-24">
              <basic-info ref="basicInfoRef" :basic-info="formData.basicInfo" />
            </div>
          </el-collapse-item>
          <el-collapse-item name="2" class="mb-16">
            <template #title>
              <div class="collapse-title">学历信息</div>
            </template>
            <div class="pb-24">
              <edu-info ref="eduInfoRef" />
            </div>
          </el-collapse-item>
          <el-collapse-item name="3" class="mb-16">
            <template #title>
              <div class="collapse-title">职业信息</div>
            </template>
            <div class="pb-24">
              <job-info ref="jobInfoRef" />
            </div>
          </el-collapse-item>
          <el-collapse-item name="4" class="mb-16">
            <template #title>
              <div class="collapse-title">专业信息</div>
            </template>
            <div class="pb-24">
              <professional-info ref="professionalInfoRef" />
            </div>
          </el-collapse-item>
          <el-collapse-item name="5" class="mb-16">
            <template #title>
              <div class="collapse-title">推荐信息</div>
            </template>
            <div class="pb-24">
              <recommend-info ref="recommendInfoRef" />
            </div>
          </el-collapse-item>
          <el-collapse-item name="6" class="mb-16">
            <template #title>
              <div class="collapse-title">其他信息</div>
            </template>
            <div class="pb-24">
              <expert-other-info ref="expertOtherInfoRef" />
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div class="footer">
        <el-button
          type="primary"
          @click="submitForm"
        >
          提交
        </el-button>
        <el-button @click="router.go(-1)">取消</el-button>
      </div>
    </template>
    <template v-else>
      <img src="@/assets/images/link-failure-img.png" style="width: 320px;height: 245px;margin: 160px auto 0" />
      <p style="color: #83868C;" class="mt-32 text-19 text-center">链接已失效，请联系管理员</p>
    </template>
    <el-dialog
      :model-value="smsDialogData.visible"
      title="短信验证"
      width="400px"
      destroy-on-close
      @close="smsDialogData.visible=false"
    >
      <el-form
        ref="smsDialogFormRef"
        :model="smsDialogForm"
        :rules="smsDialogRules"
        label-width="auto"
        label-suffix=":"
      >
        <el-form-item label="手机号">
          <span>{{ basicInfoRef.formData.phoneNo }}</span>
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="smsDialogForm.verificationCode" placeholder="请输入验证码">
            <template #suffix>
              <a v-if="!count" class="itemBlue" @click="getVerificationCodeFunc"> 获取验证码</a>
              <span v-else class="itemBlue">{{ count }}</span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          :loading="smsDialogLoading"
          @click="submitSms(smsDialogFormRef)"
        >
          提交
        </el-button>
        <el-button
          @click="smsDialogData.visible=false"
        >
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
.expertEnroll{
  .top{
    background: url("@/assets/images/expertTopBg.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding-top: 60px;
    padding-bottom: 117px;
    font-size: 53px;
    font-weight: 600;
    color: #FFFFFF;
    text-align: center;
    line-height: 75px;
  }
  .header{
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    margin-bottom: 15px;
    font-size: 20px;
  }
  :deep(.el-collapse) {
    .el-collapse-item__header {
      padding: 0px 16px;
      font-size: 14px;
    }
    .el-collapse-item__content {
      padding: 16px 16px 16px 0px;
      // margin-left: -50px;
    }
    .el-collapse-item__header.is-active {
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }
    .collapse-title {
      flex: 1 0 90%;
      order: 1;
      .el-collapse-item__header {
        flex: 1 0 auto;
        order: -1;
      }
      .el-input-number {
        width: 150px !important;
      }
    }
  }
}

</style>
