import {
  Teleport,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  watch
} from 'vue';
import styles from './login.module.less';
import loginLogo from './images/login-logo.png';
import {
  Button,
  CellGroup,
  Icon,
  NumberKeyboard,
  PasswordInput,
  showToast
} from 'vant';
import request from '@/helpers/request';
import { useRouter } from 'vue-router';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { setLogin } from '@/state';
import MImgCode from '@/components/m-img-code';

export default defineComponent({
  name: 'layout-code',
  props: {
    phone: {
      type: String,
      default: ''
    },
    isRegister: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const router = useRouter();
    const forms = reactive({
      imgCodeStatus: false,
      smsCode: '',
      showKeyboard: false,
      countDownStatus: true,
      countDownTime: 120, // 倒计时时间
      countTimer: null as any
    });

    // const onSendSms = async () => {
    //   try {
    //     await request.post('/edu-app/open/sendSmsVerify', {
    //       requestType: 'form',
    //       data: {
    //         clientId: 'cooleshow-student',
    //         type: props.isRegister ? 'REGISTER' : 'LOGIN',
    //         mobile: props.phone,
    //         code: ''
    //       }
    //     });
    //     onCountDown();
    //     setTimeout(() => {
    //       showToast('验证码已发送');
    //     }, 100);
    //   } catch {
    //     forms.countDownStatus = true;
    //   }
    // };

    const onCountDown = () => {
      forms.countDownStatus = false;
      forms.countTimer = setInterval(() => {
        if (forms.countDownTime > 0) {
          forms.countDownTime--;
        } else {
          forms.countDownStatus = true;
          clearInterval(forms.countTimer);
        }
      }, 1000);
      forms.showKeyboard = true;
    };
    const onLogin = async () => {
      try {
        const params: any = {
          username: props.phone,
          client_id: 'cooleshow-student',
          client_secret: 'cooleshow-student',
          password: forms.smsCode,
          grant_type: 'password',
          loginType: 'SMS'
        };

        const { data } = await request.post('/edu-app/userlogin', {
          requestType: 'form',
          data: {
            ...params
          }
        });
        storage.set(ACCESS_TOKEN, data.token_type + ' ' + data.access_token);

        const userCash = await request.get('/edu-app/user/getUserInfo', {
          initRequest: true // 初始化接口
        });
        setLogin(userCash.data);

        emit('close', true);
      } catch {
        //
      }
    };

    watch(
      () => forms.smsCode,
      (val: any) => {
        if (val && val.length === 6) {
          onLogin();
        }
      }
    );

    onMounted(() => {
      nextTick(async () => {
        forms.imgCodeStatus = true;
        //   await onSendSms();
        //   forms.showKeyboard = true;
      });
    });
    return () => (
      <div class={[styles.login]}>
        <Icon
          name="arrow-left"
          class={styles.arrowLeft}
          onClick={() => emit('close')}
        />
        <div class={styles.loginContainer}>
          <img src={loginLogo} class={styles.logo} />

          <CellGroup class={styles.container} border={false}>
            <h2 class={styles['code-title']}>输入验证码</h2>
            <p class={styles.codePhone}>
              已发送6位验证码至<span>{props.phone}</span>
            </p>
            <PasswordInput
              value={forms.smsCode}
              onFocus={() => {
                forms.showKeyboard = true;
              }}
              focused={forms.showKeyboard}
              length={6}
              gutter={12}
            />

            <NumberKeyboard
              v-model={forms.smsCode}
              show={forms.showKeyboard}
              maxlength={6}
              onBlur={() => {
                forms.showKeyboard = false;
              }}></NumberKeyboard>

            <div class={styles.btnWrap}>
              <Button
                type="primary"
                round
                onClick={() => {
                  forms.imgCodeStatus = true;
                }}
                class={styles.btnSend}
                disabled={!forms.countDownStatus}>
                重新发送
                {!forms.countDownStatus && <>({forms.countDownTime})</>}
              </Button>
            </div>
          </CellGroup>
        </div>

        {forms.imgCodeStatus ? (
          <Teleport to={'body'}>
            <MImgCode
              zIndex={2100}
              v-model:value={forms.imgCodeStatus}
              phone={props.phone}
              type="REGISTER"
              onClose={() => {
                forms.imgCodeStatus = false;
              }}
              onSendCode={onCountDown}
            />
          </Teleport>
        ) : null}
      </div>
    );
  }
});
