<template>
  <!-- 注册 -->
  <div class="flex-col registerPage">
    <s-header :name="$t('register.header')" :noback="false"></s-header>
    <div class="registerFormBox">
      <van-form @submit="registerSubmit">
        <!-- 账号昵称 -->
        <van-field v-model="userName" name="userName" label="账号昵称" :placeholder="$t('register.usernamePlaceholder')"
          :rules="[{ pattern: /^[a-zA-Z0-9]+$/, message: $t('register.usernameRequired') }]" />
        <br>
        <!-- <van-field v-model="actualName" name="actualName" :label="$t('register.nameLabel')" placeholder="请输入真实姓名"
          :rules="[{ required: true, message: '请输入真实姓名' }]" />
        <br> -->
        <div>
          <!-- 登录手机 -->
          <van-field v-model="phone" name="phone" type="tel" label="登录手机" :placeholder="$t('register.phonePlaceholder')"
            :rules="[{ required: true, pattern: /^1[3456789]\d{9}$/, message: $t('register.phoneRequired') }]" />
          <br />
          <!-- 短信验证码 -->
          <van-field v-model="code" name="code" :label="$t('register.codeLabel')"
            :placeholder="$t('register.codePlaceholder')"
            :rules="[{ required: true, message: $t('register.codeRequired') }]">
            <template #button>
              <van-button size="small" type="primary" @click="seedVerCode()"
                :disabled="time !== 0 || phone.length === 0" :loading=reqApi :loading-text="$t('register.sending')">{{
      time === 0 ?
        $t('register.seedVerCode') : time + $t('register.replaysInSeconds')
    }}
              </van-button>
            </template>
          </van-field>
        </div><br />
        <van-field v-model="password" name="password" type="password" :label="$t('register.passwordLabel')"
          :placeholder="$t('register.passwordPlaceholder')"
          :rules="[{ required: true, message: $t('register.passwordRequired') }]" />
        <br>
        <van-field v-model="passwordCheck" name="passwordCheck" type="password"
          :label="$t('register.passwordCheckLabel')" :placeholder="$t('register.passwordCheckPlaceholder')"
          :rules="[{ required: true, message: $t('register.passwordCheckRequired') }]" />
        <br>
        <van-field v-model="identityCard" name="identityCard" label="身份证号" placeholder="请输入身份证号码"
          :rules="[{ validator, message: '请输入合法的身份证号码' }]" /><br />
        <!-- 支付宝账号 payeeCode 不可修改 -->
        <van-field v-model="payeeCode" name="payeeCode" label="支付宝账号" placeholder="请输入支付宝账号(不可修改)"
          :rules="[{ required: true, message: '请输入支付宝账号' }]" />
        <br />
        <!-- 银行卡号 cardNo 不可修改 -->
        <van-field v-model="cardNo" name="cardNo" label="银行卡号" placeholder="请输入银行卡号(不可修改)"
          :rules="[{ required: true, message: '请输入银行卡号' }]" />
        <br />

        <!-- 邮箱地址 -->
        <van-field v-model="email" name="email" label="邮箱地址" placeholder="请输入邮箱地址"
          :rules="[{ required: true, message: '请输入邮箱地址' }]" /><br />

        <!-- 入职日期 hireDate -->
        <van-field v-model="hireDate" is-link readonly name="hireDate" label="入职日期" placeholder="请选择入职日期"
          @click="showPicker = true" />
        <van-popup v-model:show="showPicker" position="bottom">
          <van-date-picker @confirm="onConfirm" @cancel="showPicker = false"></van-date-picker>
        </van-popup>
        <br />
        <!-- 部门dept-岗位job -->
        <van-field v-model="deptName" is-link readonly label="部门岗位" placeholder="请选择部门-岗位" @click="show = true" />
        <van-popup v-model:show="show" round position="bottom">
          <van-cascader v-model="jobName" title="请选择部门-岗位" :options="options" @close="show = false"
            @finish="onFinish" />
        </van-popup><br />

        <!-- 提交验证信息 -->
        <van-button round type="primary" class="register" native-type="submit">{{
      $t('register.registerButton')
          }}
        </van-button>
        <br />
        <div>
          <template></template>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import md5 from 'js-md5';
