<script>
import { post, get } from '../../utils/request'
import crypto from '@/crypto/crypto'
import EyeClose from '@/components/icon/eye_close.vue'
import EyeOpen from '@/components/icon/eye_open.vue'
import Error from '@/components/icon/error.vue'
import AsideInfo from '@/components/asideInfo.vue'
import { userStore } from '@/store/userInfo'
import TrailForm from '@/components/trailForm.vue'

export default {
  components: { EyeClose, EyeOpen, Error, AsideInfo, TrailForm },
  data() {
    return {
      passwordError: false,
      emailError: false,
      empty: true,
      teamIds: '',
      passwordType: false,
      remember: false,
      ruleForm: {
        email: '',
        password: ''
      },
      rules: {
        email: [
          {
            required: true,
            message: 'Email Address is required',
            trigger: ['']
          },
          {
            type: 'email',
            message: 'Please enter a valid Email Address',
            trigger: ['']
          }
        ],
        password: [
          { required: true, message: 'Password is required', trigger: [''] }
        ]
      },
      showTrailForm: false
    }
  },
  mounted() {
    const isRemember = localStorage.getItem('isRemember')
    if (isRemember) {
      this.ruleForm.email = localStorage.getItem('username') || ''
      this.ruleForm.password =
        crypto.get(localStorage.getItem('password')) || ''
      this.remember = true
    }
    this.isDisable()
    if (this.$route.query.freeEmail) {
      this.ruleForm.email = this.$route.query.freeEmail
      this.ruleForm.password = ''
    }
  },
  methods: {
    submit() {
      this.passwordError = false
      this.emailError = false
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append('username', this.ruleForm.email)
          formData.append('password', this.ruleForm.password)
          post('/pdf-tech/login', formData).then(
            (res) => {
              if (res.data.code === 200 && res.data.msg === '获取授权码成功') {
                get(
                  '/pdf-tech/auth/getToken?code=' +
                  res.data.result
                ).then((res) => {
                  this.$cookies.remove('accessToken')
                  this.$cookies.set('accessToken', res.data.result.accessToken)
                  setTimeout(() => {
                    if (this.$route.query.teamIds) {
                      this.teamIds = this.$route.query.teamIds.split(',')
                      var urlencoded = new URLSearchParams()
                      urlencoded.append('memberId', this.$route.query.memberId)
                      urlencoded.append('teamIds', this.teamIds)
                      urlencoded.append('action', this.$route.query.action)
                      urlencoded.append('code', this.$route.query.code)
                      post(
                        '/pdf-tech/vppTeam/enterTeam',
                        urlencoded
                      ).then((res) => {
                        this.getMemberInfo()
                      })
                    } else {
                      this.getMemberInfo()
                    }
                  })
                })
                localStorage.setItem('username', this.ruleForm.email)
                const SECRET_PWD = crypto.set(this.ruleForm.password) // 加密
                localStorage.setItem('password', SECRET_PWD)
                if (this.remember) {
                  localStorage.setItem('isRemember', 'true')
                } else {
                  localStorage.removeItem('isRemember')
                }
              } else if (
                res.data.code === 306 &&
                res.data.msg === '账号或者密码错误'
              ) {
                this.passwordError = true
                this.ruleForm.password = ''
                this.$message.error({
                  duration: 5000,
                  message: 'Incorrect email or password'
                })
              } else if (
                res.data.code === 302 &&
                res.data.msg === 'Please Create your Account first'
              ) {
                this.emailError = true
                this.passwordError = true
                this.ruleForm.password = ''
                this.ruleForm.email = ''
                this.$message({
                  type: 'error',
                  duration: 5000,
                  message: 'Please Create Account First'
                })
              }
            }
          )
        } else {
          return false
        }
      })
    },
    isDisable() {
      if (
        this.ruleForm.email.trim() !== '' ||
        this.ruleForm.password.trim() !== ''
      ) {
        this.empty = false
      } else {
        this.empty = true
      }
      if (this.ruleForm.email.trim() !== '') {
        this.emailError = false
      }
      if (this.ruleForm.password.trim() !== '') {
        this.passwordError = false
      }
    },
    getMemberInfo() {
      get('/pdf-tech/vppMember/getMemberInfo').then((res) => {
        this.$message({
          type: 'success',
          duration: 5000,
          message: 'Sign in Success'
        })
        if (res.data.code === 200 && res.data.msg == 'success') {
          userStore().setUserInfo(res.data.result)
          // 判断是否是分销商
          if (res.data.result.role !== '4') {
            get(
              '/pdf-tech/vppLicenseCode/checkCompanyLicense?companyId=' + res.data.result.companyId
            ).then((res) => {
              if (!res.data.result) {
                // this.$router.push('/non-admin-user')
                this.$router.push('/product?type=isNoAdmin')
                return
              }
            })
          } else {
            this.$router.push('/reseller-manage-product')
            return
          }
        }
        if (
          res.data.result.role?.indexOf("2") !== -1 || res.data.result.role?.indexOf("1") !== -1
        ) {
          this.$router.push('/dashboard')
        } else {
          this.$router.push('/non-admin-user')
          // this.$router.push('/product?type=isNoAdmin')
        }
      })
    },
    closeTrailForm() {
      this.showTrailForm = false
    }
  }
}
</script>

