<script setup lang="ts">
import * as _ from 'lodash'
import { Message } from '@arco-design/web-vue'
import { IconPhone, IconLock, IconSafe } from '@arco-design/web-vue/es/icon'
import { Ref } from 'vue'
import { phoneRule } from '@/rules/login-rules'
import { passwordRule } from '@/rules/user-rules'
// import store from '@/store'
import { login } from '@/api/api'
import platformType from '@/enums/platform_type'
import { filterLabel } from '@/enums/util'
import { getStore, setStore } from '@/utils/storage'
import Verify from '@/components/verifition/Verify.vue'
import { progressive } from '@/utils/image'
import packageConfig from '../../../package.json'
import { SystemInfo } from '@/types/types'
import { useUserStore } from '@/store/user'
import { User } from '@/entity/upms/user'

const router = useRouter()
const route = useRoute()

const toHref = () => {
  const redirect = route.query.redirect as string
  router.replace(redirect || '/')
}
if (getStore('token')) {
  toHref()
}

const userStore = useUserStore()
const { version } = packageConfig

const systemInfo = inject<Ref<SystemInfo>>('systemInfo')
const checkRules = [
  {
    required: true,
    validator: (value: boolean | undefined, callback: (errMsg?: string) => void) => {
      if (import.meta.env.DEV || value === true) {
        callback()
      } else {
        callback('请阅读并勾选此选项')
      }
    }
  }
]
const verifyRules = [
  {
    required: true,
    validator: (value: boolean | undefined, callback: (errMsg?: string) => void) => {
      if (import.meta.env.DEV || value === true) {
        callback()
      } else {
        callback('请进行安全验证')
      }
    }
  }
]
const loginBoxRef = ref()
progressive('/bg_small.jpeg')
  .then(() => {
    nextTick(() => {
      loginBoxRef.value.style.backgroundImage = "url('/bg_small.jpeg')"
    })
    return progressive('/bg.jpeg')
  })
  .then(() => {
    nextTick(() => {
      loginBoxRef.value.style.backgroundImage = "url('/bg.jpeg')"
    })
  })
const loading = ref(false)
const formRef = ref()
const form = ref({
  checkAgreement: getStore('checkAgreement') || false,
  verify: false,
  captchaVerification: '',
  phone: getStore('login_phone') || undefined,
  password: import.meta.env.DEV ? '123456' : ''
})
const userList = ref<User[]>([])
const verifyRef = ref()

const loginSuccess = (authUser: User) => {
  if (authUser.claims.status === 'suspend') {
    Message.error('当前账号已被停用')
    loading.value = false
    return
  }
  loading.value = true
  setStore('token', authUser.token)
  setStore('checkAgreement', true)
  setStore('login_phone', authUser.phone)
  userStore.login(authUser)
  toHref()
}
const handleLogin = _.throttle(
  () => {
    if (loading.value) {
      return
    }
    let flag = false
    setTimeout(() => {
      if (!flag) {
        loading.value = true
      }
    }, 500)
    login(form.value)
      .then((res: any) => {
        flag = true
        if (res.length === 1) {
          loginSuccess(res[0])
        } else {
          userList.value = res
          loading.value = false
        }
        form.value.verify = false
      })
      .catch((err) => {
        formRef.value.setFields({
          password: {
            status: 'error',
            message: err
          }
        })
        flag = true
        loading.value = false
        form.value.verify = false
        form.value.captchaVerification = ''
      })
  },
  1000,
  { leading: true, trailing: false }
)