import { ref, onMounted, reactive, toRefs } from 'vue';
import { showFailToast, showToast } from 'vant';
import { sentRegisterCode, addUserApply } from '@/service/login/register';
import sHeader from '@/components/SimpleHeader';
import logiLogoImgUrl from "@/assets/login/logo.png";
import { useRouter } from 'vue-router';
import { getLocal, setLocal, styleUrl } from '@/common/js/utils';
import { useI18n } from "vue-i18n";

export default {
  setup() {
    // 引入语言
    const { t } = useI18n();
    const active = ref(0);
    const userName = ref('');
    // const actualName = ref('');
    const password = ref('');
    const passwordCheck = ref('');
    const identityCard = ref('');
    const payeeCode = ref('');
    const cardNo = ref('');
    const phone = ref('');
    const code = ref('');
    const email = ref('');
    const hireDate = ref('');
    const verifyRef = ref(null);
    const verCodeTime = reactive({
      time: 0
    });

    const deptId = ref('');
    const jobId = ref('');
    const show = ref(false);
    const deptName = ref('');
    const jobName = ref('');
    // 选项列表，children 代表子选项，支持多级嵌套
    const options = [
      {
        text: '营销部',
        value: '1',
        children: [
          { text: '营销业务员', value: '3' },
          { text: '营销助理', value: '4' },
          { text: '营销其他', value: '6' },
          { text: '营销运维', value: '5' },
          { text: '营销部长', value: '2' },
        ],
      },
      {
        text: '采购部',
        value: '10',
        children: [
          { text: '采购主管', value: '41' },
          { text: '采购工程师', value: '42' },
          { text: '采购文员', value: '43' },
          { text: '采购其他', value: '44' },
        ],
      }, {
        text: '人事部',
        value: '11',
        children: [
          { text: '人事专员', value: '47' },
          { text: '人事主管', value: '45' },
          { text: '人事其他', value: '46' },
        ],
      }, {
        text: '总经办',
        value: '12',
        children: [
          { text: '总经理', value: '48' },
          { text: '副总经理', value: '49' },
          { text: '总经理助理', value: '50' },
        ],
      },
      {
        text: '推广部',
        value: '2',
        children: [
          { text: '推广运营', value: '7' },
          { text: '推广美工', value: '8' },
          { text: '推广其他', value: '9' },
          { text: '推广部长', value: '1' },
        ],
      },
      {
        text: '市场部',
        value: '3',
        children: [
          { text: '市场部长', value: '10' },
          { text: '市场专员', value: '11' },
          { text: '市场其他', value: '12' },
        ],
      }, {
        text: '售后部',
        value: '4',
        children: [
          { text: '售后部长', value: '13' },
          { text: '售后文员', value: '14' },
          { text: '售后工程师', value: '15' },
          { text: '售后其他', value: '16' },
        ],
      }, {
        text: '研发部',
        value: '5',
        children: [
          { text: '研发主管', value: '17' },
          { text: '研发组长', value: '18' },
          { text: '研发项目经理', value: '19' },
          { text: '研发工程师', value: '20' },
          { text: '研发助理工程师', value: '21' },
          { text: '研发其他', value: '22' },
        ],
      }, {
        text: '生产部',
        value: '6',
        children: [
          { text: '生产工程师', value: '25' },
          { text: '生产部长', value: '23' },
          { text: '生产组长', value: '24' },
          { text: '生产助理', value: '28' },
          { text: '生产助理工程师', value: '26' },
          { text: '生产专员', value: '27' },
          { text: '生产其他', value: '29' },
        ],
      }, {
        text: '品质部',
        value: '7',
        children: [
          { text: '品质其他', value: '32' },
          { text: '品质质检员', value: '31' },
          { text: '品质部长', value: '30' },
        ],
      }, {
        text: '财务部',
        value: '8',
        children: [
          { text: '财务其他', value: '37' },
          { text: '财务助理', value: '36' },
          { text: '财务出纳', value: '35' },
          { text: '财务会计', value: '34' },
          { text: '财务主管', value: '33' },
        ],
      }, {
        text: '行政后勤',
        value: '9',
        children: [
          { text: '行政后勤其他', value: '40' },
          { text: '行政文员', value: '39' },
          { text: '行政主管', value: '38' },
        ],
      },
    ];
    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish = ({ selectedOptions }) => {
      show.value = false;
      deptName.value = selectedOptions.map((option) => option.text).join('-');

      deptId.value = selectedOptions[0].value;
      jobId.value = selectedOptions[1].value;
    };


    const router = useRouter();
    const reqApi = ref(false);

    // 校验18位身份证号码函数返回 true 表示校验通过，false 表示不通过
    const validator = (val) => /^([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]$/.test(val);

    const showPicker = ref(false);
    const onConfirm = ({ selectedValues }) => {
      hireDate.value = selectedValues.join('-');
      showPicker.value = false;
    }
    // 注册点击
    const registerSubmit = async () => {
      if (password.value !== passwordCheck.value) {
        showFailToast(t('register.twoTypedDiff'));
        return false;
      }
      const { data } = await addUserApply({
        userName: userName.value,
        password: md5(password.value),
        identityCard: identityCard.value,
        payeeCode: payeeCode.value,
        cardNo: cardNo.value,
        phone: phone.value,
        code: code.value,
        email: email.value,
        hireDate: hireDate.value,
        jobId: jobId.value,
        deptId: deptId.value,
      });

      if (data.code === '00000') {
        showToast('注册成功');
        router.push({ path: '/login' });
      } else {
        showFailToast(data.message);
      }
    };

    // 发送验证码
    const seedVerCode = async () => {

      reqApi.value = true;

      try {
        const { data } = await sentRegisterCode({
          phone: phone.value,
        });
        if (data.code === '00000') {
          reqApi.value = false;
          showToast("发送成功");
          verCodeTime.time = 1 * 60; // 1分钟定时器，60s后可以更换验证方式
          verCodeTimeInterval();
        } else {
          reqApi.value = false;
          showFailToast(data.message);
        }
      } catch (error) {
        reqApi.value = false;
      }
    }
    // 验证码发送成功开始1分钟倒计时
    const verCodeTimeInterval = () => {
      const intervalId = setInterval(() => {
        verCodeTime.time--;
        setLocal('registerVerCodeTime', verCodeTime.time);
        if (verCodeTime.time === 0) {
          clearInterval(intervalId); // 清除定时器
        }
      }, 1000);
    }
    // 初始化页面获取验证码倒计时
    onMounted(async () => {
      // 加载样式
      styleUrl('register');
      verCodeTime.time = getLocal('registerVerCodeTime');
      if (verCodeTime.time && verCodeTime.time !== '') {
        verCodeTime.time = parseInt(verCodeTime.time);
        if (verCodeTime.time > 0) {
          verCodeTimeInterval();
        }
      } else {
        verCodeTime.time = 0;
      }
    });


    return {
      ...toRefs(verCodeTime),
      logiLogoImgUrl,
      userName,
      // actualName,
      password,
      passwordCheck,
      phone,
      email,
      code,
      verifyRef,
      verCodeTime,
      verCodeTimeInterval,
      seedVerCode,
      registerSubmit,
      active,
      reqApi,
      validator,
      onConfirm,
      showPicker,
      identityCard,
      payeeCode,
      cardNo,
      hireDate,
      deptId,
      deptName,
      jobName,
      jobId,
      show,
      options,
      onFinish,
    }
  },
  components: { sHeader }
}
</script>
<style lang="less" scoped>
@import '@/common/style/mixin';

.register {
  margin-bottom: 40px
}
</style>