<template>
  <div class="matrix-login">
    <div class="matrix-login--container">
      <div class="matrix-login--container--content">
        <div class="matrix-login--container--content__left">
          <div class="matrix-login--container--content__left--logo">
            <img src="@/assets/images/logo.png" alt="" />
            <span>北京华软恒信</span>
          </div>
          <div class="matrix-login--container--content__left--content">
            <img src="@/assets/svg/login-box-bg.svg" alt="" />
            <div class="matrix-login--container--content__left--content--title">生产管控一体化系统平台</div>
            <div class="matrix-login--container--content__left--content--description">
              北京华软恒信科技发展有限公司出品
            </div>
          </div>
        </div>
        <div class="matrix-login--container--content__right">
          <div class="matrix-login--container--content__right--content">
            <div class="matrix-login--container--content__right--content--form">
              <h1>登录</h1>
              <a-form :form="form" class="user-layout-login" @keyup.enter.native="loginSubmit">
                <a-form-item>
                  <a-input v-decorator="['username', validatorRules.username]" placeholder="账号" size="large" />
                </a-form-item>
                <a-form-item ref="password" prop="password">
                  <a-input-password
                    v-decorator="['password', validatorRules.password]"
                    type="password"
                    placeholder="密码"
                    size="large"
                    autocomplete="false"
                    style="margin-top: 8px"
                  />
                </a-form-item>
              </a-form>
              <a-row style="margin-top: 12px">
                <a-col :span="12">
                  <a-checkbox>记住我</a-checkbox>
                </a-col>
                <a-col :span="12" style="text-align: right">
                  <a-button type="link" size="small">忘记密码？</a-button>
                </a-col>
              </a-row>
              <a-button
                block
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="loading"
                style="margin: 18px 0"
                @click.stop.prevent="loginSubmit"
              >
                登录
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <a-modal title="登录部门选择" :width="450" :visible="departVisible" :closable="false" :maskClosable="false">
      <template slot="footer">
        <a-button type="primary" @click="departOk">确认</a-button>
      </template>

      <a-form>
        <a-form-item
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 20 }"
          style="margin-bottom: 10px"
          :validate-status="validate_status"
        >
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>您隶属于多部门，请选择登录部门</span>
            </template>
            <a-avatar style="background-color: #87d068" icon="gold" />
          </a-tooltip>
          <a-select
            :class="{ 'valid-error': validate_status === 'error' }"
            placeholder="请选择登录部门"
            style="margin-left: 10px; width: 80%"
            @change="departChange"
          >
            <a-icon slot="suffixIcon" type="gold" />
            <a-select-option v-for="d in departList" :key="d.id" :value="d.orgCode">
              {{ d.departName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { mapActions } from 'vuex'
import { putAction } from '@/api/manage'
import { timeFix } from '@/utils/util'

export default {
  name: 'LoginPortal',
  data() {
    return {
      loading: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      form: this.$form.createForm(this),
      validatorRules: {
        username: { rules: [{ required: true, message: '请输入用户名!', validator: 'click' }] },
        password: { rules: [{ required: true, message: '请输入密码!', validator: 'click' }] },
        captcha: { rule: [{ required: true, message: '请输入验证码!' }] },
        inputCode: { rules: [{ required: true, message: '请输入验证码!' }, { validator: this.validateInputCode }] }
      },
      verifiedCode: '',
      inputCodeContent: '',
      inputCodeNull: true,

      departList: [],
      departVisible: false,
      departSelected: '',
      currentUsername: '',
      validate_status: ''
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.setRouterUserData()
  },
  methods: {
    ...mapActions(['Login', 'Logout', 'PhoneLogin']),

    /**
     * 校验验证码
     * @param rule
     * @param value
     * @param callback
     */
    validateInputCode(rule, value, callback) {
      if (!value || this.verifiedCode === this.inputCodeContent) {
        callback()
      } else {
        callback('您输入的验证码不正确!')
      }
    },

    /**
     * 登录
     */
    loginSubmit() {
      let that = this
      let loginParams = {}
      that.loading = true
      // 使用账户密码登陆
      that.form.validateFields(['username', 'password', 'inputCode', 'rememberMe'], { force: true }, (err, values) => {
        if (!err) {
          loginParams.username = values.username
          loginParams.password = values.password
          loginParams.remember_me = values.rememberMe
          that
            .Login(loginParams)
            .then(res => {
              localStorage.setItem('username', loginParams.username)
              localStorage.setItem('password', loginParams.password)
              // 登录部门确认
              this.departConfirm(res)
            })
            .catch(() => (this.loading = false))
        } else {
          that.loading = false
        }
      })
    },

    /**
     * 登录成功
     */
    loginSuccess() {
      this.loading = false
      this.$router.push({ name: 'dashboard' })
      this.$notification.success({
        message: `${timeFix()} ${this.$store.getters.userInfo.realname}！`,
        description: '欢迎回来 🎉🎉🎉'
      })
    },

    /**
     * 登录失败
     */
    requestFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.loading = false
    },

    /**
     * 登录部门确认
     * @param res
     */
    departConfirm(res) {
      if (res.value.userInfo.passwordOverdue) {
        this.loading = false
        this.$message.warn('您的密码已过期请更换密码！')
        this.handleChangePassword(res.value.userInfo.username)
        return
      }
      if (res.code === '200') {
        let multi_depart = res.value.multi_depart
        //0:无部门 1:一个部门 2:多个部门
        if (multi_depart === 0) {
          this.loginSuccess()
          this.$notification.warn({
            message: '提示',
            description: `您尚未归属部门,请确认账号信息`,
            duration: 3
          })
        } else if (multi_depart === 2) {
          this.departVisible = true
          this.currentUsername = this.form.getFieldValue('username')
          this.departList = res.value.departs
        } else {
          this.loginSuccess()
        }
      } else {
        this.requestFailed(res)
        this.Logout()
      }
    },

    /**
     * 确认登录部门
     * @return {boolean}
     */
    departOk() {
      if (!this.departSelected) {
        this.validate_status = 'error'
        return false
      }
      let obj = {
        orgCode: this.departSelected,
        username: this.form.getFieldValue('username')
      }
      putAction('/sys/selectDepart', obj).then(res => {
        if (res.code === '200') {
          const userInfo = res.value.userInfo
          Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
          this.$store.commit('SET_INFO', userInfo)
          this.departClear()
          this.loginSuccess()
        } else {
          this.requestFailed(res)
          this.Logout().then(() => {
            this.departClear()
          })
        }
      })
    },

    /**
     * 清理部门
     */
    departClear() {
      this.departList = []
      this.departSelected = ''
      this.currentUsername = ''
      this.departVisible = false
      this.validate_status = ''
    },

    /**
     * 部门变更回调
     * @param value
     */
    departChange(value) {
      this.validate_status = 'success'
      this.departSelected = value
    },

    /**
     * 存储路由用户数据
     */
    setRouterUserData() {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          username: this.$route.params.username
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}

.matrix-login {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  position: relative;

  &:before {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    margin-left: -48%;
    background-image: url('../../assets/svg/login-bg.svg');
    background-position: 100%;
    background-repeat: no-repeat;
    background-size: auto 100%;
    content: '';
    z-index: -1;
  }

  &--container {
    width: 80%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    &--content {
      width: 100%;
      height: 90%;
      display: flex;
      position: relative;

      &__left {
        width: 50%;
        height: 100%;
        position: relative;
        display: flex;
        justify-content: flex-end;

        &--logo {
          height: 50px;
          display: flex;
          position: absolute;
          top: 0;
          left: 0;

          img {
            width: 50px;
            height: 50px;
          }

          span {
            height: 100%;
            font-size: 24px;
            font-weight: 700;
            color: #ffffff;
            margin-left: 10px;
            display: flex;
            align-items: center;
          }
        }

        &--content {
          position: absolute;
          top: 50%;
          margin-top: -170px;
          margin-right: 40%;

          img {
            width: 368px;
            margin-bottom: 30px;
          }

          &--title {
            font-size: 30px;
            font-weight: 500;
            color: #ffffff;
            margin-top: 30px;
          }

          &--description {
            font-size: 14px;
            color: #ffffff;
            margin-top: 20px;
          }
        }
      }

      &__right {
        width: 50%;
        height: 100%;
        position: relative;

        &--content {
          position: absolute;
          top: 50%;
          margin-left: 30%;
          margin-top: -135px;

          &--form {
            width: 400px;
          }
        }
      }
    }
  }
}
</style>
