<template>
  <div class="father">
    <!--<van-cell-group inset class="mar-auto15">
      <van-field class="van-field__label_rectangle" label-width="400px" label="哈尔滨师范大学评卷信息填报" type="hidden" />
    </van-cell-group>-->
    <van-form @submit="onSubmit">
      <div class="head-cg">
          <img src="@/assets/Ui/信息/个人信息/个人信息.svg" />
        </div>
      <van-cell-group inset style="background-color: transparent;">
        <van-field
          v-model="notLocalTeacher.userName"
          name="userName"
          label="姓名"
          type="text"
          placeholder="请输入姓名"
          :rules="[{ validator: userName, message: '请正确输入姓名' }]"
        >
          <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/姓名.svg"
            style="width: 16px; height: 16px;"
            />
          </template>
      </van-field>
        <van-field
          v-model="notLocalTeacher.identityId"
          name="userCardId"
          label="身份证号"
          type="text"
          placeholder="请输入身份证号"
          :rules="[{ validator: userCardId, message: '请输入身份证号' }]"
        >
        <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/身份证号.svg"
            style="width: 16px; height: 16px;"
            />
          </template>
      </van-field>
        <van-field v-model="notLocalTeacher.sex" readonly name="picker" label="性别">

          <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/性别.svg"
            style="width: 16px; height: 16px;"
            />
          </template>

        </van-field>
        <van-field readonly v-model="notLocalTeacher.age" name="age" label="年龄" type="text">
          <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/年龄.svg"
            style="width: 16px; height: 16px;"
            />
          </template>

        </van-field>


        <!--        <van-field-->
        <!--            v-model="notLocalTeacher.identityId"-->
        <!--            name="userCardId"-->
        <!--            label="身份证号"-->
        <!--            type="text"-->
        <!--            placeholder="请输入身份证号"-->
        <!--            :rules="[{ validator:userCardId, message: '请输入身份证号' }]"-->
        <!--        />-->
        <van-field
          v-model="notLocalTeacher.phone"
          name="phone"
          label="手机号"
          type="number"
          placeholder="请输入手机号"
          :rules="[{ validator: phoneNum, message: '请输入手机号' }]"
        >
        <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/手机号.svg"
            style="width: 16px; height: 16px;"
            />
          </template>
      
      </van-field>

        <van-field
          v-model="notLocalTeacher.jobTitle"
          is-link
          readonly
          name="picker"
          label="职称"
          placeholder="点击选择职称"
          @click="showPicker = true"
          :rules="[{ required: true, message: '请选择职称' }]"
        >
        <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/职称.svg"
            style="width: 16px; height: 16px;"
            />
          </template>

      </van-field>
        <van-popup v-model:show="showPicker" position="bottom">
          <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
        </van-popup>

        <van-field
          v-model="notLocalTeacher.office"
          name="office"
          label="职务"
          type="text"
          placeholder="请输入职务（如教师，教务主任）"
          :rules="[{ required: true, message: '请输入职务' }]"
        >
        <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/职务.svg"
            style="width: 16px; height: 16px;"
            />
          </template>

      </van-field>
      </van-cell-group>
      <div class="head-cg">
          <img src="@/assets/Ui/信息/个人信息/工作单位.svg" />
        </div>
      <van-cell-group inset class="mar-auto15" style="background-color: transparent;">
        <!--<van-field class="van-field__label1——circle" label-width="400px" label="工作单位" type="hidden" />-->
        <van-field
          v-model="notLocalTeacher.workName"
          name="workName"
          label="单位名称"
          type="text"
          placeholder="请输入单位名称"
          :rules="[{ required: true, message: '请输入单位名称' }]"
        >

        <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/单位名称.svg"
            style="width: 16px; height: 16px;"
            />
          </template>
      </van-field>
        <van-field v-model="notLocalTeacher.workPhone" name="workPhoen" label="单位电话" type="text" placeholder="电话/固定电话(选填)" >
          <template #left-icon>
            <img 
            src= "@/assets/Ui/信息/个人信息/图标/单位电话.svg"
            style="width: 16px; height: 16px;"
            />
          </template>
        </van-field>

      </van-cell-group>

      <div style="margin: 16px">
        <!--<van-button style="background-color: #8d2328; border: none; font-weight: 600" round block type="primary" native-type="submit">-->
          <!--下一步
        </van-button>-->
        <button style="background-color: transparent; width: 100%; border: none; display: flex; justify-content: flex-end;" native-type="submit">
          <img 
            src="@/assets/Ui/信息/个人信息/下一页.svg" 
            style="width: 35%; "
            alt="下一步">
        </button>
      </div>
    </van-form>
  </div>
