<template>
  <div class="bg">
    <div class="login-box">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        class="login_from"
        label-position="left"
        :model="loginForm"
        style="max-width: 400px"
        @submit.prevent="submitForm(ruleFormRef)">
        <el-tabs v-model="login_typ" style="width: 50%;" @tab-change="resetForm(ruleFormRef)">
          <el-tab-pane label="密码登录" name="pwd" />
          <el-tab-pane label="验证码登录" name="sms" />
        </el-tabs>
        <template v-if="login_typ === 'pwd'">
          <el-form-item label="" prop="account">
            <el-input v-model="loginForm.account" type="text" placeholder="请输入账号" clearable :prefix-icon="User" />
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              show-password
              placeholder="请输入密码"
              autocomplete="off"
              :prefix-icon="Lock" />
            <el-input
              v-model="loginForm.password"
              type="hidden"
              autocomplete="off"
              id="md5_password"
              show-password
              placeholder="请输入密码"
              :prefix-icon="Lock" />
          </el-form-item>
        </template>
        <template v-else-if="login_typ === 'sms'">
          <el-form-item label="" prop="account">
            <el-input v-model="loginForm.account"  type="text" placeholder="请输入手机号" clearable :prefix-icon="Cellphone" />
          </el-form-item>
          <el-form-item label="" prop="smsCaptcha">
            <div style="display: flex;align-items: center;justify-content: space-between;width: 100%;">
              <el-input v-model="loginForm.smsCaptcha" type="number" placeholder="请输入验证码" :prefix-icon="Lock"/>
              <el-button @click="getCaptcha" type="primary" style="width: 100px;" :disabled ="!can_send">{{smsMessage}}</el-button>
            </div>
          </el-form-item>
        </template>
        <!-- <el-form-item style="margin-top:-10px;margin-bottom:-5px;">
                    <el-checkbox v-model="checked" style="color:#a0a0a0;margin-top:-10px;">记住我</el-checkbox>
                </el-form-item> -->
        <div class="btn df aic jcsb">
          <el-button
            round
            class="submit_btn"
            block
            type="primary"
            size="large"
            native-type="submit">登&emsp;录</el-button>
        </div>
      </el-form>
    </div>
  </div>
  <div class="mob-login">
    <div class="login-box" :style="'transform: translateX('+transWidth+')'">
      <div class="item">
        <div class="text">欢迎登录</div>
        <img v-if="user.isQingQue" class="logo" :src="img('logo.png')" alt=""/>
        <div class="tel-login">
          <van-form @submit="submitFormM">
            <van-cell-group inset>
              <van-field
                style="font-size: 16px;"
                v-model="loginForm.account"
                autocomplete="off"
                left-icon="user-circle-o"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
              <van-field
                style="font-size: 16px;"
                v-model="loginForm.password"
                autocomplete="off"
                left-icon="shield-o"
                type="password"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>
            <div style="margin: 16px;margin-top: 30px;">
              <van-button round type="primary" block  native-type="submit">
                登录
              </van-button>
            </div>
          </van-form>
        </div>
        <div class="trans" @click="login_typ = 'sms', transWidth = '0vw'">
          <van-icon name="exchange" />
          验证码登录
        </div>
      </div>
      <div class="item">
        <div class="text">欢迎登录</div>
        <img v-if="user.isQingQue" class="logo" :src="img('logo.png')" alt=""/>
        <img v-else class="logo" style="width: 100px;" :src="img('default_logo.png')" alt=""/>
        <div class="tel-login">
          <van-form >
            <van-cell-group inset>
              <van-field
                type="tel"
                style="font-size: 16px;"
                v-model="loginForm.account"
                autocomplete="off"
                left-icon="phone-o"
                placeholder="请输入手机号"
                :rules="[{ required: true, message: '请填写手机号' }]" />
            </van-cell-group>
            <div style="margin: 16px;margin-top: 30px;">
              <van-button round block type="primary" :disabled="!can_send || loginForm.account.length!==11" @click="getCaptcha">
                {{ smsMessage }}
              </van-button>
            </div>
          </van-form>
        </div>
        <div class="trans" @click="login_typ = 'pwd', transWidth = '100vw'">
          <van-icon name="exchange"  />
          密码登录
        </div>
      </div>
      <div class="item">
        <div class="text">输入验证码
          <div class="notice">验证码已发送至{{loginForm.account}}</div>
        </div>
        <div class="tel-login">
          <van-form @submit="submitFormM">
            <van-password-input
              :value="loginForm.smsCaptcha"
              :mask="false"
              info="请输入6位手机验证码"
              :error-info="errorInfo"
              length="6"
              :gutter="10"
              :focused="showKeyboard"
              @focus="showKeyboard = true"
            />
            <div style="margin: 16px;margin-top: 30px;">
              <van-button round block type="primary" :disabled="loginForm.smsCaptcha === undefined || loginForm.smsCaptcha.length!==6" native-type="submit">
                登录
              </van-button>
            </div>
          </van-form>
        </div>
        <div class="trans"  @click="transWidth = '0vw'">
          <van-icon name="arrow-left"  />
          返回
        </div>
      </div>

    </div>
  </div>
  <van-number-keyboard
    v-model="loginForm.smsCaptcha"
    :show="showKeyboard"
    @blur="showKeyboard = false"
  />
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, inject } from 'vue'
import { Lock, User, Cellphone } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getUserLogin, captchaLogin, getCaptchaHttp } from '@/api/index'
import { showSuccessToast, showFailToast } from 'vant'
// import '@/utils/md5'
import Message from '@/utils/Message'
import checkRestTime from '@/utils/captcha'
import { useRouter } from 'vue-router'
import { useStore } from '@/store/index'
import local from '@/utils/local'

