<template>
  <div id="userLayout" class="w-full h-full relative">
    <div
      class="rounded-lg flex items-center justify-evenly w-full h-full bg-white md:w-screen md:h-screen md:bg-[#ace4db]"
    >
      <div class="md:w-3/5 w-10/12 h-full flex items-center justify-evenly">
        <div
          class="oblique h-[130%] w-3/5 bg-white transform -rotate-12 absolute -ml-52"
        />
        <!-- 分割斜块 -->
        <div
          class="z-[999] pt-12 pb-10 md:w-96 w-full rounded-lg flex flex-col justify-between box-border"
        >
          <div>
            <div class="flex items-center justify-center">
              <img alt class="w-24" src="@/assets/logo.png" />
            </div>
            <div class="mb-9">
              <p class="text-center text-4xl font-bold">
                {{ $GIN_VUE_ADMIN.appName }}
              </p>
            </div>

            <el-tabs>
              <el-tab-pane v-if="loginType.includes(1)" label="账号密码">
                <el-form
                  ref="loginForm"
                  :model="loginFormData"
                  :rules="rules"
                  :validate-on-rule-change="false"
                  @keyup.enter="submitForm"
                >
                  <el-form-item class="mb-6" prop="username">
                    <el-input
                      v-model="loginFormData.username"
                      placeholder="请输入用户名"
                      size="large"
                      suffix-icon="user"
                    />
                  </el-form-item>
                  <el-form-item class="mb-6" prop="password">
                    <el-input
                      v-model="loginFormData.password"
                      placeholder="请输入密码"
                      show-password
                      size="large"
                      type="password"
                    />
                  </el-form-item>
                  <el-form-item
                    v-if="loginFormData.openCaptcha"
                    class="mb-6"
                    prop="captcha"
                  >
                    <div class="flex w-full justify-between">
                      <el-input
                        v-model="loginFormData.captcha"
                        class="flex-1 mr-5"
                        placeholder="请输入验证码"
                        size="large"
                      />
                      <div class="w-1/3 h-11 bg-[#c3d4f2] rounded">
                        <img
                          v-if="picPath"
                          :src="picPath"
                          alt="请输入验证码"
                          class="w-full h-full"
                          @click="loginVerify()"
                        />
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item class="mb-6">
                    <el-button
                      v-preReClick
                      class="shadow shadow-blue-600 h-11 w-full"
                      size="large"
                      type="primary"
                      @click="submitForm"
                      >登 录
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane v-if="loginType.includes(2)" label="ukey">
                <el-form>
                  <el-form-item>
                    <div style="display: flex">
                      <el-select
                        v-model="userSn.info"
                        placeholder="证书名"
                        style="width: 260px; margin-right: 16px"
                      >
                        <el-option
                          v-for="item in certs"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-button
                        v-preReClick
                        style="height: 40px"
                        type="primary"
                        @click="getCertList"
                        >刷新
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-input
                      v-model="keyPassword"
                      placeholder="请输入密码"
                      show-password
                      size="large"
                      type="password"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      v-preReClick
                      class="shadow shadow-blue-600 h-11 w-full"
                      size="large"
                      type="primary"
                      @click="loginKey"
                      >登 录
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane v-if="loginType.includes(3)" label="动态令牌" />
              <el-button
                v-preReClick
                class="shadow shadow-blue-600 h-11 w-full"
                size="large"
                type="primary"
                @click="checkInit"
                >前往初始化
              </el-button>
            </el-tabs>
          </div>
        </div>
      </div>
      <div class="hidden md:block w-1/2 h-full float-right bg-[#ace4db]">
        <img
          alt="banner"
          class="h-full"
          src="@/assets/login_right_banner.jpg"
        />
      </div>
    </div>

    <BottomInfo class="left-0 right-0 absolute bottom-3 mx-auto w-full z-20" />
  </div>
</template>

