<template>
  <div class="HomeBox">
    <div class="header">
      <header-comp/>
    </div>
    <div class="container">
      <router-view/>
    </div>

  </div>
</template>
<script>
import HeaderComp from './views/components/HeaderComp.vue';

export default {
  name: 'App',
  components: {HeaderComp},
  data() {
    return {
      ticketStr: '',
    }
  },
  created() {
    const that = this;
    window.onbeforeunload = function () {
      const syUserObj = JSON.parse(localStorage.getItem('ybz_syUserInfo'));
      const xzqdm = localStorage.getItem("ybz_XzqhCode");
      let len = 6 - xzqdm.toString().length;
      let xzqdmStr = xzqdm;
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          xzqdmStr = xzqdmStr + '0';
        }
      }
      if (syUserObj) {
        that.insertLogtail(syUserObj['Id'], syUserObj["Role"] || '政府监管人员', xzqdmStr, 2);
      }
    };
  },
  mounted() {
    this.clearStorage()
    //从缓存读取行政区划基础数据
    // const xzqhStr = localStorage.getItem("ybz_Xzqh") || "";
    // if (xzqhStr) {
    //   this.queryXzqCodeByName(xzqhStr);
    // }
    this.getUrlParamByToken();
  },
  methods: {
    changeDateHandle() {
      this.queryLogHzGroupXzq();
    },
    foundHandle() {
      this.$router.replace('/404')
      this.clearStorage();
    },
    clearStorage() {
      localStorage.clear()
      // localStorage.removeItem("ybz_syUser");
      // localStorage.removeItem("ybz_Xzqh");
      // localStorage.removeItem("ybz_XzqhCode");
      // localStorage.removeItem("ybz_userToken");
    },
    getUrlParamByToken() {
      const routePath = this.$router.history.current.path
      if (routePath.indexOf('404') !== -1) {
        return
      }
      var urlStr = window.location.href
      var arr = urlStr.split('?')
      if (arr.length === 1) {
        this.foundHandle()
        return
      }

      var paramStr = arr[1]
      var paramArr = paramStr.split('&')
      var paramMap = {}
      paramArr.forEach(item => {
        var arr = item.split('=')
        paramMap[arr[0]] = arr[1]
      })
      if (paramMap["debugger"] == "1") {
        localStorage.setItem("ybz_Xzqh", '浙江省');
        localStorage.setItem("ybz_XzqhCode", '33');
        this.$store.commit("BaseData/SET_XZQ_STATE", '浙江省');
        this.$store.commit("BaseData/SET_XZQ_CODE_STATE", '33');
        setTimeout(() => {
          localStorage.setItem('ybz_showOrgRole', "1");
          this.$vm.$emit('orgRoleEvent', true)
        }, 500)
        return;
      }
      if (!paramMap.hasOwnProperty('sykjzlptv2_ticket')) {
        this.foundHandle()
        return
      }
      this.ticketStr = paramMap['sykjzlptv2_ticket']
      const storeTicketStr = localStorage.getItem('ybz_sykjzlptv2_ticket')
      if (storeTicketStr) {
        if (storeTicketStr === paramMap['sykjzlptv2_ticket']) {
          // 缓存ticket，如果还是原来的就不用重新请求
          return
        }
      }
      this.getCommonToken()
    },
    async insertLogtail(userId, userRole, areaCode, actionType, actionId = '') {
      const urlApi = "/api/common/insertLogtail";
      const sendData = {
        "userId": userId || '',
        "userRole": userRole || '',
        "areaCode": areaCode || '',
        "actionType": actionType,
        "actionId": actionId,
        "actionStatus": 0
      };
      sendData['actionTime'] = this.getCurrentTime();
      const result = await this.$ajax.post(urlApi, sendData, this, false);
      const dataList = result["data"] || [];
      return dataList;
    },
    getCurrentTime() {
      const date = new Date();
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      let hours = date.getHours();
      let min = date.getMinutes();
      let mis = date.getSeconds();
      month = month < 10 ? ("0" + month) : month;
      day = day < 10 ? ("0" + day) : day;
      hours = hours < 10 ? ('0' + hours) : hours;
      min = min < 10 ? ('0' + min) : min;
      mis = mis < 10 ? ('0' + mis) : mis;
      return `${year}-${month}-${day} ${hours}:${min}:${mis}`;
    },
    async getCommonToken() {
      if (!this.ticketStr) {
        return
      }
      this.clearStorage();
      this.$vm.$emit('updateStorage');  //更新用户Storage
      const urlApi = '/mspdApi/ecgap_mspd/MSPDApi/getUserBySyToken'
      const formData = new FormData()
      formData.append('ticket', this.ticketStr)
      formData.append('zjugis.api.ticket', 'zjww%26key%26zdww1402!')
      this.testTicket = 'ticket值：' + this.ticketStr
      const result = await this.$axios.post(urlApi, formData, this, false)
      if (result['status'] !== 200) return;
      const resultData = result['data']
      this.testTicket += '\nresult的值: ' + JSON.stringify(resultData)
      if (!resultData || resultData['error_code']) {
        this.$message.error('用户不合法，请核实用户信息!')
        this.foundHandle()
        return
      }
      if (resultData['error']) {
        this.$message.error(resultData['error'])
        this.foundHandle()
        return
      }
      // if (!resultData['zjugisUser']) {
      //   this.$router.push({
      //     path: '/infoForm',
      //     query: {
      //       sykjzlptv2_ticket: this.ticketStr,
      //       accountId: resultData['syUser']['Account']
      //     }
      //   });
      //   return;
      // }
      if (resultData['syUser']) {
        const syUserObj = resultData["syUser"];
        localStorage.setItem('ybz_syUserInfo', JSON.stringify(syUserObj));
        localStorage.setItem("ybz_sykjzlptv2_ticket", this.ticketStr);
        localStorage.setItem("ybz_syUser", syUserObj["Name"]);
        this.$vm.$emit('updateStorage');  //更新用户Storage
        let xzqhStr = "";
        if (syUserObj["Xzqh"]) {
          if (syUserObj["Xzqh"] != "省级") {
            xzqhStr = syUserObj["Xzqh"];
          }
        }
        if (syUserObj["Name"] === "卓一瑞") {
          xzqhStr = "";
        }
        const orgLine = syUserObj["OrganizationLine"];
        var str1 = '浙政钉-->省政府机构-->省自然资源厅-->自然资源开发利用处';
        var str2 = '浙政钉-->省政府机构-->省自然资源厅-->厅领导'
        if (orgLine == str1 || orgLine == str2) {
          localStorage.setItem('ybz_showOrgRole', "1");
          this.$vm.$emit('orgRoleEvent', true)
        } else {
          localStorage.removeItem('ybz_showOrgRole')
          this.$vm.$emit('orgRoleEvent', false)
        }
        const xzqdm = await this.queryXzqCodeByName(xzqhStr);
        this.addLoginLog(
            syUserObj["Name"],
            syUserObj["OrganizationName"],
            syUserObj["OrganizationLine"],
            syUserObj["Xzqh"],
            xzqdm,
            syUserObj["Role"],
            syUserObj['Id'],
            syUserObj['Account']
        );
        let len = 6 - xzqdm.toString().length;
        let xzqdmStr = xzqdm;
        if (len > 0) {
          for (let i = 0; i < len; i++) {
            xzqdmStr = xzqdmStr + '0';
          }
        }
        this.insertLogtail(syUserObj['Id'], syUserObj["Role"] || '政府监管人员', xzqdmStr, 1);
        this.getTokenByUserId(resultData['zjugisUser']['id'])
      }
    },
    async queryXzqCodeByName(name) {
      if (name === '省级' || name === '') {
        localStorage.setItem("ybz_Xzqh", '浙江省');
        localStorage.setItem("ybz_XzqhCode", '33');
        this.$store.commit("BaseData/SET_XZQ_STATE", '浙江省');
        this.$store.commit("BaseData/SET_XZQ_CODE_STATE", '33');
        return '33';
      }
      const urlApi = `/api/dictXzdm/queryXzqCodeByName?xzqName=${name}`;
      const result = await this.$ajax.get(urlApi, {}, this, false);
      const dataMap = result["data"] || {};
      if (dataMap["dictCode"]) {
        localStorage.setItem("ybz_Xzqh", dataMap["dictName"]);
        localStorage.setItem("ybz_XzqhCode", dataMap["dictCode"]);
        this.$store.commit("BaseData/SET_XZQ_STATE", dataMap["dictName"]);
        this.$store.commit("BaseData/SET_XZQ_CODE_STATE", dataMap["dictCode"]);
        this.$vm.$emit('updateXzqhData')
      }
      return dataMap['dictCode'];
    },
    // 根据用户ID获取平台用户token
    getTokenByUserId(userId) {
      if (!userId) {
        return
      }
      const urlApi = '/z_user_org_right/LoginApi/ticketGet'
      const params = new FormData()
      params.append('id', userId)
      params.append('zjugis.api.ticket', 'zkr&key&zkr!@')
      const that = this
      that.$axios.post(urlApi, params, that, false).then(resp => {
        const {data, status} = resp
        localStorage.setItem('ybz_userToken', data['zjugis.ticket'])
      })
    },
    //添加登录日志
    addLoginLog(name, orgname, orgline, xzqh, xzqhcode, role, userId, accountId) {
      const urlApi = "/mspdApi/ecgap_mspd/MSPDApi/insertLoginLog";
      const params = new FormData();
      params.append("zjugis.api.ticket", "zkr&key&zkr!@");
      params.append("name", name);
      params.append("orgname", orgname);
      params.append("orgline", orgline);
      params.append("xzqh", xzqh);
      params.append("role", role);
      params.append("userId", userId);
      params.append("accountId", accountId);
      params.append("sysname", "浙地智用");
      this.$axios.post(urlApi, params, this, false);
    },
  }
}
</script>

