<template>
  <div>
    <div class="image">
      <img
        src="static/images/init.gif"
        alt=""
        style="width:100%;height:100%;"
      />
      <span style="text-align:center;color:#5f5a5a;"
        >管理执行难，就用功道云</span
      >
      <transition name="fade">
        <p
          v-show="pShow"
          style="text-align:center;color:rgb(160 160 160);font-size：13px;"
        >
          请联系客服4006877880
          <span>
            或，<a class="CXDL" href="" @click="$router.push({push:'/login'})">去登录</a>
          </span>
        </p>
      </transition>
      <transition name="fade">
        <el-button
          v-show="buttonShow"
          :disabled="disabledBt"
          type="primary"
          style="font-size:15px;margin:14px 0 0 36px;"
          @click="reconnection"
          >重新连接</el-button
        >
      </transition>
    </div>

    <el-dialog
      :title="$t('login.dialogVisible')"
      :visible.sync="dialogVisible"
      append-to-body
      width="400"
    >
      <el-button
        style="margin:5px 0; width:100%;"
        @click="loginBySite(item.site.id)"
        v-for="(item, index) in site_list"
        :key="index"
        size="medium"
        >{{ item.site.name }}
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import {
  getToken,
  setToken,
  getUser,
  getPasw,
  setUser,
  setPasw,
  removeAllToken
} from "@/utils/auth"; // getToken from cookie
import requests from "@/utils/request-user";
let nextReconnection = 3;
export default {
  data() {
    return {
      username: 0,
      password: 0,
      pShow: false, //按钮的显示隐藏
      buttonShow: false, //按钮的显示隐藏
      disabledBt: false,

      loginForm: {
        tel: "",
        password: ""
      },
      user: "",

      dialogVisible: false,
      site_list: []
    };
  },
  components: {},
  watch: {
    buttonShow() {
      // console.log(this.buttonShow);
      if (this.buttonShow) {
        this.disabledBt = false;
      } else {
        this.disabledBt = true;
      }
    }
  },
  created() {
    // this.$store.dispatch("LogOut");
    // console.log(this.$store.getters.addRouters.length);
    // if (this.$store.getters.addRouters.length > 0) { // 判断是否已经刷新
    //   return window.location.reload()
    // }
    this.clearData();
    // autoLogin?MTMxMTMxOTU4NDUsMTIzNDU2Nw
    // autoLogin?MTMxMTMxOTU4NDUsMTIzNDU2
    //15817743610
    //MTU4MTc3NDM2MTAsMTIzNDU2
    //autoLogin?MTU4MTc3NDM2MTAsMTIzNDU2
    //autoLogin?MTU4MTc3NDM2MTAsMTIzNDU2Nw
    this.windowUrl();
  },
  methods: {
    // window.open('http://p.qiao.baidu.com/cps/chat?siteId=10793815&userId=3040844','_blank')
    clearData() {
      localStorage.clear();
      sessionStorage.clear();
      // setCookie("Admin-Token", "", -1);  
      // this.$store.dispatch('LogOut');
    },
    windowUrl() {
      var url = window.location.href; //获取url中"?"符后的字串
      // console.log(url)
      if(url){
        if (url.split("?")[1]) {
          var item = url.split("?")[1];
          this.user = item;
          // console.log(window.btoa('15817743610,1234567'))

          var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
          var paramsString = "?name=XX";
          if(base64regex.test(item)){//判断是否为正确Base64码
          // 　console.log('yes')
            if (window.atob(item).split(",").length > 1) {
              this.username = window.atob(item).split(",")[0];
              this.password = window.atob(item).split(",")[1];

              if (!this.username || !this.password) {
                this.error_message()
              } else {
                (this.loginForm.tel = this.username),
                  (this.loginForm.password = this.password);
                this.handleLogin();
              }
            } else {
              this.error_message()
            }
          }else{
            this.error_message()
          }
        } else {
          this.pushLogin();
        }
      }
    },
    error_message(){
      setTimeout(()=>{
        this.$message("自动登陆失败，请重新登陆或联系客服：4006877880");
        this.buttonShow = true
      },2000)
    },
    reconnection() {
      this.buttonShow = !this.buttonShow;
      nextReconnection = nextReconnection - 1;
      // console.log(nextReconnection)
      if (nextReconnection < 1) {
        this.buttonShow = false;
        setTimeout(() => {
          this.pShow = true;
        }, 1500);
      } else {
        this.windowUrl();
      }
    },

    handleLogin() {
      const self = this;
      this.$store
        .dispatch("LoginByUsername", this.loginForm)
        .then(ret => {
          // console.log(ret);
          if (ret.code == 1) {
            if (this.checked) {
              // 转成DB5并保持在Cookies
              let user = window.btoa(
                this.random(5) + this.loginForm.tel + this.random(5)
              );
              let password = window.btoa(
                this.random(5) + this.loginForm.password
              );
              setUser(user);
              setPasw(password);
            }
            requests.defaults.headers.common["A-TOKEN"] = ret.data.token;
            self.site_list = ret.data.account_site;
            if (self.site_list !== null && self.site_list.length == 0) {
              //无企业--情况
              this.loginExperience(); //无企业进入体验账号
            } else if (self.site_list.length == 1) {
              localStorage.setItem(
                "Experience_data",
                JSON.stringify({ if: false, name: "" })
              );
              self.loginBySite(self.site_list[0].site.id);
            } else {
              localStorage.setItem(
                "Experience_data",
                JSON.stringify({ if: false, name: "" })
              );
              self.dialogVisible = true;
            }
          } else {
          }
        })
        .catch(() => {
          this.buttonShow = !this.buttonShow;
        })
        .finally(err => {});
    },
    loginExperience() {
      //进入体验站点
      let self = this;
      let num = 112; //112是其中一个体验公司
      let jurisdiction = "creator";
      requests({
        url: "/api/try/employees",
        method: "get",
        params: { site_id: num }
      }).then(res => {
        if (res.data.code == 1) {
          let login_index = "";
          for (let i in res.data.data) {
            //筛选需要的角色
            let role_list = res.data.data[i].role_list;
            for (let j in role_list) {
              if (jurisdiction == role_list[j].name) {
                login_index = i;
              }
            }
          }
          if (login_index != "") {
            setToken(res.data.data[login_index].token);
            localStorage.setItem("amendMessage_none", true);
            localStorage.setItem("ExperienceOne_none", false);
            localStorage.setItem(
              "Experience_data",
              JSON.stringify({ if: true, name: jurisdiction })
            );
            self.$store.commit("SET_TOKEN", res.data.data[login_index].token);
            // localStorage.setItem('site_list_temp', JSON.stringify(data.data.account_site))
          }
          var query = { user: this.user };
          self.$router.push({ path: "/", query: query });
        } else {
          // self.$message.error(res.data.data.msg)
        }
      });
    },
    loginBySite(sid) {
      let self = this;
      requests({
        url: "/api/employee-login",
        method: "post",
        data: { site_id: sid }
      }).then(res => {
        if (res.data.code == 1) {
          setToken(res.data.data.token);
          self.$store.commit("SET_TOKEN", res.data.data.token);
          let manager = res.data.data.user.employee_detail.role_list.findIndex(
            item => {
              return (
                item.name == "creator" ||
                item.name == "admin" ||
                item.name == "point_manager" ||
                item.name == "dept_manager"
              );
            }
          );
          if (manager >= 0) {
            self.$router.push({ path: "/" });
          } else {
            this.$confirm(
              "电脑版暂未开放【员工】的使用，请使用功道云APP",
              "提示",
              {
                confirmButtonText: "确定",
                type: "warning"
              }
            )
              .then(() => {
                this.logout();
              })
              .catch(() => {
                this.logout();
              });
          }
        } else {
          // self.$message.error(res.data.data.msg)
        }
      });
    },

    loginBySite(sid) {
      let self = this;
      requests({
        url: "/api/employee-login",
        method: "post",
        data: { site_id: sid }
      }).then(res => {
        if (res.data.code == 1) {
          setToken(res.data.data.token);
          self.$store.commit("SET_TOKEN", res.data.data.token);
          let manager = res.data.data.user.employee_detail.role_list.findIndex(
            item => {
              return (
                item.name == "creator" ||
                item.name == "admin" ||
                item.name == "point_manager" ||
                item.name == "dept_manager"
              );
            }
          );
          if (manager >= 0) {
            self.$router.push({ path: "/" });
          } else {
            this.$confirm(
              "电脑版暂未开放【员工】的使用，请使用功道云APP",
              "提示",
              {
                confirmButtonText: "确定",
                type: "warning"
              }
            )
              .then(() => {
                this.logout();
              })
              .catch(() => {
                this.logout();
              });
          }
        } else {
          // self.$message.error(res.data.data.msg)
        }
      });
    },

    // 登出
    logout() {
      const self = this;
      self
        .$http_user({
          url: "/api/logout",
          method: "post"
        })
        .then(res => {
          if (res.data.code == 1) {
            self.$store.dispatch("LogOut");
          }
        })
        .finally(() => {});
    },
    random(num) {
      let name = [];
      for (let i = 0; i < num; i++) {
        name.push(Math.floor(Math.random() * 10));
      }
      return name.join("");
    },

    pushLogin() {
      //跳转去登录界面
      setTimeout(() => {
        this.$router.push("/login");
      }, 2000);
    }
  },
  mounted() {}
};
</script>

<style type="text/css" scoped>
.image {
  width: 200px;
  height: 200px;
  position: fixed;
  z-index: 2;
  padding: 6px 10px;
  left: 50%;
  top: 50%;
  margin: -180px 0 0 -100px;
}

.fade-enter {
  opacity: 0;
}
.fade-enter-active {
  transition: opacity 1.2s;
}
.fade-leave-to {
  opacity: 0;
}
.fade-leave-active {
  transition: opacity 1s;
}
.CXDL{
  color:rgb(160 160 160);
  transition: .5s;
}
.CXDL:hover{
  color: rgb(94, 196, 255);
}
</style>
