<script>

export default {
  data() {
    return {
      rules: {
        company: [{validator: this.validatePass, required: true, trigger: 'blur'}],
        loginName: [{message: '请输入用户名', required: true, trigger: 'blur'}],
        password: [{message: '请输入密码', required: true, trigger: 'blur'}],
      },
      companyList: [],
      company: null,
      authorityVisible: false,
      authorityForm: {},
      form: {
        loginName: '',
        company: '',
        password: ''
      }
    }
  },
  created() {

    this.company = this.$dataStore.get('company')
    if (this.company) {
      this.form.company = this.company.domain
    }
    // if (user) {
    //   return this.$router.push('/design')
    // }
    this.getCompanyList()
  },
  mounted() {
    document.addEventListener('keyup', this.keyUp)
  },
  beforeDestroy() {
    document.removeEventListener('keyup', this.keyUp)
  },
  methods: {
    keyUp(e) {
      console.log(e)
      if (e.keyCode === 13) {
        this.login()
      }
    },
    submitAuthority() {
      this.$refs.authorityForm.validate((v) => {
        if (v) {
          this.$api.post('/commitApply', {
            ...this.authorityForm,
            ...this.form
          }, {
            headers: {
              'company': this.form.company + '.jomalls.com'
            }
          }).then((res) => {
            if (res.code === 200) {
              this.authorityVisible = false
              this.$message.success('申请提交成功')
              this.$dataStore.set('deviceId' + this.form.loginName, res.data.id)
            }
          })
        }
      })
    },
    validatePass(rule, value, callback) {
      if (!value || value === '') {
        return callback(new Error('请输入客户（例如demo)'));
      }
      let item = this.companyList.find(item => item.domain.replace('.jomalls.com', '') === value)
      if (item) {
        return callback()
      } else {
        return callback(new Error('未查找到该客户'))
      }
    },
    async login() {

      this.$refs.formRef.validate(async valid => {
        if (valid) {
          let f = JSON.parse(JSON.stringify(this.form))
          f.company = f.company.includes('.jomalls.com') ? f.company : f.company + '.jomalls.com'

          f.deviceId = this.$dataStore.get('deviceId' + this.form.loginName)
          if (!f.deviceId) delete f.deviceId
          let {data, code, message} = await this.$api.post('/login', f)
          if (code === 411) {
            this.authorityVisible = true
            this.authorityForm = {}
            return this.$message.error(message)
          }
          data = {
            ...data.sysUser,
            ...{
              token: data.token
            }
          }
          delete data.sysMenus
          delete data.sysUser
          let item = this.companyList.find(item => item.domain === f.company)
          console.log(item, 111222)
          this.$dataStore.set('user', data)
          this.$dataStore.set('company', item)
          this.$message.success('登录成功')

          await this.$router.push('/design')
        }
      })


    },
    async getCompanyList() {
      let {data} = await this.$api.get('/getCompanyList')
      this.companyList = data.records
    }
  }
}
</script>

<template>
  <div class="login">
    <div class="form-content">
      <el-form ref="formRef" :rules="rules" size="small" :model="form">
        <el-form-item v-if="!company" prop="company">
          <el-input placeholder="客户（例如demo）" prefix-icon="el-icon-monitor" v-model="form.company"
                    clearable></el-input>
          <!--          <el-select filterable style="width: 100%;" placeholder="系统" v-model="form.company"-->
          <!--                     clearable>-->
          <!--            <template slot="prefix">-->
          <!--              <i class="el-icon-monitor"></i>-->
          <!--            </template>-->
          <!--            <el-option v-for="(it,i) in companyList" :key="i" :label="it.companyName" :value="it.domain"></el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item prop="loginName">
          <el-input placeholder="用户名" prefix-icon="el-icon-user" v-model="form.loginName" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="密码" show-password prefix-icon="el-icon-lock" type="password" v-model="form.password"
                    clearable></el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex;justify-content: center">
            <el-button @keyup.enter.native="login" @click="login" type="primary" style="width: 60%;">登录</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
        :close-on-click-modal="false"
        title="权限申请"
        :visible.sync="authorityVisible"
        top="15%"
        width="400px">
      <el-form
          :model="authorityForm"
          size="mini"
          ref="authorityForm"
          label-width="80px">
        <el-form-item label="设备名称" prop="deviceName" required>
          <el-input v-model="authorityForm.deviceName"></el-input>
        </el-form-item>
        <el-form-item label="授权类型" prop="authType" required>
          <el-radio v-model="authorityForm.authType" label="1">
            一次授权
          </el-radio>
          <el-radio v-model="authorityForm.authType" label="2">
            永久授权
          </el-radio>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button size="mini" @click="authorityVisible = false">
          取 消
        </el-button>
        <el-button size="mini" type="primary" @click="submitAuthority">
          提交
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.login {
  width: 100%;
  height: 100%;
  background-image: url("../../assets/logo-bg.jpg");
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-content {
  width: 300px;
  padding-top: 50px;
}

.el-icon-monitor {
  position: relative;
  left: 6px;
}
</style>