<template>
  <common-layout>
    <div class="loginContent">
      <div class="illustration"/>
      <div class="business">
        <div class="top">
          <div class="header">
            <span class="title">{{ systemName }}</span>
          </div>
        </div>
        <div class="login" id="loginForm">
          <a-form :form="form" @submit="onSubmit">
            <a-tabs :tabBarStyle="{textAlign: 'center'}" size="large" style="padding: 0 2px;">
              <a-tab-pane key="1" tab="账户密码登录">
                <a-alert
                  v-show="error"
                  :closable="false"
                  :message="error"
                  showIcon
                  style="margin-bottom: 2.8vh;"
                  type="error" />
                <a-form-item>
                  <a-input
                    v-decorator="['name', {rules: [{ required: true, message: '请输入账户名', whitespace: true}]}]"
                    autocomplete="autocomplete"
                    placeholder="请输入账户名"
                    size="large"
                  >
                    <a-icon slot="prefix" type="user" />
                  </a-input>
                </a-form-item>
                <a-form-item>
                  <a-input
                    v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]"
                    autocomplete="autocomplete"
                    placeholder="请输入密码"
                    size="large"
                    type="password"
                  >
                    <a-icon slot="prefix" type="lock" />
                  </a-input>
                </a-form-item>
                <a-form-item>
                  <a-button :loading="loading" htmlType="submit" size="large" class="btn" type="primary">登录</a-button>
                </a-form-item>
              </a-tab-pane>
            </a-tabs>
          </a-form>
        </div>
      </div>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from '@vue2-client/layouts/CommonLayout'
import { getRoutesConfig, login, V4Login } from '@vue2-client/services/user'
import { setV4AccessToken } from '@vue2-client/utils/login'
import { setAuthorization } from '@vue2-client/utils/request'
import { loadRoutes, funcToRouterOA, funcToRouter } from '@vue2-client/utils/routerUtil'
import { mapMutations, mapState } from 'vuex'
import JSEncrypt from 'jsencrypt'
import { ACCESS_TOKEN } from '@vue2-client/store/mutation-types'
import { positions } from '@vue2-client/mock/common'
import { timeFix } from '@vue2-client/utils/util'
import { loginStart } from '@vue2-client/base-client/plugins/compatible/LoginServiceOA'
import { indexedDB } from '@vue2-client/utils/indexedDB'
import Vue from 'vue'

