import { defineComponent } from 'vue';
import { CellGroup, Field, Button, showToast } from 'vant';
import request from '@/helpers/request';
import { setLogin, state } from '@/state';
import { checkPhone } from '@/helpers/utils';
import loginLogo from './images/login-logo.png';
import iconPhone from './images/icon-phone.png';
import iconPassword from './images/icon-password.png';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import styles from './login.module.less';
import MPopup from '@/components/m-popup';
import Code from './code';
import router from '@/router';

type loginType = 'PWD' | 'SMS';
export default defineComponent({
  name: 'layout-login',
  data() {
    const { isRegister } = this.$route.query;
    return {
      isRegister: isRegister as any,
      loginType: 'SMS' as loginType,
      username: '',
      password: '',
      smsCode: '',
      countDownStatus: true, // 是否发送验证码
      countDownTime: 1000 * 120, // 倒计时时间
      imgCodeStatus: false,
      isAgree: true
    };
  },
  mounted() {
    storage.remove(ACCESS_TOKEN);
    this.directNext();
  },
  methods: {
    directNext() {
      if (state.user.status === 'login' || state.user.status === 'error') {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { returnUrl, isRegister, ...rest } = this.$route.query;
        this.$router.replace({
          path: returnUrl as any,
          query: {
            ...rest
          }
        });
      }
    },
    async onLogin() {
      try {
        if (!checkPhone(this.username)) {
          return showToast('请输入正确的手机号码');
        }
        const forms: any = {
          username: this.username,
          client_id: 'cooleshow-student',
          client_secret: 'cooleshow-student',
          password: this.loginType === 'PWD' ? this.password : this.smsCode,
          grant_type: 'password',
          loginType: this.loginType === 'PWD' ? 'PASSWORD' : 'SMS'
        };

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

        const userCash = await request.get('/edu-app/user/getUserInfo', {
          initRequest: true // 初始化接口
        });
        setLogin(userCash.data);
        this.directNext();
      } catch (e: any) {
        //
        console.log(e);
      }
    },
    async onSendCode() {
      // 发送验证码
      if (!this.isAgree) {
        return showToast('请阅读并同意以下协议');
      }
      if (!checkPhone(this.username)) {
        return showToast('请输入正确的手机号码');
      }
      this.imgCodeStatus = true;
    },
    onChange() {
      if (this.loginType === 'PWD') {
        this.loginType = 'SMS';
      } else if (this.loginType === 'SMS') {
        this.loginType = 'PWD';
      }
    }
  },
  render() {
    return (
      <div class={[styles.login]}>
        <div class={styles.loginContainer}>
          <img src={loginLogo} class={styles.logo} />

          <CellGroup class={styles.container} border={false}>
            <Field
              v-model={this.username}
              name="手机号"
              placeholder="请输入您的手机号"
              type="tel"
              class={styles['input-group']}
              maxlength={11}
              autocomplete="off"
              border={false}>
              {{
                'left-icon': () => (
                  <img src={iconPhone} class={styles.iconPhone} />
                )
              }}
            </Field>

            {this.loginType === 'PWD' && (
              <Field
                v-model={this.password}
                type="password"
                name="密码"
                class={styles['input-group']}
                placeholder="请输入密码"
                autocomplete="off"
                border={false}>
                {{
                  'left-icon': () => (
                    <img src={iconPassword} class={styles.iconPassword} />
                  )
                }}
              </Field>
            )}

            <div class={styles.btnGroup}>
              <Button
                round
                block
                class={styles.primaryButton}
                onClick={() => {
                  if (this.loginType === 'PWD') {
                    this.onLogin();
                  } else {
                    this.onSendCode();
                  }
                }}>
                {this.loginType === 'PWD' ? '登录' : '获取短信验证码'}
              </Button>

              <Button
                round
                block
                type="default"
                class={styles['login-change']}
                onClick={this.onChange}>
                {this.loginType === 'PWD' ? '短信登录' : '密码登录'}
              </Button>
            </div>

            {this.loginType === 'SMS' && (
              <div
                class={styles.protocol}
                onClick={() => (this.isAgree = !this.isAgree)}>
                <i
                  class={[
                    styles.iconChecked,
                    this.isAgree ? styles.active : ''
                  ]}></i>
                我已阅读并同意
                {/* <span
                  onClick={(e: MouseEvent) => {
                    e.stopPropagation();

                    router.push('/preview-protocol');
                  }}>
                  《用户注册协议》
                </span>
                和 */}
                <span
                  onClick={(e: MouseEvent) => {
                    e.stopPropagation();

                    router.push('/privacy-protocol');
                  }}>
                  《隐私政策》
                </span>
              </div>
            )}
          </CellGroup>
        </div>

        <MPopup v-model:modelValue={this.imgCodeStatus}>
          <Code
            phone={this.username}
            isRegister={this.isRegister}
            onClose={val => {
              this.imgCodeStatus = false;
              if (val) {
                requestAnimationFrame(() => {
                  requestAnimationFrame(() => {
                    this.directNext();
                  });
                });
              }
            }}
            onConfirm={this.directNext}
          />
        </MPopup>
      </div>
    );
  }
});