declare let md5: any
const transWidth = ref('0vw')
const { user } = useStore()
const router = useRouter()
const VALID = 60
const login_typ = ref<'pwd'| 'sms'>('sms')
const smsMessage = ref<'获取验证码' | number>('获取验证码')
const errorInfo = ref<string>('')
const ruleFormRef = ref<FormInstance>()
const img:any = inject('img')
const can_send = ref<boolean>(true)
interface login {
    account: string,
    password: string,
    timestamp: number | string,
    smsCaptcha:string | undefined
}
const loginForm = reactive<login>({
  account: '',
  password: '',
  timestamp: parseInt(`${Date.now() / 1000}`),
  smsCaptcha: undefined
})
const showKeyboard = ref(false)
const rules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 255, message: '请正确输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur,change' }
  ],
  smsCaptcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

const submitForm = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      if (login_typ.value === 'pwd') {
        // 登录密码加密
        let md5Pwd: any = document.querySelector('#md5_password')
        // eslint-disable-next-line no-undef
        md5Pwd = md5(md5(md5(loginForm.password)) + loginForm.timestamp)

        const params = {
          account: loginForm.account,
          password: md5Pwd,
          timestamp: loginForm.timestamp
        }
        getUserLogin(params).then(async(res) => {
          // console.log('res---->', res);
          if (res.data.code === 200) {
            Message.success('登录成功')
            // 保存用户信息 和 token
            sessionStorage.setItem('token', res.data.data.token)
            sessionStorage.setItem('account', loginForm.account)
            localStorage.setItem('from', '1')
            user.isLogin = true
            await user.getUserProfile()
            // 跳转我的游戏页面
            setTimeout(() => {
              router.push({ path: '/my_game', query: { account: loginForm.account }})
              local.set('headerPath', '我的')
            }, 1000)
          }
        }).catch(err => {
          // console.log('err===>', err);
          Message.error(err.data.msg)
        })
      } else if (login_typ.value === 'sms') {
        const params = {
          mobile: loginForm.account,
          captcha: loginForm.smsCaptcha
        }
        console.log(params)

        await captchaLogin(params).then(async(res) => {
          console.log(res)
          if (res.data.code === 200) {
            Message.success('登录成功')
            sessionStorage.setItem('token', res.data.data.token)
            sessionStorage.setItem('account', loginForm.account)
            localStorage.setItem('from', '2')
            user.isLogin = true
            await user.getUserProfile()
            setTimeout(() => {
              router.push({ path: '/my_game', query: { account: loginForm.account }})
              local.set('headerPath', '我的')
            }, 1000)
          }
        }).catch((error) => {
          console.log(error)
          Message.error(error.data.msg)
        })
      }
    } else {
      console.log('登录失败', fields)
    }
  })
}
const submitFormM = async() => {
  console.log(login_typ.value)

  if (login_typ.value === 'pwd') {
    // 登录密码加密
    let md5Pwd: any = document.querySelector('#md5_password')
    // eslint-disable-next-line no-undef
    md5Pwd = md5(md5(md5(loginForm.password)) + loginForm.timestamp)

    const params = {
      account: loginForm.account,
      password: md5Pwd,
      timestamp: loginForm.timestamp
    }
    await getUserLogin(params).then(async(res) => {
      // console.log('res---->', res);
      if (res.data.code === 200) {
        Message.success('登录成功')
        // 保存用户信息 和 token
        sessionStorage.setItem('token', res.data.data.token)
        sessionStorage.setItem('account', loginForm.account)
        localStorage.setItem('from', '1')
        user.isLogin = true
        await user.getUserProfile()
        // 跳转我的游戏页面
        setTimeout(() => {
          router.push({ path: '/my_game', query: { account: loginForm.account }})
          local.set('headerPath', '我的')
        }, 1000)
      }
    }).catch(err => {
      // console.log('err===>', err);
      errorInfo.value = err.data.msg
      showFailToast(err.data.msg)
    })
  } else if (login_typ.value === 'sms') {
    const params = {
      mobile: loginForm.account,
      captcha: loginForm.smsCaptcha
    }
    console.log(params)

    await captchaLogin(params).then(async(res) => {
      console.log(res)
      if (res.data.code === 200) {
        showSuccessToast('登录成功')
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('account', loginForm.account)
        localStorage.setItem('from', '2')
        user.isLogin = true
        await user.getUserProfile()
        setTimeout(() => {
          router.push({ path: '/my_game', query: { account: loginForm.account }})
          local.set('headerPath', '我的')
        }, 1000)
      }
    }).catch((error) => {
      errorInfo.value = error.data.msg
      showFailToast(error.data.msg)
    })
  }
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const getCaptcha = async() => {
  if (loginForm.account.length !== 11) {
    return Message.error('请输入有效手机号！')
  }
  await getCaptchaHttp({ mobile: loginForm.account }).then((res) => {
    console.log(res)
    can_send.value = false
    smsMessage.value = VALID
    settimes()
    sessionStorage.setItem('LOGIN_CAPTCHA', Math.round(new Date().getTime() / 1000).toString())
    Message.success('验证码已发送，请注意查收')
    transWidth.value = '-100vw'
  }).catch((error) => {
    console.log(error)
    Message.error(error.data.msg)
  })
}
const settimes = () => {
  var interval:any
  const setTimeFn = () => {
    (smsMessage.value as number)--
    if (smsMessage.value as number < 0 || can_send.value === true) {
      clearInterval(interval)
      can_send.value = true
      smsMessage.value = '获取验证码'
    }
  }
  interval = setInterval(function() {
    setTimeFn()
  }, 1000)
}
onMounted(() => {
  const res = checkRestTime('LOGIN_CAPTCHA', VALID)
  if (res) {
    smsMessage.value = res
    can_send.value = false
    settimes()
  }
})

</script>

<style lang="scss" scoped>
.bg{
  width: 100%;
  height: 29rem;
  background: linear-gradient(#d9e8fe, #ddf2f4, #e3fee9);
  // background-position: 4rem;
  // background-size: cover;
  border-radius: .8rem;
  overflow: hidden;
  margin-top: 3rem;
  position: relative;
  .login-box{
    position: absolute;
    width: 22rem;
    height: 17.5rem;
    left: 3rem;
    top: 50%;
    transform: translateY(-45%);
    background-color: rgba($color: #fff, $alpha: 0.5);
    border-radius: .5rem;
    box-sizing: border-box;
    padding: 2rem 1rem 0 1rem;
    .submit_btn{
      width: 100%;
    }
  }
}
.mob-login{
  display: none;
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 60px);
  background: #EBEEFD url('../assets/img/mobbg.png') no-repeat center;
  background-size: cover;
  // position: relative;
  // align-items: center;
  padding-top: 70px;
  justify-content: center;
  box-sizing: border-box;
  .login-box{
    width: 300vw;
    height: 400px;
    border-radius: 15px;
    padding: 20px 10px;
    box-sizing: border-box;
    // padding-left: 7.5vw;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transition:  all 300ms ease;
    .item{
      width: 100vw;
      // margin-right: 7.5vw;
      padding: 0 7.5vw;
    }
    .logo{
      width: 150px;
      display: block;
      margin: 30px auto;
    }
    .text{
      font-size: 25px;
      margin-bottom: 40px;
      border-bottom: 5px solid #99ccff;
      border-radius: 10px;
      padding-bottom: 5px;
      width: fit-content;
      font-family: 'youshe';
      font-weight: 400;
      position: relative;
      box-sizing: border-box;
      .notice{
        position: absolute;
        width: 80vw;
        height: 20px;
        bottom: -30px;
        left: 0;
        font-family:Arial, Helvetica, sans-serif;
        font-size: 12px;
        color: rgba($color: #000000, $alpha: .8);
      }
    }
    .trans{
      margin-top: 30px;
    }

    .pwd-login{
      transform: translateX(-100vw);
    }

  }
}
</style>
