<template>
  <zpa-form class="LoginForm">
    <zpa-form-group title="登录信息">
      <zpa-text-input label="用户名" v-model="user.username" />
      <zpa-text-input
        label="密码"
        type="password"
        password
        v-model="user.password"
      />
      <p class="ErrorMessage" v-if="error">
        {{ error }}
      </p>
      <Button :loading="loading" type="primary" long @click="doLogin"
        >登录</Button
      >
    </zpa-form-group>
    <Modal v-model="tenantModal" title="选择租户" @on-ok="tenantOk">
      <zpa-row
        :span="8"
        style="background: #fff; overflow-y: auto"
        padding="24px"
      >
        <zpa-form>
          <zpa-select
            label="选择租户"
            :values="tenantList"
            value-field="topUnit"
            text-field="unitName"
            v-model="tenantId"
          />
        </zpa-form>
      </zpa-row>
    </Modal>
  </zpa-form>
</template>

<script>
import Vue from 'vue'
import { getUser, modifyUser } from '@centit/api-admin/user'
import { queryTopUnit } from '@centit/api-admin/unit'
import { mapMutations } from 'vuex'
import { getPosition, login } from '@centit/api-auth'

export default {
  name: 'LoginForm',

  data () {
    return {
      user: {},

      error: '',

      loading: false,

      userCode: '',
      tenantModal: false,
      tenantList: [],
      tenantId: ''
    }
  },

  computed: {
    lastRoute () {
      const defaultRoute = {
        name: 'Home'
      }
      if (this.$router.$lastRoute && this.$router.$lastRoute.name === 'Login') {
        return defaultRoute
      }
      return (
        this.$router.$lastRoute || {
          name: 'Home'
        }
      )
    }
  },

  methods: {
    ...mapMutations('core', ['setToken', 'setLoginInfo']),

    checkForm () {
      const { username, password } = this.user

      if (!username) {
        this.error = '用户名不能为空'
        return false
      } else if (!password) {
        this.error = '密码不能为空'
        return false
      } else {
        this.error = ''
      }

      return true
    },
    doLogin (e) {
      if (e) e.preventDefault()
      if (!this.checkForm()) return

      this.loading = true
      login(this.user)
        .then(({ accessToken, userInfo }) => {
          if (userInfo.userInfo.topUnit) { localStorage.setItem('topUnit', userInfo.userInfo.topUnit) }
          return getPosition().then(pos => {
            userInfo.userPosition = pos
            return {
              accessToken,
              userInfo
            }
          })
        })
        .then(this.afterLogin)
        .catch(e => {
          this.error = e.message
        })
        .finally(() => {
          this.loading = false
        })
    },
    afterLogin ({ accessToken, userInfo }) {
      this.setToken(accessToken)
      this.setLoginInfo(userInfo)
      if (!Vue.config.useTopUnit || userInfo.userInfo.topUnit) {
        this.$router.replace(this.lastRoute).then(() => {
          this.$router.$lastRoute = null
        })
      } else {
        this.userCode = userInfo.userInfo.userCode
        queryTopUnit({ userCode: userInfo.userInfo.userCode }).then(res => {
          this.tenantModal = true
          this.tenantList = res
        })
      }
    },
    tenantOk () {
      if (this.tenantId) {
        localStorage.setItem('topUnit', this.tenantId)
        getUser(this.userCode).then(user => {
          user.userInfo.topUnit = this.tenantId
          const data = {
            ...user.userInfo,
            ...{
              userRank: user.userUnit.userRank,
              userStation: user.userUnit.userStation
            }
          }
          modifyUser(this.userCode, data).then(res => {
            this.doLogin()
          })
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
.LoginForm {
  width: 360px;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px 32px;
  margin: 0 auto;

  .ErrorMessage {
    width: 100%;
    height: 32px;
    line-height: 32px;
    padding: 0 4px;
    color: firebrick;
  }
}
</style>
