<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="username">
      <Input v-model="form.username" :size="'large'" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" :size="'large'" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" :size="'large'" long style="font-size: large;text-align: center;line-height:1;" :disabled="loggingIn">
        <span v-if="!loggingIn">登录</span>
        <Icon v-if="loggingIn" type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      </Button>
    </FormItem>
    <Modal
      v-model="showSecondaryPasswordBox"
      title="请输入二级密码进行验证"
      @on-ok="checkSecondaryPassword">
      <Input v-model="secondaryPassword" placeholder="请输入二级密码"></Input>
    </Modal>
  </Form>
</template>
<script>

import ukeyPassword from '../../../ukey/ukey-password'
import { mapActions } from 'vuex'
const publicIp = require('public-ip');

export default {
  name: 'LoginForm',
  components: {
    ukeyPassword,
  },
  props: {

  },
  data () {
    return {
      form: {
        username: '',
        password: '',
      },
      usernameRules: { required: true, message: '账号不能为空', trigger: 'blur' },
      passwordRules: { required: true, message: '密码不能为空', trigger: 'blur' },
      loggingIn: false,
      loginName: '',
      useUkeyFlag: false,
      ukey: null,
      showSecondaryPasswordBox: false,
      secondaryPassword: null
    }
  },
  computed: {
    rules () {
      return {
        username: this.usernameRules,
        password: this.passwordRules
      }
    }
  },
  methods: {
    ...mapActions([
      'handleLogin',
      'getUserInfo'
    ]),
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.doSubmit({
            username: this.form.username,
            password: this.form.password
          })
        }
      })
    },
    ukeyPassword (bean) {
      this.ukey = bean
    },
    doSubmit ({ username, password }) {
      if (this.$config.deploymentStandAlone){
        this.handleCommon(username, password)
      }else {
        try{
          this.$refs.ukeyPasswordEdit.checkBasicUkey({
            ukeyHolderLoginname: this.$refs.loginForm.form.username,
            state: 1
          })
            .then(data => {
              let result = data.result
              if (result) {
                let loginIsCheck = result.loginIsCheck
                if (loginIsCheck) {
                  let ukeyCode = result.ukeyCode
                  if (ukeyCode) {
                    if (!this.ukey) {
                      this.$Message.error('请先点击检测UKEY按钮进行检测!')
                      return false
                    }
                    if (ukeyCode != this.ukey.ukeyCode) {
                      this.$Message.error('用户名和ukey不匹配，请更换ukey插入!')
                      return false
                    }
                    if (!this.useUkeyFlag) {
                      this.$Message.error('ukey验证失败！')
                      return false
                    }
                  }
                }
              }
              this.handleCommon(username, password)
            }).catch(err => {
              this.handleCommon(username, password)
          })
        }catch{
          this.handleCommon(username, password)
        }
      }

    },
    handleCommon (username, password,secondaryPassword) {
      this.loggingIn = true//开启登录中模式
      this.handleLogin({ username, password, secondaryPassword }).then(res => {
        this.$Message.success('登录成功')
        this.getUserInfo().then(res => {
          this.loggingIn = false//关闭登录中模式
          if(this.$config.deploymentStandAlone){
            /**/
            window.location.href = '/home'
            /*this.$router.push({
              name: this.$config.homeName
            })*/
          }else {
            this.$router.push({
              name: this.$config.PThomeName
            })
          }

        }).catch(err => {
          this.$Message.error(err)
          this.loggingIn = false//关闭登录中模式
        })
      }).catch(err => {
        console.log(err)
        if (err.response.status == '601' || err.response.status == '602' || err.response.status == '603') {
          this.$Message.warning(err.response.data.message)
          this.showSecondaryPasswordBox = true
        } else if (err.response.data.error == '400') {
          this.$Message.error('用户名或密码错误')
        } else if (err.response.data.error == '500') {
          this.$Message.error('系统异常,请稍后再试')
        } else {
          this.$Message.error(err.response.data.message)
        }
        this.loggingIn = false//关闭登录中模式
      })
    },
    checkSecondaryPassword(){
      this.handleCommon(this.form.username, this.form.password, this.secondaryPassword)
    }
  },
  mounted () {
    //加入本机ip
    let ip = sessionStorage.getItem("ip")
    //记录当前登设备的ip,这里的没啥用.第一次提交的时候,由于异步,根本拿不到ip,
    //有用的在login登录页面
    if (!ip) {
      publicIp.v4().then(ip => {
        sessionStorage.setItem("ip", ip)
      });
    }
  },
  watch:{
    loginName(){
      this.form.username = this.loginName
      if(this.show){
        this.form.username = '';
      }
    },
  }
}
</script>
<style>
.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
</style>
