import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './update-password.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui';
import { useRouter } from 'vue-router';
import { useUserStore } from '/src/store/modules/users';
import { gradeToCN } from '/src/utils/contants';
import { sendSms, updatePassword } from '/src/views/login/api';
export default defineComponent({
  name: 'train-update',
  emits: ['close', 'submit'],
  setup(props, { emit }) {
    const message = useMessage();
    const userStore = useUserStore();
    const forms = reactive({
      mobile: userStore.getUserInfo.phone || '',
      password: null,
      rePassword: null,
      clientType: 'TEACHER',
      code: null
    });

    const validatePass2 = (rule: any, value: any, callback: any): any => {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
      if (value === '' || !value) {
        callback(new Error('请再次输入新密码'));
      } else if (value !== forms.password) {
        callback(new Error('两次输入密码不一致'));
      } else if (!reg.test(value)) {
        callback(new Error('密码为6-20位数字和字母组合'));
      } else {
        callback();
      }
    };
    const validatePass = (rule: any, value: any, callback: any): any => {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
      if (value === '' || !value) {
        callback(new Error('请输入新密码'));
      } else if (!reg.test(value)) {
        callback(new Error('密码为6-20位数字和字母组合'));
      } else {
        callback();
      }
    };

    const gotoClassPage = () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return;

        if (forms.password !== forms.rePassword) {
          message.error('两次输入密码不一致');
          return;
        }

        await updatePassword({
          mobile: forms.mobile,
          password: forms.password,
          clientType: 'TEACHER',
          code: forms.code
        });

        message.success('更新成功');
        emit('submit');
      });
    };

    const formsRef = ref();

    const isDisabledCode = ref(false);
    const starTimer = ref(60);
    const codeName = '发送短信';
    const sendMessage = async () => {
      if (!forms.mobile) {
        message.error('请输入手机号');
        return;
      }
      try {
        await sendSms({
          clientId: 'cooleshow-teacher',
          mobile: forms.mobile,
          type: 'LOGIN'
        });
        checkTimeOut();
      } catch (e) {
        console.log(e);
      }
    };

    const checkTimeOut = () => {
      if (isDisabledCode.value) {
        return;
      }
      isDisabledCode.value = true;
      const tiemr = setInterval(() => {
        starTimer.value--;
        console.log(starTimer.value);
        if (starTimer.value <= 0) {
          isDisabledCode.value = false;
          clearInterval(tiemr);
        }
      }, 1000);
    };

    onMounted(async () => {
      //
    });
    return () => (
      <div class={styles.updatePassword}>
        <p class={styles.tips}>
          检测到您尚未修改默认密码，为了您的账户安全，请重新设置登录密码
        </p>
        <NForm
          labelAlign="right"
          labelPlacement="left"
          labelWidth={'auto'}
          ref={formsRef}
          model={forms}
          requireMarkPlacement="left">
          <NFormItem
            path="currentClass"
            label="手机号"
            class={styles.phoneContainer}>
            <p class={styles.phone}>{forms.mobile}</p>
          </NFormItem>
          <NFormItem
            path="password"
            label="新密码"
            rule={[
              {
                validator: validatePass,
                trigger: 'blur',
                required: true
              }
            ]}>
            <NInput
              v-model:value={forms.password}
              clearable
              type="password"
              show-password-on="click"
              placeholder={'请输入新密码'}
            />
          </NFormItem>
          <NFormItem
            path="rePassword"
            label="再次输入"
            rule={[
              {
                validator: validatePass2,
                trigger: 'blur',
                required: true
              }
            ]}>
            <NInput
              v-model:value={forms.rePassword}
              clearable
              type="password"
              show-password-on="click"
              placeholder={'再次输入新密码'}
            />
          </NFormItem>
          <NFormItem
            path="code"
            label="验证码"
            rule={[
              {
                required: true,
                message: '请输入验证码',
                trigger: 'blur'
              }
            ]}>
            <NInput
              v-model:value={forms.code}
              placeholder={'请输入验证码'}
              clearable
              class={styles.sendInput}
              maxlength={6}>
              {{
                suffix: () => (
                  <NButton
                    class={styles.sendMsg}
                    disabled={isDisabledCode.value}
                    onClick={() => sendMessage()}>
                    {isDisabledCode.value ? starTimer.value + 'S' : codeName}
                  </NButton>
                )
              }}
            </NInput>
          </NFormItem>
          <div class={styles.updateBtnGroup}>
            <NButton
              strong
              type="primary"
              round
              onClick={() => gotoClassPage()}>
              确认
            </NButton>
          </div>
        </NForm>
      </div>
    );
  }
});
