<script setup>
import { ElMessage } from 'element-plus'
import { Encrypt } from '@/utils/crypto'
import { getCurrentTime } from '@/utils/config'
import useStore from '@/stores'
import { apiGetImgCode, apiGetSmsCode } from '@/api/login'
import DialogPassword from '@/components/DialogPassword/index.vue'

const { user } = useStore()
const router = useRouter()

// 绑定el-form的ref属性
const loginFormRef = ref(null)
const loginData = reactive({
  userPhoneEn: '',
  password: '',
  imageCode: '',
  uuid: '',
  smsCode: ''
})
const loginRules = reactive({
  userPhoneEn: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  imageCode: [
    { required: true, message: '请输入图像验证码', trigger: 'blur' },
    { min: 4, message: '图像验证码不能少于4位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码不能少于8位', trigger: 'blur' },
    { max: 16, message: '密码不能超过16位', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { min: 6, message: '短信验证码不能少于6位', trigger: 'blur' }
  ]
})
const imageCodeUrl = ref('') // 图像验证码
const hasSendMsg = ref(false) // 是否发送过短信
const time = ref(0) // 倒计时
const dialogPasswordVisible = ref(false)

// 获取图像验证码
const handleGetImgCode = () => {
  apiGetImgCode().then((res) => {
    if (res.code === 200) {
      imageCodeUrl.value = `data:image/gif;base64,${res.data.img}`
      loginData.uuid = res.data.uuid
    }
  })
}
handleGetImgCode()

// 获取短信验证码
const timer = ref()
const handleGetSmsCode = () => {
  if (hasSendMsg.value) return
  const emptyData = {
    userPhoneEn: loginData.userPhoneEn,
    password: loginData.password,
    imageCode: loginData.imageCode,
    uuid: loginData.uuid
  }
  if (hasEmptyValue(emptyData)) {
    return ElMessage.error('请输入对应信息')
  }
  apiGetSmsCode({
    userPhoneEn: loginData.userPhoneEn,
    password: Encrypt(loginData.password),
    imageCode: loginData.imageCode,
    uuid: loginData.uuid
  }).then((res) => {
    if (res.code === 200) {
      hasSendMsg.value = true
      time.value = 60
      timeCb()
    } else {
      ElMessage.error(res.msg)
      setTimeout(() => {
        handleGetImgCode()
        loginData.imageCode = ''
      }, 1000)
    }
  })

  // 倒计时
  const timeCb = () => {
    clearTimeout(timer)
    time.value--
    if (time.value < 1) {
      return (hasSendMsg.value = false)
    }
    timer.value = setTimeout(timeCb, 1000)
  }
}

// 登录
const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      user.onLogin(loginData).then((res) => {
        if (res.code === 200) {
          router.push({ path: '/home' })
        } else if (res.code === 6005) {
          dialogPasswordVisible.value = true
        }
      })
    } else {
      return false
    }
  })
}

// 是否有为空的值
const hasEmptyValue = (obj) => {
  for (let key in obj) {
    if (obj[key] == null || obj[key] === '') {
      return true
    }
  }
  return false
}

// 获取当前时间
const currentDate = ref()
setInterval(() => {
  currentDate.value = getCurrentTime()
})
</script>

<template>
  <div id="login">
    <el-card class="login_elCard">
      <h2>东成工作台</h2>
      <h3>{{ currentDate }}</h3>
      <el-form
        :model="loginData"
        :rules="loginRules"
        label-width="auto"
        ref="loginFormRef"
        @keyup.enter="handleLogin"
        class="login_form"
      >
        <el-form-item label="手机号码" prop="userPhoneEn">
          <el-input
            v-model="loginData.userPhoneEn"
            placeholder="请输入手机号码"
            type="text"
            maxlength="11"
            class="login_form__input"
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            v-model="loginData.password"
            placeholder="请输入登录密码"
            type="password"
            maxlength="16"
            minlength="8"
            show-password
            class="login_form__input"
          />
        </el-form-item>
        <el-form-item label="图像验证码" prop="imageCode">
          <el-input
            v-model="loginData.imageCode"
            placeholder="请输入图像验证码"
            type="text"
            maxlength="4"
            class="login_form__input login_form__img-code"
          >
            <template #append>
              <img class="login_form__input-img" @click="handleGetImgCode" :src="imageCodeUrl" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="smsCode">
          <el-input
            v-model="loginData.smsCode"
            placeholder="请输入短信验证码"
            type="text"
            maxlength="6"
            class="login_form__input"
          >
            <template #append>
              <span class="cursor-pointer" @click="handleGetSmsCode">
                {{ hasSendMsg ? time + 's后重发' : '发送验证码' }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="login_submit_btn">
        <el-button @click="handleLogin" type="primary">登录</el-button>
      </div>
    </el-card>
    <dialog-password
      ref="dialogPasswordRef"
      v-model:dialogPasswordVisible="dialogPasswordVisible"
      :loginData="loginData"
      :type="'init'"
    />
  </div>
</template>

<style lang="scss" scoped>
#login {
  width: 100%;
  height: 100%;
  background-image: url('@/assets/images/login_bg1.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  .login_tips {
    position: absolute;
    top: 20%;
    left: 20%;
    h3,
    p {
      color: #5d5d5e;
    }
  }
  .login_elCard {
    // width: 420px;
    // height: 430px;
    // background-color: #ecf5ff;
    border-radius: 30px;
    text-align: center;
    padding: 10px 20px;
    position: absolute;
    top: 20%;
    right: 10%;
  }
  .login_form {
    &__input {
      ::v-deep(.el-input__inner) {
        height: 40px;
        line-height: 40px;
        font-size: 13px;
      }
    }
    &__img-code {
      .el-input__wrapper {
        padding-right: 1px;
      }
      ::v-deep(.el-input-group__append) {
        padding: 0 !important;
      }
    }
    &__input-img {
      height: 40px;
      cursor: pointer;
    }
    .el-input-group__append {
      cursor: pointer;
    }
    ::v-deep(.el-form-item__label) {
      height: 40px !important;
      line-height: 40px !important;
    }
  }
  .login_submit_btn {
    margin: 30px 0;
    .el-button {
      width: 100%;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>
