<template>
  <div class="login">
    <div class="login__container">
      <div class="container__left" />
      <div class="container__right">
        <div class="right__title">林场巡检管理平台</div>
        <div class="right__form">
          <n-form
            ref="formRef"
            :model="loginForm"
            :rules="rules"
            label-placement="left"
            require-mark-placement="right-hanging"
            :style="{maxWidth: '300px'}"
            @keyup.enter="handleLogin"
          >
            <n-form-item path="username">
              <n-input v-model:value="loginForm.username" placeholder="请输入用户名">
                <template #prefix>
                  <img src="@/assets/icon/username.png" alt="">
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="password">
              <n-input v-model:value="loginForm.password" type="password" placeholder="请输入密码">
                <template #prefix>
                  <img src="@/assets/icon/password.png" alt="">
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="captcha">
              <n-input v-model:value="loginForm.captcha" placeholder="请输入验证码">
                <template #prefix>
                  <img src="@/assets/icon/verify.png" alt="">
                </template>
                <template #suffix>
                  <img v-if="captcha" class="captcha_img" :src="captcha" @click="changeCode">
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="remember">
              <n-checkbox v-model:checked="loginForm.remember" size="medium" label="记住密码" />
            </n-form-item>
          </n-form>
        </div>
        <div class="right__button" @click="handleLogin">登录</div>
      </div>
    </div>
    <div class="login__copyright">copyright©2022拓恒技术有限公司</div>
  </div>
</template>

<script>
import { ref, toRefs, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { userCaptcha } from '@/api/login/index.js'
import { useUserStore } from '@/store/modules/user.js'
export default {
  name: 'LoginPage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()

    const data = reactive({
      loginForm: {
        username: '',
        password: '',
        key: '',
        captcha: '',
        remember: false
      },
      captcha: '',
      rules: {
        username: { required: true, message: '请输入用户名', trigger: ['blur', 'input'] },
        password: { required: true, message: '请输入密码', trigger: ['blur', 'input'] },
        captcha: { required: true, message: '请输入验证码', trigger: ['blur', 'input'] }
      }
    })
    onMounted(() => {
      changeCode()
      data.loginForm = Object.assign(
        data.loginForm,
        JSON.parse(localStorage.getItem('login-form'))
      )
    })
    // 获取图形验证码
    async function changeCode() {
      const captForm = await userCaptcha()
      data.captcha = captForm.data.captcha
      data.loginForm.key = captForm.data.key
    }

    const formRef = ref('')

    function handleLogin() {
      formRef.value.validate(async(errors) => {
        if (!errors) {
          const { username, password, remember } = data.loginForm
          if (remember) {
            localStorage.setItem('login-form', JSON.stringify({ username, password, remember }))
          } else {
            localStorage.removeItem('login-form')
          }

          /* 调用store中的方法，登录以及存储token和用户信息 */
          const res = await userStore.getLoginToken(data.loginForm)
          if (res.code === 0) {
            const toPath = decodeURIComponent((route.query?.redirect || '/'))
            route.path === '/login' ? router.replace('/') : router.replace(toPath)
          }
        }
      })
    }

    return {
      ...toRefs(data),
      formRef,
      handleLogin,
      changeCode
    }
  }
}

</script>

<style lang="scss" scoped>
.login{
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("../../assets/back/login.png");
  background-size: 100% 100%;
}
.login__container {
  width: 1460px;
  background-color: #fff;
  display: flex;
  border-radius: 20px;
  position: relative;
  z-index: 10;
  .container__left{
    width: 50%;
    align-self: stretch;
    background-image: url("../../assets/back/form.png");
    background-size: 100% 100%;
  }
  .container__right{
    flex: 1;
    padding: 137px 0 236px 0;
    .right__title{
      font-size: 44px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #1890FF;
      text-align: center;
    }
    .right__form{
      padding: 34px 0 20px 0;
      .n-form{
        margin: 0 auto;
      }
      .n-input:not(.n-input--autosize) {
        width: 100%;
        height: 40px;
        line-height: 40px;
        background-color: transparent;
      }
      ::v-deep(.n-input__suffix){
        cursor: pointer;
        transform: translate(12px);
      }
      .captcha_img {
        width: 90px;
        height: 100%;
        border-left: 1px solid rgb(224, 224, 230);
        border-radius: 4px;
      }
    }
    .right__button{
      width: 300px;
      height: 40px;
      border-radius: 4px;
      cursor: pointer;
      background-color: #1890ff;
      line-height: 40px;
      text-align: center;
      color: #fff;
      font-size: 16px;
      margin: 0 auto;
    }
  }
}

.login__copyright {
  font-size: 20px;
  color: #fff;
  position: absolute;
  bottom: 16px;
}

@media screen and (max-width: 1200px) {
  .login__container{
    max-width: 730px;
  }
  .container__left{
    display: none;
  }
}
</style>