<style lang="scss" scoped>
.HomeBox {
  height: 100%;
  background: url('./assets/images/bg.png') no-repeat;
  background-size: 100% 100%;

  > .heder {
    height: 94px;
  }

  > .container {
    height: calc(100% - 94px);
  }
}

.tableBox {
  user-select: none;

  > .tableFilter {
    display: flex;
    padding-bottom: 15px;
    align-items: center;

    > div {
      &:first-child {
        flex: 1;
        text-align: right;
        color: #fff;
        cursor: pointer;
        padding-right: 15px;
      }
    }
  }

  .tdClass {
    font-size: 16px;
  }

  ::v-deep {
    .ivu-table-wrapper-with-border {
      border: 0px;
    }

    .ivu-table {
      &::before,
      &::after {
        height: 0px;
        background-color: none;
      }

      th,
      td {
        background: transparent !important;
        color: #fff;
        border: 0px;
        text-align: center;
        font-size: 16px;
      }

      th {
        background: #07316f !important;
      }

      background: transparent !important;
    }
  }

  > table {
    width: 100%;
    color: #eee;
    border-spacing: 0px;

    > thead {
      > tr {
        background: #07316f !important;
      }
    }

    th,
    td {
      padding: 8px 15px;
      text-align: center;
    }
  }
}
</style>