<script setup>
import { captcha, hasAccount } from '@/api/user'
import { checkDB } from '@/api/initdb'
import BottomInfo from '@/view/layout/bottomInfo/bottomInfo.vue'
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import { getLoginType } from '@/api/config'
import hunca_mToken_core from '@/utils/mtoken/hunca_mToken_core.js'

defineOptions({
  name: 'Login'
})

onMounted(async () => {
  await LoginType()
})

const loginTypeInfo = ref(['账号密码登录', 'ukey登录', '动态令牌登录'])

const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length < 5) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

// 获取验证码
const loginVerify = () => {
  captcha({}).then(async ele => {
    rules.captcha.push({
      max: ele.data.captchaLength,
      min: ele.data.captchaLength,
      message: `请输入${ele.data.captchaLength}位验证码`,
      trigger: 'blur'
    })
    picPath.value = ele.data.picPath
    loginFormData.captchaId = ele.data.captchaId
    loginFormData.openCaptcha = ele.data.openCaptcha
  })
}
loginVerify()

// 登录方式 1 账号密码登录  2 ukey 登录  3 动态口令登录
const loginType = ref([])
const LoginType = async () => {
  const res = await getLoginType()
  if (res.code === 100000) {
    loginType.value = JSON.parse(res.data)
  }
}

const mToken = new hunca_mToken_core()
const certs = ref([])
const userSn = ref({
  userName: '',
  userId: '',
  info: ''
})
const loginKeyForm = reactive({
  sn: '',
  cert: '',
  sign: ''
})
const keyPassword = ref('')

const loginKey = async () => {
  const userName = userSn.value.info.userName
  const res = await hasAccount({ sn: userSn.value.info.sn })
  const key = res.data
  if (!mToken.Hunca_PKCS1(key, userName, keyPassword.value)) {
    ElMessage({ type: 'error', message: mToken.Hunca_GetLastError() })
    return false
  }
  const sign = mToken.Hunca_GetSignData()
  const cert = mToken.Hunca_GetSignCert()
  loginKeyForm.sn = userSn.value.info.sn
  loginKeyForm.cert = cert
  loginKeyForm.sign = sign
  userStore.setLoginType(2)
  loginByKey()
}

const getCertList = () => {
  const userList = mToken.Hunca_GetUserList()
  if (userList.length == 0) {
    ElMessage({ type: 'error', message: '未识别到key' })
    return
  }
  certs.value = []
  for (const user of userList) {
    mToken.Hunca_DealCertInfo(user)
    const certSn = mToken.Hunca_GetSignCertSn()
    certs.value.push({ label: user, value: { sn: certSn, userName: user } })
  }
  userSn.value.info = certs.value[0].value
  ElMessage({ type: 'success', message: '刷新成功' })
}

// 登录相关操作
const loginForm = ref(null)
const picPath = ref('')
const loginFormData = reactive({
  username: '',
  password: '',
  captcha: '',
  captchaId: '',
  openCaptcha: false
})
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  captcha: [
    {
      message: '验证码格式不正确',
      trigger: 'blur'
    }
  ]
})

const userStore = useUserStore()
const login = async () => {
  return await userStore.LoginIn(loginFormData)
}
const loginByKey = async () => {
  return await userStore.LoginIn(loginKeyForm)
}
const submitForm = () => {
  userStore.setLoginType(1)
  loginForm.value.validate(async v => {
    if (v) {
      const flag = await login()
      if (!flag) {
        loginVerify()
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请正确填写登录信息',
        showClose: true
      })
      loginVerify()
      return false
    }
  })
}

// 跳转初始化
const checkInit = async () => {
  const res = await checkDB()
  if (res.code === 100000) {
    if (res.data?.needInit) {
      userStore.NeedInit()
      router.push({ name: 'Init' })
    } else {
      ElMessage({
        type: 'info',
        message: '已配置数据库信息，无法初始化'
      })
    }
  }
}
</script>
<style scoped>
::v-deep .el-select__wrapper {
  min-height: 40px !important;
}
</style>