</template>
<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store';

  const router = useRouter();
  const store = useUserStore();

  let notLocalTeacher = reactive({
    userName: '',
    phone: '',
    sex: '',
    age: '',
    identityId: '',
    jobTitle: '',
    office: '',
    workName: '',
    workPhone: '',
    openId: store.getOpenId,
    userId: store.getUserId,
  });

  const showPicker = ref(false);
  const showSex = ref(false);
  const columns = [
    { text: '正高级教师', value: 'Hangzhou' },
    { text: '高级教师', value: 'Ningbo' },
    { text: '一级教师', value: 'Wenzhou' },
    { text: '二级教师', value: 'Shaoxing' },
  ];

  // 校验表单
  const userName = (value: any) => {
    const reg = /^.{2,12}$/;
    return reg.test(value);
  };
  const jobTitleTest = (value: any) => {
    if (value.length > 0) {
      return false;
    }
    return true;
  };
  // 身份证验证
  // const userCardId = (value: any) => {
  //   const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  //  let birthday = value.substring(6, 10) + "-" + value.substring(10, 12) + "-" + value.substring(12, 14)
  //   let age = calculateAge(birthday);
  //   notLocalTeacher.age=age
  //   notLocalTeacher.sex=getSex(value)
  //   return reg.test(value);
  // };

  // 计算年龄的函数
  function calculateAge(birthday: string) {
    const today = new Date();
    const birthDate = new Date(birthday);
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();

    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }

    return age || '';
  }

  /**
   * @description : 校验身份证号是否合规（18位、15位）
   * @param        {String|Number} value
   * @return       {Boolean} true-合规 false-不合规
   */
  function userCardId(value) {
    let psidno = String(value);
    psidno = psidno.toUpperCase();
    // 1.校验身份证号格式和长度
    const regPsidno =
      /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[X])$)$/;
    if (!regPsidno.test(psidno)) {
      notLocalTeacher.age = '';
      notLocalTeacher.sex = '';
      return false;
    }
    // 2.校验前两位的省份编码是否正确
    const province = {
      11: '北京',
      12: '天津',
      13: '河北',
      14: '山西',
      15: '内蒙古',
      21: '辽宁',
      22: '吉林',
      23: '黑龙江 ',
      31: '上海',
      32: '江苏',
      33: '浙江',
      34: '安徽',
      35: '福建',
      36: '江西',
      37: '山东',
      41: '河南',
      42: '湖北 ',
      43: '湖南',
      44: '广东',
      45: '广西',
      46: '海南',
      50: '重庆',
      51: '四川',
      52: '贵州',
      53: '云南',
      54: '西藏 ',
      61: '陕西',
      62: '甘肃',
      63: '青海',
      64: '宁夏',
      65: '新疆',
      71: '台湾',
      81: '香港',
      82: '澳门',
      91: '国外',
    };
    if (!province[Number(psidno.slice(0, 2))]) {
      notLocalTeacher.age = '';
      notLocalTeacher.sex = '';
      return false;
    }
    // 3.校验出生日期
    if (psidno.length === 15) {
      // 15位号码 省（2位）市（2位）县（2位）年（2位）月（2位）日（2位）校验码（3位）
      const reg = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
      const arrSplit = psidno.match(reg);
      // 15位号码在年份前补 19 或 20
      const year = Number(arrSplit[2].charAt(0)) > 0 ? '19' + arrSplit[2] : '20' + arrSplit[2];
      const month = arrSplit[3];
      const day = arrSplit[4];
      if (!validateBirthday(year, month, day)) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
    } else if (psidno.length === 18) {
      // 18位号码 省（2位）市（2位）县（2位）年（4位）月（2位）日（2位）校验码（4位）
      const reg = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
      const arrSplit = psidno.match(reg);
      const year = arrSplit[2];
      const month = arrSplit[3];
      const day = arrSplit[4];
      if (!validateBirthday(year, month, day)) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
    } else {
      notLocalTeacher.age = '';
      notLocalTeacher.sex = '';
      return false;
    }
    // 校验出生日期是否合理
    function validateBirthday(year, month, day) {
      year = Number(year); // 年
      month = Number(month); // 月
      day = Number(day); // 日
      const nowTime = new Date().getTime(); // 当前时间戳
      const birthTime = new Date(`${year}-${month}-${day}`).getTime(); // 获取出生日期的时间戳
      // 不能是明天出生的吧
      if (birthTime > nowTime) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
      // 一般人活不到150岁吧
      const nowYear = new Date().getFullYear();
      if (nowYear - year > 150) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
      // 不能是13月出生的吧
      if (month < 1 || month > 12) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
      // 不能是2月30号、4月31号、5月32号出生的吧
      const date = new Date(year, month, 0); // 获取当月的最后一天
      if (day < 1 || day > date.getDate()) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
      return true;
    }
    // 4.18位号码校验生成的校验码
    if (psidno.length === 18) {
      const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
      const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码
      let sum = 0;
      for (let i = 0; i < 17; i++) {
        sum += Number(psidno.charAt(i)) * Wi[i];
      }
      if (parity[sum % 11] !== psidno[17]) {
        notLocalTeacher.age = '';
        notLocalTeacher.sex = '';
        return false;
      }
    }

    let birthday = value.substring(6, 10) + '-' + value.substring(10, 12) + '-' + value.substring(12, 14);
    let age = calculateAge(birthday);
    notLocalTeacher.age = age;
    notLocalTeacher.sex = getSex(value);
    return true;
  }

  // 获取性别
  function getSex(value: string) {
    if (value.length < 17) {
      return '';
    }
    let sex = value.substr(16, 1);
    if (sex !== '' || sex !== undefined) {
      if (parseInt(sex) % 2 == 1) {
        return '男';
      } else {
        return '女';
      }
    }
  }

  const phoneNum = (value: string) => {
    const reg = /^.{11}$/;
    return reg.test(value);
  };
  const onConfirm = ({ selectedOptions }) => {
    notLocalTeacher.jobTitle = selectedOptions[0]?.text;
    showPicker.value = false;
  };

  const onConfirmSex = ({ selectedOptions }) => {
    notLocalTeacher.sex = selectedOptions[0]?.text;
    showSex.value = false;
  };
  const onSubmit = (values: object) => {
    console.log('submit', values);
    localStorage.setItem('notLocalTeacher', JSON.stringify(notLocalTeacher));
    router.push('/waiTeacherTwo');
  };

  //
  // eslint-disable-next-line no-undef
  onMounted(() => {
    // console.log("组件挂在了")
    const notLocalTeacherStr = localStorage.getItem('notLocalTeacher');
    if (notLocalTeacherStr == null) {
      // console.log("数据空")
    } else {
      const storedData = JSON.parse(notLocalTeacherStr);
      Object.assign(notLocalTeacher, storedData);
      console.log(notLocalTeacher);
    }
  });
</script>
<style scoped lang="scss">

  .father {
    height: 100vh;
    background-color: #efefef;
    padding-top: 20px;
    background-image: url('@/assets/Ui/信息/个人信息/背景.svg');
    background-repeat: no-repeat;
    background-size: cover; /* 修改这里 */
  }

  .mar-auto15 {
    margin: 15px 30px;
  }

  .van-field__label_rectangle {
    position: relative;
    font-size: 1rem; /* 调整为您所需的字体大小 */
  }

  .van-field__label1——circle {
    position: relative;
    font-size: 1rem; /* 调整为您所需的字体大小 */
  }

  .van-field__label_rectangle:before {
    content: '';
    position: absolute;
    top: 30%;
    left: 5px;
    display: inline-block;
    height: 20px;
    width: 5px;
    background-color: #8d2328;
    border-radius: 8px;
  }

  .van-field__label1——circle:before {
    content: '';
    position: absolute;
    top: 50%;
    left: 5px;
    display: inline-block;
    height: 5px;
    width: 5px;
    background-color: #8d2328;
    border-radius: 50%;
  }
  .head-cg {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      width: 50%;
      margin-top: 5vh;
      margin-bottom: 2vh;
    }
  }
</style>
