<script name="basicInfo" setup>
import { onMounted, ref } from 'vue'
import store from '@/store'
import { storeToRefs } from 'pinia'
import { districtList } from '@/http/apis/commonApi'
import { fileFormatVerification, downloadFileUrl } from '@/utils/uploadAction.js'
import { zzdInfo } from '@/http/apis/expertManage/expertStore'
const uploadUrl = store.dictStore.uploadUrl,
  userInfo = storeToRefs(store.userStore).userInfo,
  { nationList } = store.dictStore.globalDicts,
  { tagList } = storeToRefs(store.dictStore),
  formData = ref({
    expertIntentionWorkRegions: [{}], // 履职意向
    avatarFile: { fileId: '' }
  }),
  formRef = ref(),
  // 手机号码校验
  checkTelPhone = (rule, value, callback) => {
    if (value === '') {
      return callback(new Error('请输入正确的手机号'))
    } else {
      const regIdCard =
            /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regIdCard.test(value)) {
        callback()
      } else {
        return callback(new Error('请输入正确的手机号'))
      }
    }
  },
  idCardValidator = (rule, value, callback) => {
    const _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
    // 校验身份证：
    if (!(_IDRe18.test(value) || _IDre15.test(value))) {
      callback('请输入正确格式')
    } else {
      callback()
    }
  },
  rules = {
    phoneNo: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: checkTelPhone, trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'blur' }
    ],
    hometown: [
      { required: true, message: '请选择籍贯', trigger: 'blur' }
    ],
    nationality: [
      { required: true, message: '请选择民族', trigger: 'blur' }
    ],
    political: [
      { required: true, message: '请选择政治面貌', trigger: 'blur' }
    ],
    idCard: [
      { required: true, message: '请输入正确的身份证号', trigger: 'blur' },
      { validator: idCardValidator, tigger: 'blur' }
    ],
    birth: [
      { required: true, message: '请选择出生年月', trigger: 'blur' }
    ],
    bankNo: [
      { required: true, message: '请输入银行卡号', trigger: 'blur' }
    ],
    bank: [
      { required: false, message: '请输入开户行', trigger: 'blur' }
    ],
    email: [
      { required: false, message: '请输入电子邮箱', trigger: 'blur' },
      {
        pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
        message: '请输入正确邮箱',
        trigger: 'blur'
      }
    ],
    expertSource: [
      {
        required: true,
        trigger: 'change',
        message: '请选择专家来源'
      }
    ],
    expertRegionInfo: [
      {
        required: true,
        trigger: 'change',
        message: '请选择专家级别'
      }
    ],
    expertIntentionWorkRegions: [
      {
        required: true,
        trigger: 'change',
        message: '请选择履职意向'
      }
    ],
    expertType: [
      { required: true, message: '请选择专家类型', trigger: 'blur' }
    ],
    avatarUrl: [
      {
        required: true,
        message: '请上传免冠照'
      }
    ]
  },
  // 校验
  validForm = (callback) => {
    formRef.value.validate(valid => {
      callback(valid)
    })
  },
  // 回显
  setFormData = async (data) => {
    formData.value = {
      ...data,
      political: data.political?.[0] || undefined,
      expertSource: data.expertSource?.[0] || undefined,
      expertType: data.expertType?.[0] || undefined,
      expertRegionInfo: data.expertRegionInfo.regionName?.split('@@').slice(1),
      expertIntentionWorkRegions: data.expertIntentionWorkRegions?.map(i => { return { unionCode: i.regionName.split('@@').slice(1) } }),
      avatarUrl: data?.avatarFile?.fileId && await downloadFileUrl(data.avatarFile.fileId),
      avatarFile: data?.avatarFile || { fileId: '' }
    }
  },
  regionTree = ref(),
  // 增加或删除履职意向
  updateWorkRegions = (type, index) => {
    if (type === 'add') {
      formData.value.expertIntentionWorkRegions.push({
        id: new Date().getTime()
      })
    } else {
      formData.value.expertIntentionWorkRegions.splice(index, 1)
    }
  },
  // 上传免冠照
  handleAvatarSuccess = res => {
    formData.value.avatarFile['fileId'] = res.data.id
    downloadFileUrl(res.data.id).then(res => {
      formData.value.avatarUrl = res
    })
  },
  // 获取浙政钉信息
  getZzdInfo = async () => {
    const res = await zzdInfo({ phoneNo: formData.value.phoneNo })
    formData.value.isDingUser = res.data.isDingUser
    if (res.data.isDingUser) {
      formData.value.name = res.data.name
    }
  }
