import request from '@/helpers/request'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElLink,
  ElMessage
} from 'element-plus'
import { defineComponent, nextTick } from 'vue'
import Cookies from 'js-cookie'
import ImgCode from '../img-code'
import styles from './index.module.less'
import { setAuth } from '@/helpers/utils'
import { checkPhone } from '@/helpers/validate'
import iconSuccess from '@/common/images/icon_success.png'

// const validatePassword = (
//   rule: any,
//   value: string | any[],
//   callback: () => void
// ) => {
//   if (value.length < 6) {
//     // @ts-ignore
//     callback(new Error('密码必须大于六位'))
//   } else {
//     callback()
//   }
// }

export default defineComponent({
  name: 'loginForm',
  props: {
    type: {
      type: String,
      default: 'login' as 'login' | 'register'
    },
    loginType: {
      type: String,
      default: 'TEACHER' as 'TEACHER' | 'STUDENT'
    },
    onClose: {
      type: Function,
      default: () => {}
    },
    onChange: {
      type: Function,
      default: (type: string) => {}
    },
    onLoginTypeChange: {
      type: Function,
      default: (type: string) => {}
    }
  },
  data() {
    return {
      loading: false,
      codeDsiable: false,
      codeStatus: false, // 是否显示图形验证码
      codeTimer: 120, // 发短信时长
      codeInverval: null as any,
      form: {
        username: '',
        code: ''
        // password: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
        // password: [
        //   { required: true, trigger: 'blur', validator: validatePassword }
        // ]
      }
    }
  },
  unmounted() {
    console.log('form unmounted')
    clearInterval(this.codeInverval)
  },
  methods: {
    onSubmit() {
      ;(this as any).$refs.loginForm.validate(async (valid: boolean) => {
        if (valid) {
          if (this.type === 'login') {
            const params = {
              isSurportRegister: false,
              loginUserType: this.loginType
            }
            await this.onLogin(params)
          } else if (this.type === 'register') {
            const params = {
              isSurportRegister: true,
              loginUserType: this.loginType
            }
            await this.onLogin(params)
          }
        }
      })
    },
    async onLogin(params: any) {
      this.loading = true
      try {
        const form = this.form
        const res = await request.post('/api-auth/smsLogin', {
          requestType: 'form',
          data: {
            clientId: 'website',
            clientSecret: 'website',
            phone: form.username,
            smsCode: form.code,
            ...params
          }
        })
        const { authentication } = res.data
        const token =
          authentication.token_type + ' ' + authentication.access_token
        setAuth(
          JSON.stringify({
            token,
            loginUserType: params.loginUserType
          })
        )
        // console.log(res, 'res')
        if (this.type === 'login') {
          window.location.reload()
          this.onClose()
        } else if (this.type === 'register') {
          this.onChange('register-success')
        }
      } catch (e: any) {
        console.log(e)
      }
      this.loading = false
    },
    onResetFields() {
      ;(this as any).$refs.loginForm.resetFields()
    }
  },
  render() {
    return (
      <ElForm
        ref="loginForm"
        model={this.form}
        rules={this.formRules}
        class={[styles.formLogin, 'relative']}
      >
        <ElFormItem prop="username">
          <ElInput
            v-model={this.form.username}
            placeholder="请输入您的手机号码"
            // @ts-ignore
            maxlength={11}
            autocomplete={'off'}
          ></ElInput>
        </ElFormItem>
        <ElFormItem prop="code">
          <ElInput
            v-model={this.form.code}
            // @ts-ignore
            maxlength={6}
            minlength={6}
            placeholder="请输入验证码"
            v-slots={{
              suffix: () => (
                <div
                  class={
                    'before:border-l before:border-l-[#E5E5E5] before:h-[18px] before:mr-3'
                  }
                >
                  <ElLink
                    disabled={this.codeDsiable}
                    class={styles.codeStyles}
                    type="primary"
                    underline={false}
                    onClick={() => {
                      if (!checkPhone(this.form.username)) {
                        return ElMessage.error('请输入正确的手机号码')
                      }
                      this.codeStatus = true
                    }}
                  >
                    {!this.codeDsiable ? '获取验证码' : this.codeTimer + 's'}
                  </ElLink>
                </div>
              )
            }}
          ></ElInput>
        </ElFormItem>
        {/* {(this.type === 'teacher-register' ||
          this.type === 'student-register') && (
          <ElFormItem prop="password">
            <ElInput
              v-model={this.form.password}
              placeholder="请输入您的登录密码"
              type="password"
              autocomplete={'off'}
            ></ElInput>
          </ElFormItem>
        )} */}

        {this.type === 'login' ? (
          <div class="w-full flex justify-center mb-9 pt-6">
            <div
              class="flex items-center pr-6 cursor-pointer"
              onClick={() => {
                this.onLoginTypeChange('TEACHER')
              }}
            >
              {this.loginType === 'TEACHER' ? (
                <img src={iconSuccess} class="w-5 h-5 mr-2.5" />
              ) : (
                <div class="w-5 h-5 rounded-full box-border border border-[#CCCCCC] mr-2.5"></div>
              )}
              老师登录
            </div>
            <div
              class="flex items-center cursor-pointer"
              onClick={() => {
                this.onLoginTypeChange('STUDENT')
              }}
            >
              {this.loginType === 'STUDENT' ? (
                <img src={iconSuccess} class="w-5 h-5 mr-2.5" />
              ) : (
                <div class="w-5 h-5 rounded-full box-border border border-[#CCCCCC] mr-2.5"></div>
              )}
              学生登录
            </div>
          </div>
        ) : (
          <div class="h-12"></div>
        )}
        <ElFormItem>
          <ElButton
            type="primary"
            class={styles.btnStyles}
            onClick={this.onSubmit}
            disabled={this.loading}
            loading={this.loading}
            style={{ height: '48px', fontSize: '16px' }}
            round
          >
            {this.type === 'teacher-login' || this.type === 'student-login'
              ? '登 录'
              : '注 册'}
          </ElButton>
        </ElFormItem>

        {/* 图形验证码 */}
        {this.codeStatus && (
          <ImgCode
            phone={this.form.username}
            onClose={() => {
              this.codeStatus = false
            }}
            onSendCode={async () => {
              this.codeDsiable = true
              this.codeInverval = setInterval(() => {
                this.codeTimer--
                if (this.codeTimer === 0) {
                  this.codeDsiable = false
                  clearInterval(this.codeInverval)
                  this.codeTimer = 120
                }
              }, 1000)
            }}
          />
        )}
      </ElForm>
    )
  }
})
