import { defineComponent, reactive, ref } from 'vue';
import styles from '../index.module.less';
import pwdIcon from '../images/lock-icon.png';
import lockIcon from '../images/pwdIcon.png';
import useIcon from '../images/phoneIcon.png';
import openEye from '../images/openEye.png';
import closeEye from '../images/closeEye.png';
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NInputGroup
} from 'naive-ui';
import { useRoute, useRouter } from 'vue-router';
import { PageEnum } from '/src/enums/pageEnum';
import { storage } from '@/utils/storage';
import { useUserStore } from '/src/store/modules/users';
import { sendSms, updatePassword } from '../api';
interface FormState {
  mobile: string;
  password: string;
  grant_type: string;
  loginType: string;
  client_id: string;
  client_secret: string;
}

export default defineComponent({
  name: 'forgotPassword',
  emits: ['changType'],
  setup(props, { emit }) {
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();
    const message = useMessage();
    const loading = ref(false);
    const autoLogin = ref(true);
    const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;
    const showPwd = ref(false);
    const showPwd2 = ref(false);
    const userStore = useUserStore();
    const formInline = reactive({
      mobile: '',
      password: '',
      password1: '',
      code: '',
      isCaptcha: true
    });
    const isDisabledCode = ref(false);
    const starTimer = ref(60);
    const codeName = '发送短信';

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

    const handleSubmit = async () => {
      formRef.value.validate(async (errors: any) => {
        if (!errors) {
          message.loading('修改中...');
          loading.value = true;
          try {
            await updatePassword({
              ...formInline,
              clientType: 'TEACHER'
            });
            message.success('修改成功');
            loading.value = false;

            emit('changType');
            return false;
          } catch (e: any) {
            loading.value = false;
            message.error(e.msg);
            return false;
            console.log(e);
          }
        }
      });
      return false;
    };

    const sendMessage = async () => {
      if (!formInline.mobile) {
        message.error('请输入手机号');
        return;
      }
      try {
        const res = await sendSms({
          clientId: 'cooleshow-teacher',
          mobile: formInline.mobile,
          type: 'PASSWORD'
        });
        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);
    };
    return () => (
      <div class={styles['view-account-form-wrap']}>
        {/* <div class={styles.formTitle}>
      <div class={styles.dot}></div>
      酷乐秀课堂乐器
    </div> */}
        <NForm
          ref={formRef}
          label-placement="left"
          size="large"
          model={formInline}>
          <NFormItem
            path="mobile"
            rule={[
              { required: true, message: '请输入手机号', trigger: 'blur' }
            ]}>
            <NInput
              maxlength={11}
              v-model:value={formInline.mobile}
              placeholder="请输入手机号">
              {{
                prefix: () => (
                  <img src={useIcon} class={styles.prefixIcon} alt="" />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="password"
            rule={[
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                message: '密码为6-20位数字和字母组合',
                trigger: 'blur'
              }
            ]}>
            <NInput
              v-model:value={formInline.password}
              type="text"
              showPasswordOn="click"
              placeholder="请输入密码"
              inputProps={{ autocomplete: 'off' }}
              class={[showPwd.value ? '' : styles['no-pwd']]}>
              {{
                prefix: () => (
                  <img src={pwdIcon} class={styles.prefixIcon} alt="" />
                ),
                suffix: () => (
                  <img
                    src={showPwd.value ? openEye : closeEye}
                    class={styles.pwdIcon}
                    alt=""
                    onClick={() => {
                      showPwd.value = !showPwd.value;
                    }}
                  />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="password1"
            rule={[
              {
                validator: validatePass2 as any,
                trigger: 'blur',
                required: true
              }
            ]}>
            <NInput
              v-model:value={formInline.password1}
              type="text"
              showPasswordOn="click"
              placeholder="请确认密码"
              inputProps={{ autocomplete: 'off' }}
              class={[showPwd2.value ? '' : styles['no-pwd']]}>
              {{
                prefix: () => (
                  <img src={pwdIcon} class={styles.prefixIcon} alt="" />
                ),
                suffix: () => (
                  <img
                    src={showPwd2.value ? openEye : closeEye}
                    class={styles.pwdIcon}
                    alt=""
                    onClick={() => {
                      showPwd2.value = !showPwd2.value;
                    }}
                  />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="code"
            rule={[
              { required: true, message: '请输入验证码', trigger: 'blur' }
            ]}>
            <NInputGroup>
              <NInput
                v-model:value={formInline.code}
                type="text"
                showPasswordOn="click"
                placeholder="请输入验证码"
                inputProps={{ autocomplete: 'off' }}
                class={styles.sendInput}
                onKeydown={(e: KeyboardEvent) => {
                  if (e.code === 'Enter') {
                    handleSubmit();
                  }
                }}>
                {{
                  prefix: () => (
                    <img src={lockIcon} class={styles.prefixIcon} alt="" />
                  ),
                  suffix: () => (
                    <NButton
                      class={styles.sendMsg}
                      disabled={isDisabledCode.value}
                      onClick={() => sendMessage()}>
                      {isDisabledCode.value ? starTimer.value : codeName}
                    </NButton>
                  )
                }}
              </NInput>
            </NInputGroup>
          </NFormItem>

          <NFormItem>
            <NButton
              class={[styles.submitBtm, styles.submitForgoBtm]}
              type="primary"
              onClick={handleSubmit}
              size="large"
              disabled={loading.value}
              block>
              确认
            </NButton>
          </NFormItem>
          <NFormItem>
            <NButton
              text
              class={styles.forgetBtm}
              onClick={() => {
                emit('changType');
              }}
              size="large"
              block>
              返回登录
            </NButton>
          </NFormItem>
        </NForm>
      </div>
    );
  }
});