const handleToAgreement = () => {
  window.open('/doc/隐私政策.pdf')
}
const handleToUserAgreement = () => {
  window.open('/doc/用户协议.pdf')
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleAgreementChange = (value: boolean | (string | number | boolean)[]) => {
  if (!value) {
    setStore('checkAgreement', false)
  }
  formRef.value.validateField('checkAgreement')
}
const handleVerify = () => {
  verifyRef.value.show()
}
const verifySuccess = (e: any) => {
  form.value.captchaVerification = e.captchaVerification
  form.value.verify = true
  formRef.value.validateField('verify')
  setTimeout(() => {
    form.value.verify = false
    form.value.captchaVerification = ''
  }, 60 * 1000)
}
</script>

<template>
  <div class="login-box" ref="loginBoxRef">
    <a-row justify="center" class="md-align-center" style="height: 100%; width: 100%">
      <a-col
        class="md-hide"
        :xs="0"
        :sm="12"
        :md="12"
        :lg="10"
        :xl="8"
        :xxl="7"
        style="max-width: 500px"
      >
        <div
          class="wrap flex-column align-center un-select justify-center"
          style="height: 386px; font-size: 26px; color: #fff; font-weight: 500"
        >
          <div style="width: 100%">
            <div style="padding: 0 40px" class="align-center flex-row">
              欢迎来到
              <img
                src="/src/assets/images/login-arrow.png"
                style="margin-left: 12px; margin-bottom: 4px"
                alt="arrow-icon"
              />
            </div>
          </div>
          <div style="width: 100%; margin: 20px 0">
            <div
              style="
                margin: 0 40px;
                height: 1px;
                background-color: #fff;
                opacity: 0.6;
                border-radius: 1px;
              "
            ></div>
          </div>
          <div style="width: 100%">
            <div style="padding: 0 40px" class="align-center flex-row">
              <img
                style="margin-bottom: 5px; margin-right: 12px; height: 22px"
                src="/src/assets/images/login-logo.png"
                alt="logo"
              />FxBoot-快速开发框架
            </div>
          </div>
        </div>
      </a-col>
      <a-col :xs="22" :sm="14" :md="11" :lg="9" :xl="7" :xxl="6" style="max-width: 420px"
        ><div
          class="wrap flex-column align-center md-show justify-center"
          style="font-size: 23px; color: #fff; font-weight: 500; max-width: 420px; padding: 20px 0"
        >
          <div style="width: 100%">
            <div style="padding: 0 20px" class="align-center flex-row">
              欢迎来到
              <img
                src="/src/assets/images/login-arrow.png"
                style="margin-left: 8px; margin-bottom: 2px; width: 25px"
                alt="arrow-icon"
              />
            </div>
          </div>
          <div style="margin: 10px 0">
            <div
              style="
                margin: 0 20px;
                height: 1px;
                background-color: #fff;
                opacity: 0.6;
                border-radius: 1px;
              "
            ></div>
          </div>
          <div style="width: 100%">
            <div style="padding: 0 20px" class="align-center flex-row">
              <img
                style="margin-bottom: 4px; margin-right: 8px; height: 22px"
                src="/src/assets/images/login-logo.png"
                alt="logo"
              />FxBoot | 快速开发框架
            </div>
          </div>
        </div>
        <a-card>
          <a-typography-title
            :heading="4"
            :ellipsis="true"
            v-show="userList.length === 0"
            class="un-select"
          >
            账号登录
          </a-typography-title>
          <a-breadcrumb v-show="userList.length > 0">
            <a-breadcrumb-item>
              <a-button type="text" @click="userList = []">
                <template #icon>
                  <icon-arrow-left />
                </template>
              </a-button>
            </a-breadcrumb-item>
            <a-breadcrumb-item>请选择要登录的身份</a-breadcrumb-item>
          </a-breadcrumb>
          <a-spin :loading="loading" tip="登录中..." style="width: 100%">
            <a-form
              v-show="userList.length === 0"
              size="large"
              ref="formRef"
              :model="form"
              layout="vertical"
              @submit-success="handleLogin"
            >
              <a-form-item
                field="phone"
                hide-label
                label=""
                :rules="phoneRule"
                validate-trigger="input"
              >
                <a-input v-model="form.phone" placeholder="手机号">
                  <template #prefix>
                    <icon-phone />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                field="password"
                hide-label
                label=""
                :rules="passwordRule"
                validate-trigger="input"
              >
                <a-input-password v-model="form.password" placeholder="密码">
                  <template #prefix>
                    <icon-lock />
                  </template>
                </a-input-password>
              </a-form-item>
              <!-- <a-row align="center" justify="space-between">
                  <a-checkbox>记住密码</a-checkbox>
                  <a-link>忘记密码？</a-link>
                </a-row> -->
              <a-form-item
                field="verify"
                hide-label
                label=""
                :rules="verifyRules"
                validate-trigger="change"
              >
                <a-button
                  long
                  @click="handleVerify"
                  :disabled="form.verify"
                  :style="form.verify ? { cursor: 'default' } : {}"
                  :status="form.verify ? 'success' : undefined"
                >
                  <template #icon>
                    <div class="point point-flicker" v-if="!form.verify"></div>
                    <icon-safe color="green" v-else />
                  </template>
                  {{ form.verify ? '验证成功' : '点击按钮进行验证' }}
                  <icon-refresh
                    v-if="form.verify"
                    @click.stop="form.verify = false"
                    style="cursor: pointer; color: rgb(var(--primary-4)); margin-left: 4px"
                  />
                </a-button>
              </a-form-item>
              <a-form-item>
                <a-button style="margin-top: 10px" type="primary" :long="true" html-type="submit"
                  >登录</a-button
                >
              </a-form-item>
              <a-form-item
                field="checkAgreement"
                hide-label
                :rules="checkRules"
                :validate-trigger="[]"
              >
                <a-checkbox
                  @change="handleAgreementChange"
                  v-model="form.checkAgreement"
                  style="font-size: 13px"
                >
                  <span style="color: var(--color-text-3)" class="un-select"
                    >我已阅读并同意<a-link
                      class="doc-link"
                      @click.stop.prevent="handleToUserAgreement"
                      >《用户协议》</a-link
                    >和<a-link class="doc-link" @click.stop.prevent="handleToAgreement"
                      >《隐私政策》</a-link
                    ></span
                  >
                </a-checkbox>
              </a-form-item>
            </a-form>
            <a-scrollbar style="height: 300px; overflow-y: auto" v-show="userList.length > 0">
              <a-space direction="vertical" style="width: 100%">
                <a-button
                  v-for="item in userList"
                  :key="item.id"
                  :long="true"
                  :disabled="item.claims.status !== 'normal'"
                  @click="loginSuccess(item)"
                  class="align-center flex-row justify-between"
                >
                  <span>{{ item.fullName }}</span>
                  <a-space>
                    <a-tag color="red" v-if="item.claims.status === 'suspend'">停用</a-tag>
                    <a-tag color="purple" v-if="item.tenantName">
                      {{
                        item.tenantName.length > 10
                          ? item.tenantName.substring(0, 8) + '..'
                          : item.tenantName
                      }}
                    </a-tag>
                    <a-tag color="arcoblue">{{
                      filterLabel(item.claims.platformType, platformType)
                    }}</a-tag>
                  </a-space>
                </a-button>
              </a-space>
            </a-scrollbar>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
    <!-- </a-col> -->
    <!-- </a-row> -->
    <span class="copy-right absolute" style="bottom: 32px">
      <a href="https://beian.miit.gov.cn/">闽ICP备2021019176号-3</a>
      <span> Copyright © 2022 All rights reserved.</span>
    </span>
    <span
      class="un-select absolute"
      style="font-weight: normal; color: rgba(255, 255, 255, 0.3); right: 10px; bottom: 6px"
      >v{{ version }}</span
    >
  </div>

  <Verify
    @success="verifySuccess"
    :mode="'pop'"
    :captchaType="
      systemInfo && (systemInfo.isMobile || !systemInfo.isWideScreen) ? 'clickWord' : 'blockPuzzle'
    "
    :imgSize="{ width: '330px', height: '155px' }"
    ref="verifyRef"
  ></Verify>
</template>

<style scoped lang="scss">
.login-box {
  flex: 1;
  width: 100%;
  height: 100%;
  background: linear-gradient(#8c6179, #1a4371);
  position: relative;
  background-attachment: fixed;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  .doc-link {
    color: rgb(var(--primary-5));
    padding: 1px 0;
    font-size: 12px;
  }
  .copy-right {
    color: #fff;
    left: 0;
    right: 0;
    text-align: center;
    font-weight: bold;
    a {
      text-decoration: none;
      color: #fff !important;
    }
    a:link {
      text-decoration: none;
    }
    a:visited {
      text-decoration: none;
    }
    a:hover {
      text-decoration: none;
    }
    a:active {
      text-decoration: none;
    }
  }
  @media screen and (max-width: 768px) {
    .copy-right {
      display: flex;
      flex-direction: column;
    }
  }
}
// 设置暗黑模式下背景图颜色变暗
body[arco-theme='dark'] {
  .login-box {
    filter: brightness(70%) !important;
  }
}
@media screen and (max-width: 576px) {
  .xs-hide {
    display: none;
  }
}
.md-show {
  display: none;
}
.md-align-center {
  align-items: center;
}
// 当高度576以下时
@media screen and (max-height: 576px) {
  .md-align-center {
    align-items: flex-start;
  }
  .wrap {
    margin-top: 20px;
  }
  .arco-card {
    margin-top: 20px;
  }
}
// 当宽度768一下时，变成竖型
@media screen and (max-width: 768px) {
  .md-hide {
    display: none;
  }
  .md-show {
    display: block;
  }
  // 当竖型且高度768以下时
  @media screen and (max-height: 768px) {
    .md-align-center {
      align-items: flex-start;
    }
    .wrap {
      margin-top: 20px;
    }
    .arco-card {
      margin-top: 0;
    }
  }
}
::v-deep(.arco-breadcrumb) {
  margin-bottom: 14px;
  .arco-btn-text {
    color: var(--color-text-1);
  }
}
::v-deep(.arco-card-bordered) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  // border-radius: var(--border-radius-large);
  border-top-right-radius: var(--border-radius-large);
  border-bottom-right-radius: var(--border-radius-large);
  @media screen and (max-width: 768px) {
    border-top-right-radius: 0;
    border-bottom-left-radius: var(--border-radius-large);
    border-bottom-right-radius: var(--border-radius-large);
  }
}
::v-deep(.arco-card-body) {
  padding: 18px 24px 16px;
  height: 386px;
}
.wrap {
  box-shadow: 0 0 8px rgba(43, 69, 124, 0.35);
  backdrop-filter: saturate(120%) blur(6px);
  background-color: rgba(169, 181, 207, 0.3);
}

.point {
  width: 6px;
  height: 6px;
  background-color: rgb(var(--primary-5));
  position: relative;
  border-radius: 50%;
  margin-right: 4px;
  display: inline-block;
  margin-bottom: 2px;
}

/* 设置动画前颜色 */
.point-flicker:after {
  background-color: rgb(var(--primary-5));
}

/* 设置动画后颜色 */
.point-flicker:before {
  background-color: rgb(var(--primary-4));
}

/* 设置动画 */
.point-flicker:before,
.point-flicker:after {
  content: '';
  width: 12px;
  height: 12px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -6px;
  margin-top: -6px;
  border-radius: 50%;
  animation: warn 1.5s ease-out 0s infinite;
}

/* @keyframes 规则用于创建动画。在 @keyframes 中规定某项 CSS 样式，就能创建由当前样式逐渐改为新样式的动画效果。 */
@keyframes warn {
  0% {
    transform: scale(0.5);
    opacity: 1;
  }

  30% {
    opacity: 1;
  }

  100% {
    transform: scale(1.4);
    opacity: 0;
  }
}
</style>