export default {
  name: 'Login',
  components: { CommonLayout },
  data () {
    return {
      loading: false,
      error: '',
      form: this.$form.createForm(this)
    }
  },
  computed: {
    ...mapState('setting', ['systemName', 'systemDesc', 'homePage', 'ticketPage', 'compatible', 'routeName', 'defaultAvatarUrl'])
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    onSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.loading = true
          const name = this.form.getFieldValue('name')
          const password = this.form.getFieldValue('password')
          switch (this.compatible) {
            case 'V2':
            case 'V3': {
              login(name, password).then(this.afterLogin).catch(msg => {
                this.error = msg
                this.loading = false
              })
              break
            }
            case 'OA' : {
              loginStart(name, password).then(this.afterLoginOA).catch(msg => {
                this.error = msg
                this.loading = false
              })
              break
            }
            case 'V4' : {
              V4Login(name, password, this.routeName).then(this.afterLoginV4).catch(msg => {
                this.error = msg
                this.loading = false
              })
              break
            }
          }
        }
      })
    },
    afterLoginOA (result) {
      try {
        // 默认第一个是旧OA地址
        result.functions[0].navigate = result.functions[0].link
        result.functions[0].link = null
        this.afterGeneral(result)
        this.setAccessToken(result.password)
        this.$router.push(this.homePage).catch(() => {
        })
      } catch (res) {
        this.error = res
      } finally {
        this.loading = false
      }
    },
    afterLoginV4 (res) {
      setV4AccessToken(res)
      let data = res.resources
      if (data.data) {
        data = data.data
      }
      this.$login.login(data).then(() => {
        this.afterGeneral(data)
        if (data.deps === '用户工单登记') {
          this.$router.push(this.ticketPage).catch(() => {
          })
        } else {
          this.$router.push(this.homePage).catch(() => {
          })
        }
      }).catch(res => {
        this.error = res
      }).finally(() => {
        this.loading = false
      })
    },
    afterLogin (res) {
      const name = this.form.getFieldValue('name')
      const password = this.form.getFieldValue('password')
      const loginRes = res.states
      if (loginRes === '登录成功') {
        const encrypt = new JSEncrypt()
        encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqPvovSfXcwBbW8cKMCgwqNpsYuzF8RPAPFb7LGsnVo44JhM/xxzDyzoYtdfNmtbIuKVi9PzIsyp6rg+09gbuI6UGwBZ5DWBDBMqv5MPdOF5dCQkB2Bbr5yPfURPENypUz+pBFBg41d+BC+rwRiXELwKy7Y9caD/MtJyHydj8OUwIDAQAB')
        const data = encrypt.encrypt(JSON.stringify({ username: name, password: password }))
        // 获取路由配置
        getRoutesConfig(data, this.routeName).then(result => {
          this.$login.login(result).then(() => {
            // V3任何情况首位加入资源管理
            const resourceManageMain = {
              name: '资源管理',
              icon: 'api',
              position: 1,
              link: 'resourceManageMain'
            }
            result.functions.unshift(resourceManageMain)
            this.afterGeneral(result)
            this.setAccessToken(data)
            if (result.deps === '用户工单登记') {
              this.$router.push(this.ticketPage).catch(() => {})
            } else {
              this.$router.push(this.homePage).catch(() => {})
            }
          }).finally(() => {
            this.loading = false
          })
        }).catch(res => {
          this.error = res
        })
      } else {
        this.error = loginRes
        this.loading = false
      }
    },
    afterGeneral (result) {
      const user = Object.assign({
        id: result.id,
        username: result.ename,
        password: this.form.getFieldValue('password'),
        name: result.name,
        avatar: result.avatar ? result.avatar : this.defaultAvatarUrl,
        address: '西安市',
        position: positions[0]
      }, result)
      this.setUser(user)
      this.setPermissions(Vue.$login.r || [])
      this.setRoles(result.rolestr?.split(',') || [])
      let func
      switch (this.compatible) {
        case 'OA' :
          func = funcToRouterOA(user.functions)
          break
        default:
          func = funcToRouter(user.functions)
          break
      }
      loadRoutes(func)
      // 每次重新登录时，清除indexedDB缓存
      indexedDB.clear()
      this.$message.success(timeFix().CN + `，${result.name} 欢迎回来`, 3)
    },
    setAccessToken (data) {
      if (data) {
        localStorage.setItem(ACCESS_TOKEN, data)
        let timestamp = new Date().getTime()// 当前的时间戳
        timestamp = timestamp + 12 * 60 * 60 * 1000
        // 格式化时间获取年月日, 登陆过期时间
        const dateAfter = new Date(timestamp)
        setAuthorization({ token: data, expireAt: dateAfter })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.common-layout {
  background-image: url('/public/img/login/background.webp');
  background-size: cover;
  background-position: center;
  .content {
    .loginContent {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 63vw;
      padding: 12.4vh 4.8vw 13.4vh 3.5vw;
      @media screen and (max-width: 479px) {
        padding: 6.4vh 4.8vw 4.4vh 3.5vw;
      }
      transform: translate(-50%, -50%);
      background: #fff;
      border-radius: 30px;
      display: flex;
      .illustration {
        flex: 1;
        background-image: url("/public/img/login/illustration.webp");
        background-size: contain;
        background-position: center;
        background-repeat: no-repeat;
        @media screen and (max-width: 959px) {
          flex: 0;
        }
      }
      .business {
        flex: 1;
        .top {
          text-align: center;
          .header {
            height: 2vh;
            line-height: 2.7vh;
            padding-bottom: 5.4vh;
            .title {
              font-size: 1.5rem;
              @media screen and (max-width: 479px) {
                font-size: 1rem;
              }
              @media screen and (min-width: 480px) and (max-width: 767px) {
                font-size: 1.3rem;
              }
              @media screen and (min-width: 768px) and (max-width: 959px) {
                font-size: 1.5rem;
              }
              @media screen and (min-width: 960px) {
                font-size: 1.3rem;
              }
              @media screen and (min-width: 1200px) {
                font-size: 1.5rem;
              }
              color: #333333;
              font-weight: bold;
              font-family: 'Microsoft YaHei UI Light', 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
              letter-spacing: 0.13rem;
            }
          }
        }
        .login{
          width: 20vw;
          margin: 0 auto;
          @media screen and (max-width: 479px) {
            width: 50vw;
          }
          @media screen and (min-width: 480px) and (max-width: 767px) {
            width: 50vw;
          }
          @media screen and (min-width: 768px) and (max-width: 959px) {
            width: 40vw;
          }
          @media screen and (min-width: 960px) {
            width: 20vw;
          }
          @media screen and (min-width: 1200px) {
            width: 20vw;
          }
          .btn {
            width: 100%;
            min-height: 43px;
            height: 5.4vh;
            border-radius: 30px;
            background-color: #4F93FE;
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.common-layout {
  .footer {
    .copyright {
      color: #fff !important;
    }
  }
}
#loginForm {
  .ant-input {
    border-radius: 30px;
  }
  .ant-input-lg {
    min-height: 43px;
    height: 5.4vh;
  }
  .ant-tabs-bar {
    margin-bottom: 24px;
  }
  .ant-input-affix-wrapper {
    font-size: 1.15rem;
  }
  .ant-input-affix-wrapper .ant-input:not(:first-child) {
    padding-left: 2.4vw;
    @media screen and (max-width: 479px) {
      padding-left: 10vw;
    }
    @media screen and (min-width: 480px) and (max-width: 767px) {
      padding-left: 8vw;
    }
    @media screen and (min-width: 768px) and (max-width: 959px) {
      padding-left: 5vw;
    }
    @media screen and (min-width: 960px) {
      padding-left: 4vw;
    }
    @media screen and (min-width: 1200px) {
      padding-left: 2.4vw;
    }
  }
  .ant-input-affix-wrapper .ant-input-prefix, .ant-input-affix-wrapper .ant-input-suffix {
    color: #4F93FE;
  }
  .ant-alert {
    border-radius: 12px;
  }
}
</style>
