import { defineComponent } from "vue"
import { ElForm, ElFormItem, ElInput, ElMessage } from "element-plus";
import styles from './index.module.less'
import request from "/src/helpers/request";
import { removeToken, setToken } from "/src/utils/auth";
import LogoPng from '././../../assets/home/logo.png'
import FromBg from './images/from-bg.png'


export default defineComponent({
  data() {
    const validatePassword = (rule: any, value: string | any[], callback: () => void) => {
      if (value.length < 6) {
        // @ts-ignore
        callback(new Error("密码必须大于六位"));
      } else {
        callback();
      }
    }
    return {
      loginForm: {
        username: null,
        password: null
      } as any,
      loginRules: {
        username: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      passwordType: "password",
      redirect: undefined as any,
      isSaveUserInfo: true
    }
  },
  mounted() {
    if (this.$route.query.redirect) {
      this.redirect = this.$route.query.redirect;
    }
    this.loginForm.username = localStorage.getItem('username');
    this.loginForm.password = localStorage.getItem('password');
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        (this as any).$refs.password.focus();
      });
    },
    handleLogin() {
      // 判断是否点击了记住密码 =>  存储密码
      const loginForm = this.loginForm;
      if (this.isSaveUserInfo) {
        localStorage.setItem('username', loginForm.username);
        localStorage.setItem('password', loginForm.password);
      } else {
        localStorage.setItem('username', '');
        localStorage.setItem('password', '');
      }
      (this as any).$refs.loginForm.validate(async (valid: any) => {
        if (valid) {
          try {
            // 根据手机号获取学生信息
            const resPhone: any = await request('/api-auth/user/queryClient', {
              params: {
                phone: loginForm.username
              }
            })
            console.log(resPhone)
            // "SYSTEM,STUDENT,TEACHER"
            const authType = resPhone.data
            let clientType = 'SYSTEM'
            if (authType.includes('SYSTEM')) {
              clientType = 'SYSTEM'
            } else if(authType.includes('TEACHER')) {
              clientType = 'TEACHER'
            }
            const res: any = await request.post('/api-auth/usernameLogin', {
              data: {
                username: loginForm.username,
                password: loginForm.password,
                clientId: clientType,
                clientSecret: clientType
              }
            })
            let token: string = res?.data.authentication.token_type + ' ' + res?.data.authentication.access_token;
            setToken(token)

            const roomUid = sessionStorage.getItem('roomUid')
            const details:any =  await  request.get('/api-web/imLiveBroadcastRoom/queryRoom', {
              params: {
                roomUid: roomUid
              }
            })

            sessionStorage.setItem('details',JSON.stringify(details.data))
            ElMessage.success('登录成功')
            this.$router.push(this.redirect || '/')
          } catch (error) {
            // console.log(error)
            removeToken()
          }
        } else {
          return false;
        }
      });
    },
    saveUserInfo() {
      this.isSaveUserInfo = !this.isSaveUserInfo;
    }
  },
  render() {
    return (
      <div class={styles.loginContainer}>
        <div class={styles.loginHeader}>
          <div class={styles.logo}>
            <img src={LogoPng} alt="" />
          </div>
          <i class={styles.line}></i>
          <div class={styles.logoName}>乐团管理系统</div>
        </div>


        <div>
          <div class={styles.loginSection}>
            <div class={styles.formBg}>
              <img src={FromBg} alt="" />
            </div>
            <ElForm ref="loginForm"
              model={this.loginForm}
              rules={this.loginRules}
              class={styles.loginForm}
              auto-complete="on"
              label-position="left">
              <div class={styles.titleContainer}>登录</div>
              <ElFormItem prop="username"
                class={styles.logitem}>
                <span class={styles.svgContainer}>
                  {/* <img class={styles.icon} src="/src/icons/svg/user.svg" alt="" /> */}
                  <SvgIcon class={styles.icon} name="svg-user" color="#fff" />
                </span>
                <ElInput ref="username"
                  class={styles.loginInput}
                  v-model={this.loginForm.username}
                  placeholder="请输入手机号"
                  // @ts-ignore
                  maxlength={11}
                  type="tel"
                  tabindex="1"
                  auto-complete="off" />
              </ElFormItem>
              <ElFormItem prop="password"
                class={styles.logitem}>
                <span class={styles.svgContainer}>
                  {/* <img class={styles.icon} src="/src/icons/svg/password.svg" alt="" /> */}
                  <SvgIcon class={styles.icon} name="svg-password" color="#fff" />
                </span>
                <ElInput
                  ref="password"
                  class={styles.loginInput}
                  v-model={this.loginForm.password}
                  type={this.passwordType}
                  placeholder="请输入密码"
                  tabindex="2"
                  auto-complete="off" />
                <span class={styles.showPwd} onClick={this.showPwd}>
                  {this.passwordType === 'password' ? <SvgIcon class={styles.icon} name="svg-eye" color="#fff" /> : <SvgIcon class={styles.icon} name="svg-eye-open" color="#fff" />}
                </span>
              </ElFormItem>
              <div class={[!this.loginForm.username || !this.loginForm.password ? styles.disabled : '', styles.loginBtn]}
                onClick={this.handleLogin}>登录</div>
              <div class={styles.remberBox} onClick={() => { this.isSaveUserInfo = !this.isSaveUserInfo }}>
                <div class={[this.isSaveUserInfo ? styles.checked : '', styles.dotWrap]}></div>
                记住密码
              </div>
            </ElForm>
          </div>
          <div class={styles.footer}>
            Copyright © 2022 管乐迷, Inc.ALL Rights Reserved
          </div>
        </div>
      </div>
    )
  }
})
