<template>
  <div class="fle bgColor" v-if="!isSSo">
    <load-ing v-show="requesterLgoinType == 'wechat'"></load-ing>
    <h2
      v-if="requesterLgoinType == 'web'"
      style="font-size: 0.36rem; margin-bottom: 0.36rem; font-weight: 700"
    >
      运维管理平台
    </h2>
    <div v-if="requesterLgoinType == 'web'" style="width: 5rem">
      <cube-input
        v-model="zhanghao"
        placeholder="您的账号为学工号"
      ></cube-input>
      <br />
      <cube-input
        v-model="mima"
        type="password"
        placeholder="您的初始密码为学工号后四位"
      ></cube-input>
      <br />
      <cube-button @click="zlogin()" style="background: #005395"
        >登录</cube-button
      >
    </div>
  </div>
</template>

<script>
// 注意事项：个人微信需要关注微工作台，否则会导致没有userId（userId为openID）登录失败
import { decode } from "js-base64";
import LoadIng from "./../views/loading.vue";
export default {
  data() {
    return {
      zhanghao: "",
      mima: "",
      requesterLgoinType: "",
      isSSo: true // 是否单点登录
    };
  },
  components: {
    LoadIng
  },
  methods: {
    // 登陆
    login() {
      var that = this;
      that.$http.post("service/auth/wechatAuth", {}).then(res => {
        if (res.data.url) {
          window.location.href = res.data.url;
        } else {
          console.log(res.data);
          if (res.data.user) {
            localStorage.setItem(
              "loginUser",
              JSON.stringify(res.data.user.user)
            );
            localStorage.setItem("menu", JSON.stringify(res.data.user.menu));
            localStorage.setItem(
              "login_requester",
              JSON.stringify(res.data.user.requester)
            );
            that.getConfig(res.data.user.user,res.data.user.requester);
          }
        }
      });
    },
    // 获取code
    getCode() {
      var that = this;
      var url = window.location.href.split("?");
      if (!url[1]) {
        that.login();
      } else {
        var code = {
          code: url[1]
          // name: "微信处理人"
        };
        // alert("2--传code参数：");
        // alert(JSON.stringify(code));
        that.$http.post("service/auth/wechatLoginEncrypt", code).then(res => {
          if (res.data.state == 200) {
            console.log(res.data);
            // alert(3);
            // alert(JSON.stringify(res.data));
            if (res.data.user) {
              localStorage.setItem(
                "loginUser",
                JSON.stringify(res.data.user.user)
              );
              localStorage.setItem("menu", JSON.stringify(res.data.user.menu));
              localStorage.setItem(
                "login_requester",
                JSON.stringify(res.data.user.requester)
              );
              that.getConfig(res.data.user.user,res.data.user.requester);
            }
          } else if (res.data.state == 501) {
            that
              .$createDialog({
                type: "alert",
                title: "您的账号被删除，请联系管理员",
                icon: "cubeic-alert"
              })
              .show();
          } else {
            that
              .$createDialog({
                type: "alert",
                title: res.data.remarks,
                icon: "cubeic-alert"
              })
              .show();
          }
        });
      }
    },
    // 假登录
    login2() {
      var that = this;
      this.$http
        .post("service/auth/loginEncrypt", {
          // username: "DingDanDan",
          username: "admin",
          password: "20200326"
        })
        .then(function(res) {
          that.loading = false;
          if (res.data && res.data.state == 200) {
            localStorage.setItem(
              "loginUser",
              JSON.stringify(res.data.data.user)
            );
            localStorage.setItem("menu", JSON.stringify(res.data.data.menu));
            localStorage.setItem(
              "login_requester",
              JSON.stringify(res.data.data.requester)
            );
            that.getConfig(res.data.data.user,res.data.data.requester);
          }
        });
    },
    // 获取版本配置（报修主题：报修人/报修科室）
    // 获取配置
    getConfig(user,requester) {
      this.$http
        .post("service/sysinfo/data/fetchDataList/systemConfiguration", {
          idx: 0,
          sum: 1000
        })
        .then(res => {
          let list = res.data.list;
          list.forEach(v => {
            switch (v.keyconfig) {
              case "repairMain": //报修主体
                localStorage.setItem(
                  "valConfig",
                  JSON.stringify(v.valueconfig)
                );
                break;
              case "incidentWithConsumable": //是否绑定耗材
                localStorage.setItem("incidentWithConsumable", v.valueconfig);
                break;
              case "wxIncidentWithCmdb": //是否绑定资产
                localStorage.setItem("wxIncidentWithCmdb", v.valueconfig);
                break;
              case "ifWorking": //是否开通上下班
                localStorage.setItem("ifWorking", v.valueconfig);
                break;
              // case "wxBxQuestions": //微信报修常见问题链接
              //   localStorage.setItem("wxBxQuestions", v.valueconfig);
              //   break;
              // case "wxGuide": //微信报修服务指南链接
              //   localStorage.setItem("wxGuide", v.valueconfig);
              //   break;
              case "wxClQuestions": //微信处理常见问题链接
                localStorage.setItem("wxClQuestions", v.valueconfig);
                break;
              case "ifRoom": //是否增加房间号选择
                localStorage.setItem("ifRoom", v.valueconfig);
                break;
              case "integralMechanism": //积分机制
                localStorage.setItem("integralMechanism", v.valueconfig);
                break;
            }
          });
          this.roleHandler(user,requester);
        });
    },
    // 判断角色
    roleHandler(user,requester){
      let userRoles = user.role.map(v=>({id:v.id,rolecode:v.rolecode}));
      let isUser = false;
      if(userRoles.length){
        // this.isService = userRoles.some(v=>(v.rolecode === 'call center' || v.rolecode === 'call center admin'))
        isUser = userRoles.some(v=>(v.rolecode === 'first-line support' || v.rolecode === 'second-line support' || v.rolecode === 'incident manager' || v.rolecode === 'inspectman' || v.rolecode === 'incident-category-manager'))
      }else{
        // this.isService = false;
        isUser = false;
      }
      // this.isReq = requester ? true : false;
      if(isUser){
        this.$router.push({ path: "/main" });
      }else{
        this.$createDialog({
          type: "alert",
          title: "提示",
          content: "没有权限，无法进入！",
          icon: "cubeic-wrong",
          color: "red"
        }).show();
      }
    },
    // 获取报修人登录方式
    getLoginType() {
      this.$http.post("service/wechat/getLoginType", {}).then(result => {
        if (result.data.status == 200) {
          this.requesterLgoinType = result.data.data;
          window.localStorage.setItem(
            "requesterLgoinType",
            this.requesterLgoinType
          );
          if (this.requesterLgoinType == "wechat") {
            this.getCode();
          } else if (this.requesterLgoinType == "web") {
            // this.$router.push({ path: "/login" });
          }
        }
      });
    },
    // 账号密码登录
    zlogin() {
      console.log(this);
      var that = this;
      var ssoStr = "";
      var ssoJson;
      if (this.isSSo) {
        ssoStr = location.search
          .replace("?", "")
          .split("&")[0]
          .split("=")[1];
        ssoStr = decode(decodeURIComponent(ssoStr));
        ssoJson = JSON.parse(ssoStr);
      }
      var postData = this.isSSo
        ? { username: ssoJson.a, password: ssoJson.u, t: false }
        : { username: this.zhanghao, password: this.mima };
      this.$http.post("service/auth/loginEncrypt", postData).then(res => {
        that.loading = false;
        if (res.data && res.data.state == 200) {
          localStorage.setItem("loginUser", JSON.stringify(res.data.data.user));
          localStorage.setItem("menu", JSON.stringify(res.data.data.menu));
          localStorage.setItem(
            "login_requester",
            JSON.stringify(res.data.data.requester)
          );
          this.getConfig(res.data.data.user,res.data.data.requester);
        } else {
          that
            .$createDialog({
              type: "alert",
              title: "系统错误",
              content: "请稍后再试",
              icon: "cubeic-wrong",
              color: "red"
            })
            .show();
        }
      });
    },
    // 获取查询参数
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    }
  },
  created() {
    if (location.search.length > 0) {
      this.isSSo = Boolean(this.getQueryString("t"));
    } else {
      this.isSSo = false;
    }
    if (this.isSSo) {
      this.zlogin();
    }
    this.getLoginType();
  }
};
</script>

<style scoped>
.color {
  color: red;
  font-size: 1rem;
}
.fle {
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background: url(./../../static/images/weChartBackImage.jpg);
  background-size: cover;
}
/* .bgColor{
    background-color: white
  } */
input {
  border: 0.02rem #999999 solid;
  width: 60%;
  height: 0.8rem;
  margin-top: 0.4rem;
  border-radius: 10px;
  padding-left: 0.24rem;
}
input:nth-child(1) {
  margin-top: 0;
}
input:focus {
  outline: none;
}
.sub {
  width: 40%;
  background-color: rgb(60, 162, 254);
  height: 0.7rem;
  color: white;
  font-size: 0.36rem;
  text-align: center;
  line-height: 0.7rem;
  margin-top: 0.3rem;
  border-radius: 10px;
}
</style>
