import { defineComponent, reactive, ref } from 'vue';
import styles from '../index.module.less';
import openEye from '../images/openEye.png';
import closeEye from '../images/closeEye.png';
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NInputGroup,
  NSpace
} 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  } from '../../login/api';
import { updatePassword } from '@/views/home/api'
interface FormState {
  mobile: string;
  password: string;
  grant_type: string;
  loginType: string;
  client_id: string;
  client_secret: string;
}

export default defineComponent({
  name: 'forgotPassword',
  emits: ['close'],
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const formRef = ref();
    const message = useMessage();
    const loading = ref(false);
    const showPwd = ref(false);
    const userStore = useUserStore();
    const formInline = reactive({
      mobile: props.phone,
      password: '',
      code: '',
      // isCaptcha: true
    });
    const isDisabledCode = ref(false);
    const starTimer = ref(60);
    const codeName = '发送短信';

    const handleSubmit = async () => {
      formRef.value.validate(async (errors: any) => {
        if (!errors) {
          message.loading('修改中...');
          loading.value = true;
          try {
            await updatePassword({
              ...formInline,
              mobile:null,
              clientType: 'TEACHER'
            });
            message.success('修改成功');
            loading.value = false;
            emit('close');
            setTimeout(() => {
              userStore.logout();
              history.go(0);
            }, 500);
            return false;
          } catch (e: any) {
            loading.value = false;
            message.error(e.msg);
            return false;
          }
        }
      });
      return false;
    };
    const sendMessage = () => {
      formRef.value?.validate(
        (errors: any) => {
          if (errors) {
            return;
          }
          checkTimeOut();
          sendSms({
            clientId: 'cooleshow-teacher',
            mobile: formInline.mobile,
            type: 'PASSWORD'
          });
        },
        (rule: any) => {
          return rule.key === 'a';
        }
      );
    };

    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.wrap}>
          <NForm
            ref={formRef}
            label-placement="left"
            size="large"
            model={formInline}>
            <NFormItem
              path="mobile"
              rule={[
                {
                  key: 'a',
                  required: true,
                  message: '请输入手机号',
                  trigger: 'blur'
                },
                {
                  key: 'a',
                  pattern: /^1[3456789]\d{9}$/,
                  message: '手机号格式不正确',
                  trigger: 'blur'
                }
              ]}>
              <NInput
                readonly
                type="text"
                disabled={true}
                maxlength={11}
                v-model:value={formInline.mobile}
                placeholder="请输入手机号"></NInput>
            </NFormItem>
            <NFormItem
              path="code"
              rule={[
                { required: true, message: '请输入验证码', trigger: 'blur' },
                {
                  pattern: /^\d+$/,
                  message: '请输入数字验证码',
                  trigger: 'blur'
                }
              ]}>
              <NInputGroup>
                <NInput
                  v-model:value={formInline.code}
                  type="text"
                  maxlength={6}
                  placeholder="请输入验证码"
                  class={styles.sendInput}></NInput>
                <NButton
                  type="primary"
                  class={styles.sendMsg}
                  disabled={isDisabledCode.value}
                  bordered={false}
                  onClick={() => sendMessage()}>
                  {isDisabledCode.value ? starTimer.value : codeName}
                </NButton>
              </NInputGroup>
            </NFormItem>
            <NFormItem
              path="password"
              rule={[
                {
                  required: true,
                  message: '请输入密码',
                  trigger: 'blur'
                },
                {
                  pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                  message: '密码为6-20位数字和字母组合',
                  trigger: 'blur'
                }
              ]}>
              <NInput
                v-model:value={formInline.password}
                showPasswordOn="click"
                placeholder="请输入密码"
                inputProps={{ autocomplete: 'off' }}
                class={[showPwd.value ? '' : styles['no-pwd']]}>
                {{
                  'password-visible-icon': () => (
                    <img src={openEye} class={styles.pwdIcon} />
                  ),
                  'password-invisible-icon': () => (
                    <img src={closeEye} class={styles.pwdIcon} />
                  )
                }}
              </NInput>
            </NFormItem>
          </NForm>
        </div>
        <NSpace
          justify="space-around"
          style={{ width: '100%' }}
          wrap={false}
          wrapItem={false}>
          <NButton
            class={[styles.submitBtm, styles.submitForgoBtm]}
            onClick={() => emit('close')}
            size="large"
            round
            disabled={loading.value}>
            取消
          </NButton>
          <NButton
            class={[styles.submitBtm, styles.submitForgoBtm]}
            type="primary"
            onClick={handleSubmit}
            size="large"
            round
            disabled={loading.value}>
            确认修改
          </NButton>
        </NSpace>
      </>
    );
  }
});