<template>
  <div class="bg w-full min-h-100vh flex justify-center items-center m-auto">
    <div class="flex w-1184px py-40px">
      <AsideInfo />
      <div class="w-704px bg-[#fff] flex justify-center rounded-r-16px">
        <div class="w-592px h-auto m-auto rounded-8px p-24px bg-[#fff]">
          <h1 class="text-24px font-500 mb-8px">Log in</h1>
          <div class="text-16px leading-24px text-[#404653] pb-8px border-b-1px border-[#E2E3E5]">
            Log into
            <span class="text-[#12B76A]">Admin Console</span>
            to manage licenses and devices
          </div>
          <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-position="top" label-width="100px"
            inline-message>
            <el-form-item prop="email">
              <div class="mt-24px text-[#404653] text-16px leading-24px mb-8px">Email</div>
              <div class="flex items-center">
                <el-input v-model.trim="ruleForm.email" @input="isDisable()" placeholder="Please enter email address." />
                <Error class="w-14px h-14px block absolute right-13px bottom-15px"
                  :class="emailError ? 'block' : 'hidden'" />
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <div class="text-[#404653] text-16px leading-24px mb-8px">Password</div>
              <div class="flex items-center">
                <el-input v-model="ruleForm.password" placeholder="Please enter password" @input="isDisable()"
                  @keyup.enter.native="submit()" :type="passwordType ? '' : 'password'">
                </el-input>
                <span v-show="ruleForm.password !== ''" class="show-password inline-block"
                  :class="passwordType ? 'eye-open' : 'eye-close'" @click="passwordType = !passwordType">
                  <EyeOpen v-show="passwordType" />
                  <EyeClose v-show="!passwordType" />
                </span>
                <Error class="w-14px h-14px block show-password" :class="passwordError ? 'block' : 'hidden'" />
              </div>
            </el-form-item>
            <el-form-item>
              <div class="flex justify-between items-center !text-12px">
                <el-checkbox label="Keep me logged in" name="type" v-model="remember"></el-checkbox>
                <router-link to="/forget-password" class="text-[#3686FF]">
                  Forgot Password?
                </router-link>
              </div>
            </el-form-item>
            <el-form-item>
              <button :disabled="empty" type="button" @click="submit()" :class="empty ? 'opacity-20' : 'hover:opacity-80'"
                class="w-full h-48px bg-[#0773ED] text-[#fff] rounded-8px">
                Log in
              </button>
            </el-form-item>
            <!-- <div class="flex justify-end">
              <router-link to="/sign-up" class="text-12px text-[#1460F3]">
                Create account
              </router-link>
            </div> -->
            <!-- <div class="flex justify-center">
              <a href="/free-trial-admin-console-signup" class="text-12px text-[#0773ED] cursor-pointer">
                Don't have an account?
              </a>
            </div> -->
            <div class="flex justify-center">
              <span @click="showTrailForm = true" class="text-12px text-[#1460F3] cursor-pointer">
                Don't have an account?
              </span>
            </div>
          </el-form>
          <div v-show="showTrailForm" class="bg-cover" @touchmove.stop.prevent></div>
          <TrailForm v-show="showTrailForm" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bg {
  background: #e7eaee url('@/assets/images/background.png') center center/100% 100% no-repeat;
  font-family: Ubuntu;
}

::v-deep.el-checkbox {
  &.is-checked .el-checkbox__inner {
    background-color: #3686FF;
    border-color: #3686FF;
  }

  .el-checkbox__label {
    font-size: 12px;
    line-height: 16px;
    color: #3686FF;
    font-weight: 400;
  }
}

.el-input::v-deep input {
  border: 0px !important;
  padding-right: 30px;
  border: 1px solid #d9d9d9 !important;
  border-radius: 4px !important;
}

.el-form::v-deep .el-form-item {
  margin-bottom: 28px;

  &.is-error {
    margin-bottom: 0;
  }
}

.show-password {
  position: absolute;
  right: 13px;
  top: 45px;
  width: 14px;
  height: 14px;
  cursor: pointer;
}

.bg-cover {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.5;
  z-index: 6;
}
</style>