defineExpose({ validForm, formData, setFormData })
onMounted(async () => {
  const res = await districtList({ regionCode: 330500, regionLevel: 2 })
  regionTree.value = [res.data]
})
</script>
<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-position="right"
    label-width="120px"
    label-suffix=":"
    scroll-to-error
    class="basicInfo"
  >
    <el-row :gutter="8">
      <el-col :span="8">
        <el-form-item
          label="手机号"
          prop="phoneNo"
        >
          <el-input
            v-model="formData.phoneNo"
            placeholder="请输入"
            :maxlength="11"
            :disabled="!!$route.query.id||$route.name==='selfEditExpertInfo'"
            @blur="getZzdInfo"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="姓名"
          prop="name"
        >
          <el-input
            v-model="formData.name"
            placeholder="请输入"
            :disabled="!!$route.query.id||$route.name==='selfEditExpertInfo'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="性别"
          prop="gender"
        >
          <el-select
            v-model="formData.gender"
            class="w-full"
            placeholder="请选择"
          >
            <el-option value="1" label="男" />
            <el-option value="0" label="女" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="籍贯"
          prop="hometown"
        >
          <el-input
            v-model="formData.hometown"
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="民族"
          prop="nationality"
        >
          <el-select
            v-model="formData.nationality"
            class="m-2 w-full"
            placeholder="请选择"
          >
            <el-option
              v-for="item in nationList"
              :key="item.id"
              :label="item.info"
              :value="item.info"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="政治面貌"
          prop="political"
        >
          <el-select
            v-model="formData.political"
            class="w-full"
            placeholder="请选择"
            value-key="dictionaryCode"
          >
            <el-option
              v-for="(item,index) in store.dictStore.politicalDict"
              :key="index"
              :label="item.dictionaryName"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="身份证"
          prop="idCard"
        >
          <el-input
            v-model="formData.idCard"
            placeholder="请输入"
            :maxlength="18"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="办公电话"
          prop="officePhone"
        >
          <el-input
            v-model="formData.officePhone"
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="出生年月"
          prop="birth"
        >
          <el-date-picker
            v-model="formData.birth"
            type="month"
            placeholder="请选择"
            format="YYYY-MM"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="银行卡号"
          prop="bankNo"
        >
          <el-input
            v-model="formData.bankNo"
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="开户银行"
          prop="bank"
        >
          <el-input
            v-model="formData.bank"
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="电子邮箱"
          prop="email"
        >
          <el-input
            v-model="formData.email"
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="false" :span="8">
        <el-form-item
          label="入库意向"
          prop="expertSource"
        >
          <el-select
            v-model="formData.expertSource"
            class="w-full"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(item,index) in tagList &&
                tagList.length &&
                tagList.find(i => i.tagCode === 'expert_source')
                  .children"
              :key="index"
              :label="item.tagName"
              :value="item.unionCode"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="专家级别"
          prop="expertRegionInfo"
        >
          <el-cascader
            v-model="formData.expertRegionInfo"
            :options="regionTree"
            :props="{
              value: 'unionCode',
              label: 'name'
            }"
            clearable
            placeholder="请选择"
            class="w-full"
            :disabled="$route.name==='selfEditExpertInfo'||$route.query.id&&userInfo.regionCode!==formData?.expertRegionInfo?.[formData.expertRegionInfo?.length-1].split('##')[0]"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="专家来源"
        >
          <el-select
            v-model="formData.expertSource"
            class="w-full"
            placeholder="请选择"
            clearable
            value-key="tagCode"
          >
            <el-option
              v-for="(item,index) in store.dictStore.expertSourceDict"
              :key="index"
              :label="item.tagName"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="专家类型"
          prop="expertType"
        >
          <el-select
            v-model="formData.expertType"
            class="w-full"
            placeholder="请选择"
            value-key="dictionaryCode"
          >
            <el-option
              v-for="(item,index) in store.dictStore.expertTypeDict"
              :key="index"
              :label="item.dictionaryName"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          label="履职意向"
          prop="expertIntentionWorkRegions"
        >
          <el-row
            v-for="(item, index) in formData
              .expertIntentionWorkRegions"
            :key="item.id"
            class="intention-item w-full"
          >
            <el-col :span="24">
              <el-cascader
                v-model="
                  formData.expertIntentionWorkRegions[index]
                    .unionCode
                "
                :options="regionTree"
                :props="{
                  value: 'unionCode',
                  label: 'name'
                }"
                clearable
                style="width: 100%"
                class="mb-4"
              />
              <span
                v-if="index > 0"
                style="position: absolute; right: -20px"
                @click="updateWorkRegions('del', index)"
              >
                <el-icon>
                  <Delete color="#D40000" />
                </el-icon>
              </span>
            </el-col>
          </el-row>
          <p class="addGhostBtn mt-8 w-full">
            <el-button
              class="w-full"
              type="primary"
              plain
              style="margin: 0"
              @click="updateWorkRegions('add')"
            >
              + 增加履职意向地区
            </el-button>
          </p>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          class="avatarForm"
          label="一寸免冠照"
          prop="avatarUrl"
          style="margin-bottom: 32px"
        >
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="
              file =>
                fileFormatVerification(file, {
                  size: 500,
                  types: ['png', 'jpg', 'jpeg']
                })
            "
            accept="image/png,image/jpeg"
          >
            <img
              v-if="formData.avatarUrl"
              :src="formData.avatarUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon">
              <el-icon><Camera /></el-icon>
            </i>
          </el-upload>
          <div class="limit-name ml-4">请上传蓝底1寸免冠照片，小于500Kb</div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<style lang="less">
.basicInfo{
  .avatarForm {
    :deep(.el-form-item__content) {
      display: block;
    }
  }
  .avatar-uploader {
    .el-upload {
      background: #edf4ff;
      border-radius: 4px;
      border: 1px dashed #007df1;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409eff;
      }
    }
    .avatar-uploader-icon {
      border-radius: 4px;
      border: 1px dashed #007df1;
      font-size: 28px;
      color: #007df1;
      width: 104px;
      height: 104px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .avatar {
      width: 80px;
      height: 80px;
      display: block;
    }
  }
  .limit-name {
    margin-top: 13px;
    color: #999999;
    font-size: 12px;
  }
}
</style>
