import { defineComponent, reactive, ref } from 'vue';
import styles from '../index.module.less';
import lockIcon from '../images/pwdIcon.png';
import useIcon from '../images/phoneIcon.png';
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NInputGroup,
  NModal,
  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 '../api';
import SendSms from './sendSms';
import { formLight } from 'naive-ui/es/form/styles';
interface FormState {
  username: string;
  password: string;
  grant_type: string;
  loginType: string;
  client_id: string;
  client_secret: string;
}

export default defineComponent({
  name: 'codeLogin',
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  emits: ['update:phone'],
  setup(props, { emit }) {
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();
    const message = useMessage();
    const loading = ref(false);
    const autoLogin = ref(true);
    const showSmsClass = ref(false);
    const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;
    const userStore = useUserStore();
    const formInline = reactive({
      username: '',
      password: '',
      isCaptcha: true
    });
    const isDisabledCode = ref(false);
    const starTimer = ref(60);
    const codeName = '发送短信';
    const formInlineHistory = storage.get('userInfo-teacher');
    if (formInlineHistory) {
      formInline.username = JSON.parse(formInlineHistory).username;
    }

    if (formInline.username) {
      if (formInline.username !== props.phone && props.phone) {
        formInline.username = props.phone;
      } else {
        emit('update:phone', formInline.username);
      }
    } else {
      if (props.phone) {
        formInline.username = props.phone;
      }
    }

    const handleSubmit = async () => {
      formRef.value.validate(async (errors: any) => {
        if (!errors) {
          const { username, password } = formInline;
          message.loading('登录中...');
          loading.value = true;
          storage.set('userInfo-teacher', JSON.stringify({ username }));
          const params: FormState = {
            username,
            password,
            loginType: 'SMS',
            grant_type: 'password',
            client_id: 'cooleshow-teacher',
            client_secret: 'cooleshow-teacher'
          };

          try {
            await userStore.login(params);
            // return;
            message.destroyAll();
            // if (some.code == ResultEnum.SUCCESS) {
            //  判断是否勾选自动登录
            if (autoLogin.value) {
              storage.set('userInfo', JSON.stringify(formInline));
            } else {
              storage.remove('userInfo');
            }

            // route.query?.redirect ||
            const toPath = decodeURIComponent('/' as string);

            message.success('登录成功，即将进入系统');
            if (route.name === LOGIN_NAME) {
              router.replace('/');
            } else router.replace(toPath);
            // } else {
            //   // message.info(some.msg || "登录失败");
            // }
          } catch (e: any) {
            message.destroyAll();
            loading.value = false;
            message.error(e.msg);
            console.log(e);
          } finally {
            loading.value = false;
          }
        }
      });
    };

    const sendMessage = async () => {
      // if (!formInline.username) {
      //   message.error('请输入手机号');
      //   return;
      // }
      showSmsClass.value = true;
      // try {
      //   const res = await sendSms({
      //     clientId: 'cooleshow-teacher',
      //     mobile: formInline.username,
      //     type: 'LOGIN'
      //   });
      //   checkTimeOut();
      // } catch (e) {
      //   console.log(e);
      // }
    };

    const checkTimeOut = () => {
      if (isDisabledCode.value) {
        return;
      }
      isDisabledCode.value = true;
      const tiemr = setInterval(() => {
        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="username"
            rule={[
              { required: true, message: '请输入手机号', trigger: 'blur' }
            ]}>
            <NInput
              maxlength={11}
              v-model:value={formInline.username}
              placeholder="请输入手机号"
              onInput={(val: any) => {
                emit('update:phone', val);
              }}>
              {{
                prefix: () => (
                  <img src={useIcon} class={styles.prefixIcon} alt="" />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="password"
            rule={[
              { required: true, message: '请输入验证码', trigger: 'blur' }
            ]}>
            <NInputGroup>
              <NInput
                v-model:value={formInline.password}
                type="text"
                showPasswordOn="click"
                placeholder="请输入验证码"
                inputProps={{ autocomplete: 'off' }}
                class={styles.sendInput}
                maxlength={6}
                onKeydown={(e: KeyboardEvent) => {
                  if (e.code === 'Enter' || e.code === 'NumpadEnter') {
                    handleSubmit();
                  }
                }}>
                {{
                  prefix: () => (
                    <img src={lockIcon} class={styles.prefixIcon} alt="" />
                  ),
                  suffix: () => (
                    <NButton
                      class={styles.sendMsg}
                      disabled={isDisabledCode.value}
                      onClick={() => sendMessage()}>
                      {isDisabledCode.value ? starTimer.value + 'S' : codeName}
                    </NButton>
                  )
                }}
              </NInput>
            </NInputGroup>
          </NFormItem>

          <NFormItem class={styles['default-color']}>
            <div class={[styles['flex'], styles['justify-between']]}>
              <div class={styles['flex-initial']}>
                {/* <NCheckbox v-model:checked={autoLogin.value}>
                  记住密码
                </NCheckbox> */}
              </div>
            </div>
          </NFormItem>
          <NFormItem>
            <NButton
              class={styles.submitBtm}
              type="primary"
              onClick={handleSubmit}
              size="large"
              disabled={loading.value}
              block>
              立即登录
            </NButton>
          </NFormItem>
        </NForm>

        <NModal v-model:show={showSmsClass.value}>
          <SendSms
            phone={formInline.username}
            onClose={() => (showSmsClass.value = false)}
            onSendCode={() => {
              checkTimeOut();
            }}
          />
        </NModal>
      </div>
    );
  }
});
