<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="$t('register.usernameLabel')"
          :placeholder="$t('register.usernamePlaceholder')"
          :rules="[{ pattern: /^[a-zA-Z][a-zA-Z0-9]*$/, message: $t('register.usernameRequired') }]" />
        <br>
        <van-field v-model="name" name="name" :label="$t('register.nameLabel')"
          :placeholder="$t('register.namePlaceholder')"
          :rules="[{ required: true, message: $t('register.nameRequired') }]" />
        <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>
        <!-- 国家或地区 -->
        <div class="van-cell van-field">
          <div class="van-cell__title van-field__label"><span>{{ $t('register.country') }}</span></div>
          <div class="van-cell__value van-field__value radioBox">
            <van-radio-group v-model="ifForeign" direction="horizontal">
              <van-radio name="0" icon-size="18px">{{ $t('register.chinese') }}</van-radio>
              <van-radio name="1" icon-size="18px">{{ $t('register.other') }}</van-radio>
            </van-radio-group>
          </div>
        </div>
        <!-- 中国 -->
        <div v-if="ifForeign === '0'">
          <div class="van-cell van-field">
            <div class="van-cell__title van-field__label"><span>{{ $t('register.logonMode') }}</span></div>
            <div class="van-cell__value van-field__value radioBox">
              <van-radio-group class="o-pr-18" v-model="logonMode" direction="horizontal">
                <van-radio name="10" icon-size="18px" :value="0">{{ $t('register.phoneRegistration') }}</van-radio>
                <van-radio name="11" icon-size="18px" :value="1">{{ $t('register.emailRegistration') }}</van-radio>
              </van-radio-group>
            </div>
          </div>
          <!-- 国内手机 -->
          <van-field v-if="logonMode === '10'" v-model="phone" name="phone" type="tel" :label="$t('register.phoneLabel')"
            :placeholder="$t('register.phonePlaceholder')"
            :rules="[{ required: ifForeign === '0' && logonMode === '10', pattern: /^1[3456789]\d{9}$/, message: $t('register.phoneRequired') }]" />
          <br v-if="ifForeign === '0' && logonMode === '10'">
          <!-- 短信验证码 -->
          <van-field v-if="logonMode === '10'" v-model="code" name="code" :label="$t('register.codeLabel')"
            :placeholder="$t('register.codePlaceholder')"
            :rules="[{ required: true, message: $t('register.codeRequired') }]">
            <template #button v-if="ifForeign === '0' && logonMode === '10'">
              <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>
          <!-- 国内邮箱 -->
          <van-field v-if="logonMode === '11'" v-model="email" name="email" :label="$t('register.emailLabel')"
            :placeholder="$t('register.emailPlaceholder')" :rules="[
              { required: ifForeign === '0' && logonMode === '11', message: $t('register.emailRequired') },
              { pattern: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/, message: '邮箱格式错误！' }
            ]" :minlength="3" :maxlength="20">
          </van-field>
          <br v-if="ifForeign === '0' && logonMode === '11'">
          <!-- 国内邮箱验证码 -->
          <van-field v-if="logonMode === '11'" v-model="code" name="code" :label="$t('register.emailCodeLabel')"
            :placeholder="$t('register.emailCodePlaceholder')"
            :rules="[{ required: true, message: $t('register.emailCodeRequired') }]">
            <template #button v-if="ifForeign === '0' && logonMode === '11'">
              <van-button size="small" type="primary" @click="seedVerCode()"
                :disabled="time !== 0 || email.length === 0"
                :loading=reqApi :loading-text="$t('register.sending')">{{
                  time === 0 ?
                  $t('register.seedVerCode') : time + $t('register.replaysInSeconds')
                }}
              </van-button>
            </template>
          </van-field>
        </div>
        <!-- 海外 -->
        <div v-if="ifForeign === '1'">
          <!-- 海外邮箱 -->
          <van-field v-if="ifForeign === '1'" v-model="email" name="email" :label="$t('register.emailLabel')"
            :placeholder="$t('register.emailPlaceholder')"
            :rules="[{ required: ifForeign === '1', message: $t('register.emailRequired') }]" />
          <br v-if="ifForeign === '1'">
          <!-- 海外邮箱验证码 -->
          <van-field v-if="ifForeign === '1'" v-model="code" name="code" :label="$t('register.emailCodeLabel')"
            :placeholder="$t('register.emailCodePlaceholder')"
            :rules="[{ required: true, message: $t('register.emailCodeRequired') }]">
            <template #button v-if="ifForeign === '1'">
              <van-button size="small" type="primary" @click="seedVerCode()" :disabled="time !== 0 || email.length === 0"
                :loading=reqApi :loading-text="$t('register.sending')">{{
                  time === 0 ?
                  $t('register.seedVerCode') : time + $t('register.replaysInSeconds')
                }}
              </van-button>
            </template>
          </van-field>
        </div>
        <!-- 提交验证信息 -->
        <van-button round type="primary" class="register" native-type="submit">{{
          $t('register.registerButton')
        }}
        </van-button>
      </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, tAdminSave } from '@/service/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 name = ref('');
    const password = ref('');
    const passwordCheck = ref('');
    const ifForeign = ref('0');
    const logonMode = ref('10');
    const phone = ref('');
    const email = ref('');
    const code = ref('');
    const verifyRef = ref(null);
    const verCodeTime = reactive({
      time: 0
    });

    let phoneOrEmailStr = ref('');

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

    // 注册点击
    const registerSubmit = async () => {
      if (password.value !== passwordCheck.value) {
        showFailToast(t('register.twoTypedDiff'));
        return false;
      }
      const { data } = await tAdminSave({
        username: username.value,
        name: name.value,
        password: md5(password.value),
        ifForeign: ifForeign.value,
        // phone: phone.value,
        // email: email.value,
        phoneOrEmail: phone.value || email.value,
        code: code.value,
        companyType: '1'
      });

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

    // 发送验证码
    const seedVerCode = async () => {
      reqApi.value = true;
      if (ifForeign.value === '1') {
        phoneOrEmailStr = email.value;
      } else if (ifForeign.value === '0' && logonMode.value === '10') {
        phoneOrEmailStr = phone.value;
      } else {
        phoneOrEmailStr = email.value;
      }

      try {
        const { data } = await sentRegisterCode({
          ifForeign: ifForeign.value,
          phoneOrEmail: phoneOrEmailStr,
          hostName: 'SevenCloud',
        });
        if (data.code === '00000') {
          reqApi.value = false;
          showToast(data.data);
          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;
      }
    });

    const signOptions = [
      { text: '手机注册', value: "mo" },
      { text: '邮箱注册', value: "ema" }
    ]
    const option1 = [
      {
        text: 'aaaa', value: 0,

      },
      {
        text: 'ccc', value: 1
      }
    ]

    const option2 = [
      {
        text: 'bbb', value: 'b'
      }
    ]

    return {
      ...toRefs(verCodeTime),
      logiLogoImgUrl,
      username,
      name,
      password,
      passwordCheck,
      ifForeign,
      phone,
      email,
      code,
      verifyRef,
      verCodeTime,
      verCodeTimeInterval,
      seedVerCode,
      registerSubmit,
      option1,
      option2,
      signOptions,
      signinModel: 'aaabb',
      active,
      logonMode,
      reqApi,
    }
  },
  components: { sHeader }
}
</script>
<style lang="less" scoped>
@import '../common/style/mixin';
</style>