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 { setToken } from "/src/utils/auth";


export default defineComponent({
  data() {
    const validateUsername = (rule: any, value: any, callback: () => void) => {
      if (!value) {
        // @ts-ignore
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    }
    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, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      passwordType: "password",
      redirect: undefined,
      isSaveUserInfo: true
    }
  },
  mounted() {
    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 res: any = await request.post('/api-auth/usernameLogin', {
              data: {
                username: loginForm.username,
                password: loginForm.password,
                clientId: "system",
                clientSecret: "system"
              }
            })
            console.log(res, 'res');
            let token: string = res?.data.authentication.token_type + ' ' + res?.data.authentication.access_token;
            console.log(token);
            setToken(token)
            ElMessage.success('登录成功')
            this.$router.push({ path: "/home" });
            console.log(res)
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false;
        }
      });
    },
    saveUserInfo() {
      this.isSaveUserInfo = !this.isSaveUserInfo;
    }
  },
  render() {
    return (
      <div class={styles.loginContainer}>
        <div class={styles.loginHeader}>
          <div class={styles.logo}>
            <img src="/src/assets/home/logo.png" alt="" />
          </div>
          <i class={styles.line}></i>
          <div class={styles.logoName}>乐团管理系统</div>
        </div>


        <div>
          <div class={styles.loginSection}>
            <div class={styles.formBg}>
              <img src="/src/pages/login/images/from-bg.png" 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="请输入用户名"
                  type="text"
                  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>
    )
  }
})