<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: [],
      userList: [],
      company: null,
      authorityVisible: false,

      remember: true,
      authorityForm: {},
      form: {
        loginName: "",
        user: "",
        company: "",
        password: ""
      }
    };
  },
  created() {
    // this.len = Object.keys(this.$dataStore.store).length
    console.log(this.$dataStore, "this.$dataStore");
    // this.$dataStore.set('deviceIdceshi03','b27a0777451f789521f4240e99f65913')
    this.company = this.$dataStore.get("company");
    this.userList = this.$dataStore.get("userList") || [];
    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() {

      // if (this.form.auth) {
      //   this.$dataStore.set(this.form.auth.split(",")[0], this.form.auth.split(",")[1]);
      //   console.log("存储成功");
      //   console.log(this.$dataStore.store);
      //
      // }
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          let f = JSON.parse(JSON.stringify(this.form));
          if (f.company.split(".").length === 1) {
            f.company = f.company + ".jomalls.com";
          }
          if (!f.deviceId) {
            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);

          if (this.remember) {
            let userList = this.$dataStore.get("userList");
            if (userList && !userList.find(el => el.loginName === f.loginName && el.company === f.company)) {
              userList.push(f);
            } else {
              userList = [f];
            }
            this.$dataStore.set("userList", userList);
          }

          await this.$router.push("/design");
        }
      });


    },
    userChange(v) {
      if (v === "") {
        this.form.deviceId = "";
        return;
      }
      console.log(this.userList, v);
      this.form.company = this.userList[v].company.split(".")[0];
      this.form.loginName = this.userList[v].loginName;
      this.form.password = this.userList[v].password;
      this.form.deviceId = this.userList[v].deviceId;
    },
    async getCompanyList() {
      let { data } = await this.$api.get("/getCompanyList");
      this.companyList = data.records;
    }
  }
};
</script>

<template>
  <div class="login">
    <div class="form-content">
      <el-form v-if="" ref="formRef" :rules="rules" size="small" :model="form">
        <el-form-item v-if="userList.length>0">
          <el-select @change="userChange" filterable style="width: 100%;" placeholder="登录记录" v-model="form.user"
                     clearable>
            <template slot="prefix">
              <i class="el-icon-monitor"></i>
            </template>
            <el-option v-for="(it,i) in userList" :key="i" :label="`${it.loginName}(${it.company.split('.')[0]})`"
                       :value="i"></el-option>
          </el-select>
        </el-form-item>
        <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 v-if="len===0" prop="授权信息">-->
<!--          <el-input placeholder="授权信息" prefix-icon="el-icon-lock" v-model="form.auth"-->
<!--                    clearable></el-input>-->
<!--        </el-form-item>-->
        <div class="check">
          <el-checkbox v-model="remember">记住账号</el-checkbox>
        </div>
        <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 lang="less" scoped>
.check {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.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>