import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './update-password.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NModal,
  useMessage
} from 'naive-ui';
import { useUserStore } from '/src/store/modules/users';
import { updatePassword } from '@/views/home/api';
import openEye from '/src/views/login/images/openEye.png';
import closeEye from '/src/views/login/images/closeEye.png';
import SendSms from '/src/views/login/components/sendSms';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'update-password',
  emits: ['close', 'submit'],
  setup(props, { emit }) {
    const message = useMessage();
    const userStore = useUserStore();
    const showSmsClass = ref(false);
    const forms = reactive({
      mobile: userStore.getUserInfo.phone || '',
      password: null,
      rePassword: null,
      clientType: 'TEACHER',
      code: null
    });

    const password = reactive({
      passowrdStatus: false,
      rePasswordStatus: false
    });

    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 (value.length < 8 || value.length > 20) {
        callback(new Error('8~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 (value.length < 8 || value.length > 20) {
        callback(new Error('8~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: 'PASSWORD'
        // });
        // checkTimeOut();
        showSmsClass.value = true;
      } 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="text"
              showPasswordOn="click"
              inputProps={{ autocomplete: 'off' }}
              class={[password.passowrdStatus ? '' : styles['no-pwd']]}
              placeholder={'请输入新密码'}>
              {{
                suffix: () => (
                  <img
                    src={password.passowrdStatus ? openEye : closeEye}
                    class={styles.pwdIcon}
                    alt=""
                    onClick={() => {
                      password.passowrdStatus = !password.passowrdStatus;
                    }}
                  />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="rePassword"
            label="再次输入"
            rule={[
              {
                validator: validatePass2,
                trigger: 'blur',
                required: true
              }
            ]}>
            <NInput
              v-model:value={forms.rePassword}
              clearable
              type="text"
              showPasswordOn="click"
              inputProps={{ autocomplete: 'off' }}
              class={[password.rePasswordStatus ? '' : styles['no-pwd']]}
              placeholder={'再次输入新密码'}>
              {{
                suffix: () => (
                  <img
                    src={password.rePasswordStatus ? openEye : closeEye}
                    class={styles.pwdIcon}
                    alt=""
                    onClick={() => {
                      password.rePasswordStatus = !password.rePasswordStatus;
                    }}
                  />
                )
              }}
            </NInput>
          </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>

        <NModal maskClosable={modalClickMask} v-model:show={showSmsClass.value}>
          <SendSms
            phone={forms.mobile}
            type="PASSWORD"
            onClose={() => (showSmsClass.value = false)}
            onSendCode={() => {
              checkTimeOut();
            }}
          />
        </NModal>
      </div>
    );
  }
});
