<!--
 * @Author: zqm
 * @Date: 2021-06-25 13:49:49
 * @LastEditTime: 2022-03-30 13:55:49
 * @LastEditors: Please set LastEditors
 * @Description: 在线入口
 * @FilePath: \taxFormToolFramework\src\pages\view\taxRelated.vue
-->
<template>
  <div class="taxTableList" ref="taxTableList" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0)">
    <div class="taxLeft left" ref="taxLeft">
      <div class="tex_title" v-if="showMenu"><span>报表清单</span></div>
      <menuGroup ref="menuGroup" :tableList="tableList" :height="menuHeight" :declarationStatus="declarationStatus" @menuSelect="menuSelect" v-show="showMenu"></menuGroup>
      <i ref="menuBtn" class="menu_icon" :class="showMenu?'el-icon-arrow-left':'el-icon-arrow-right'" @click="menuShow()"></i>
    </div>
    <div class="taxRight right" ref="taxRight">
      <titleShow :bblxMc="selectTaxData.bblxMc" :sksssjq="bblxHeader.sksssjq" :sksssjz="bblxHeader.sksssjz" :bblxDm="selectTaxData.bblxDm"></titleShow>
      <el-row class="btnList">
        <buttonArea ref="buttonArea" :currentTaxData="selectTaxData" :sbResult="sbResult"></buttonArea>
      </el-row>
      <div class="tableBox" id="tableBox" ref="tableBox">
        <div ref="taxForm" id="taxForm" class="taxForm"></div>
        <inTablemodal ref="inTablemodal"></inTablemodal>
      </div>
    </div>
    <checkResult ref="checkResult" :currentTaxData="selectTaxData"></checkResult>
    <declareResult ref="declareResult" :currentTaxData="selectTaxData"></declareResult>
    <importFile ref="importFile"></importFile>
    <enterpriseDialog :selectRow="selectTaxData" :allData="qykjzdAllData" :from="kjzdForm" :dialogVisible="dialogVisible"></enterpriseDialog>
  </div>
</template>
<script>
import menuGroup from "../../components/menuGroup"
import deleteButton from "../../components/deleteButton"
import titleShow from "../../components/titleShow"
import buttonArea from "../../components/buttonArea";
import checkResult from '../../components/checkResult'
import declareResult from '../../components/declareResult'
import inTablemodal from '../../components/inTablemodal'
import importFile from '../../components/importFile'
import enterpriseDialog from '../../components/enterpriseDialog'
import FileSaver from 'file-saver'
export default {
  name: "taxTableList",
  components: {
    menuGroup, buttonArea, deleteButton, titleShow, checkResult, declareResult, inTablemodal, importFile, enterpriseDialog
  },
  data() {
    return {
      selectTaxData: {},//开表参数
      loading: false,
      showMenu: true,//菜单是否展示控制开关
      tableList: [], //左侧报表列表数据
      menuHeight: "",//菜单高度
      bblxHeader: {},//header头
      tbrq: '',//填表日期
      declarationStatus: "",//申报状态
      engines: "",//创建报表实例
      parent_this: this,
      qykjzdAllData: {},//企业会计制度 全量数据
      dialogVisible: false,//企业会计制度 弹框展示
      kjzdForm: '3',//企业会计制度 调用处理类型
      sbResult: ''//未申报成功
    };
  },
  watch: {
    '$store.state.data.loading': {
      handler(newName, oldName) {
        this.loading = newName;
      }
    }
  },
  methods: {
    //查询税种列表
    getBbList(data) {
      var _self = this;
      var getUrl = interfacePrefix + config.requestAddress.getMenu;
      //便于兼容综合申报多个税种，所以采用list形式
      var list = [];
      list.push(data);
      var params = {
        param: JSON.stringify(list),
        flag: data.flag
      };
      this.ajax.post(getUrl, params, function (returnData) {
        if (returnData.returnCode == '00') {
          _self.tableList = _self.deepClone(returnData.content[0].szlb); //报表清单数据
          _self.$store.commit("menuList", _self.tableList);
          _self.menuSelect(_self.tableList[0], "open"); //默认开表
          if (_self.tableList[0].sbzt == 'Y') {
            _self.sbResult = 'success'
          }
          _self.tbrq = returnData.content[0].tbrq;//填表日期
        }
      }, "json", true);
    },
    // 报表清单 tab切换 报表数据变更
    menuSelect(item, type) {
      this.$store.commit("defaultMenu", item.bbDm + '_' + item.detailPcdm);
      delete item.initData;
      delete item.tableData;
      var header = this.deepClone(item);
      delete header.xtbz;
      delete header.tbxh;
      delete header.bbMc;
      delete header.verificationState;
      delete header.versionNumber;
      delete header.nsqxMc;
      delete header.detailMultiPatch;
      this.bblxHeader = header;
      this.$store.commit("bblxHeader", header);
      //调用接口获取初始化数据、开表数据
      var _self = this
      var openUrl = interfacePrefix + config.requestAddress.openTable;
      this.ajax.post(openUrl, item, function (data) {
        if (data.returnCode == '00') {
          _self.$store.commit("saveStructure", data.content.data);//保存结构
          var historicalData = data.content.data.pageData;
          item.tableData = historicalData == "" ? {} : historicalData.tableData; //保存的历史数据
          var bjqsData = data.content.bjqsData;//表间取数
          var init = data.content.init;//初始化数据
          item.initData = {};
          if (init != null) {//整理开表的初始化和表间取数
            if (JSON.stringify(bjqsData) == "{}") {
              item.initData = init;
            } else {
              item.initData = _self.getInitData(init, bjqsData);
            }
          }
          _self.createEngine(item);
          _self.$store.commit("saveStatus", false);
        }
      }, "json", true);
    },
    //创建报表实例
    createEngine(item) {
      var _self = this;
      //增加传参
      item.nsrmc = this.bblxHeader.nsrmc;
      item.tbrq = this.tbrq;
      var sbdm = item.bbDm.split("_")[1];
      //查询模板数据
      var prefix = config.environmental == "";
      if (['dev'].includes(config.environmental)) {
        var prefix = '/engineJson/';
        this.$refs.buttonArea.isRemovePopup = true
      } else if (['production'].includes(config.environmental)) {
        var prefix = '/web/online/tableDisplayBusiness/static/engineJson/';
      } else {
        var prefix = '/web/tableDisplayBusiness/static/engineJson/';
      }
      var url = prefix + item.bblxDm + "/" + sbdm + "/" + item.bbDm + '_' + item.versionNumber + ".json";
      var template = {};
      this.ajax.get(url, function (res) {
        if (res.template) {
          template = res.template;
        } else {
          template = res;
        }
      }, "json", false);
      this.loading = true;
      var data = {
        pzzlDm: item.bblxDm,
        bbDm: sbdm,
        bbVersion: item.versionNumber,
        sksssjq: item.sksssjq,
        sksssjz: item.sksssjz,
        tbrq: item.tbrq,
        nsrmc: item.nsrmc,
        nsrsbh: item.nsrsbh,
        openingMode: this.selectTaxData.fillingFlag == 'corrections' ? "1" : '0',
        nssbq: item.nssbq,
        zcdz: ![null, undefined].includes(item.initData.zcdz) ? item.initData.zcdz : "",
        frdb: ![null, undefined].includes(item.initData.frdb) ? item.initData.frdb : "",
        dhhm: ![null, undefined].includes(item.initData.dhhm) ? item.initData.dhhm : "",
        swjgdm: ![null, undefined].includes(item.initData.swjgdm) ? item.initData.swjgdm : "",
        readOnly: item.sbzt == 'Y' ? true : false,
        bgColor: true,
        uniquePositioning: false,
        thousandCharacterSwitch: true,
        areaPaste: true,
        verificationSwich: true,
        initData: item.initData,
        tableData: item.tableData,//历史数据pageData
        template: template,
        isHiddenCol: false,
        millisecond: '32'
      };
      console.log('engines创建实例传参', data);
      this.engines = new engine({
        el: "#taxForm",
        data: data,
        error: function (e) {
          console.log("error", e);
          delete e.bbdm
          var messages = e.description.messages
          if (messages == "ResizeObserver loop limit exceeded") {
            return
          }
          if (messages == "ResizeObserver loop completed with undelivered notifications.") {
            return
          }
          _self.$alert(JSON.stringify(e), '提示信息', {
            type: 'error',
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        },
        userCellOperation: function (e) {
          _self.$store.commit("saveStatus", false);
        },
        tableConfigData: function (s) {
          _self.$store.commit("configData", s);
        },
        schedule: function (s) {
          _self.$store.commit("scheduleCode", s["code"]);
        },
        dialogSure: function (e) { // 用户弹出框点击确定按钮后的操作
          //展示弹出框
          if (e.checkList.length != 0) {
            var mes = _self.popupAssign("cell", item.bbDm, '', e.checkList)
            if (mes != "") {
              _self.$confirm(mes, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'btn-custom-cancel',
                closeOnClickModal: false,
                type: 'warning'
              }).then(() => {
                e.callback && e.callback(e.checkList)
              }).catch(() => {
              });
            } else {
              e.callback && e.callback(e.checkList)
            }
          } else {
            e.callback && e.callback(e.checkList)
          }
        },
      });
      this.engines.registrationEvents('dialogSure');
      this.loading = false;
      var addtLProp = {};//多批次节点（包含多批次信息）
      addtLProp.bbDm = item.bbDm;
      addtLProp.detailMultiPatch = item.detailMultiPatch;
      addtLProp.detailPcdm = item.detailPcdm;
      console.log(this.engines);
      this.engines.addtLProp = addtLProp;
      this.$store.commit("engines", this.engines);
      if (this.sbResult != 'success') {
        this.$refs.inTablemodal.initModal("init")
      }
      this.$refs.buttonArea.isSave()
    },
    sureChoose() {
      this.modalObj.isShow = "none";
    },
    cancelChoose() {
      this.modalObj.isShow = "none";
    },
    // 报表清单 展示/隐藏
    menuShow() {
      if (this.showMenu == true) {
        this.showMenu = false;
        this.$refs.taxLeft.style.width = "0%";
        this.$refs.taxRight.style.width = "98%";
      } else {
        this.$refs.taxLeft.style.width = "19%";
        this.$refs.taxRight.style.width = "80%";
        this.showMenu = true;
      }
    },
    //快捷键隐藏下载申报文件
    hideDownload() {
      var _self = this;
      var downloadUrl = "";
      downloadUrl = interfacePrefix + config.requestAddress.downloadFile;
      this.ajax.post(downloadUrl, this.bblxHeader, function (data) {
        if (data.returnCode == '00') {
          var blob = new Blob([data.content], { type: '' });
          FileSaver.saveAs(blob, _self.bblxHeader.bbDm + '_申报文件.txt');
        }
      }, "json", true);
    },
    //快捷键隐藏下载PDF文件
    downloadPDF(flag) {
      var $eleForm = $("<form id='download' method='post'></form>");
      var downloadUrl = interfacePrefix + config.downloadPDF;
      $eleForm.attr("action", downloadUrl);
      $(document.body).append($eleForm);
      var input1 = $("<input>"); //创建input标签
      input1.attr("type", "hidden"); //设置隐藏域
      input1.attr("name", "flag"); //设置发送后台数据的参数名
      input1.attr("value", flag);
      $("#download").append(input1);
      var list = []
      list.push(this.bblxHeader)
      var input2 = $("<input>"); //创建input标签
      input2.attr("type", "hidden"); //设置隐藏域
      input2.attr("name", "param"); //设置发送后台数据的参数名
      input2.attr("value", JSON.stringify(list));
      $("#download").append(input2);
      // 提交表单，实现下载
      try {
        $eleForm.submit();
      } catch (e) {
        this.$router.push({ name: 'error500' })
      }
      $("#download").remove();
    },
    //是否需要弹出企业会计制度
    isAccountingSystem(row) {
      var _self = this;
      var params = {
        type: "2",
        nsrsbq: row.nsrsbq,
        djxh: row.djxh,
        token: row.token,
        rylx: row.rylx,
        zjlx: row.zjlx,
        zjhm: row.zjhm,
        dlDjxh: row.dlDjxh
      };
      var url = interfacePrefix + config.find_full_qykjzd
      this.ajax.post(url, params, function (data) {
        if (JSON.stringify(data.content) != "{}") {
          var kjzdObj = {
            oldSelNbCwbb: data.content.oldSelNbCwbb,
            oldSelYjbCwbb: data.content.oldSelYjbCwbb,
            nbCwbbList: [],
            yjbCwbbList: [],
          };
          var kjzdNbList = data.content.nbCwbbList
          var showYjb = false;
          for (var nbIndex in kjzdNbList) {
            var bblxDm = kjzdNbList[nbIndex].bblxDm
            if (bblxDm.indexOf(row.bblxDm) != -1) {
              showYjb = true;
              kjzdObj.nbCwbbList.push(kjzdNbList[nbIndex])
            }
          }
          var kjzdYjbList = data.content.yjbCwbbList
          var showNb = false;
          for (var yjbIndex in kjzdYjbList) {
            var bblxDm = kjzdYjbList[yjbIndex].bblxDm
            if (bblxDm.indexOf(row.bblxDm) != -1) {
              showNb = true;
              kjzdObj.yjbCwbbList.push(kjzdYjbList[yjbIndex])
            }
          }
          _self.reselectKJZD(data.content, kjzdObj, showYjb, showNb)
        } else {
          _self.getBbList(this.selectTaxData);;
        }
      }, "json", true);
    },
    // 若存在企业会计制度，提示是否重新选择 add lmz 20200914
    reselectKJZD(allKjzdData, kjzdObj, showYjb, showNb) {
      var tipChangeKjzd = false;
      var kjzdMc = "";
      if (this.selectTaxData.nsqxDm == '06' || this.selectTaxData.nsqxDm == '08') {
        var oldSelYjbCwbb = allKjzdData.oldSelYjbCwbb;
        if (oldSelYjbCwbb != undefined && oldSelYjbCwbb != 'undefined' && oldSelYjbCwbb != null && oldSelYjbCwbb != 'null' && oldSelYjbCwbb != '') {
          var bblxData = Enumerable.From(allKjzdData.yjbCwbbList).Where(function (item, index) { return item.bblxDm == oldSelYjbCwbb }).ToArray();
          if (bblxData.length > 0) {
            kjzdMc = bblxData[0].bblxMc
            tipChangeKjzd = true;
          } else {
            tipChangeKjzd = false;
          }
        } else {
          tipChangeKjzd = false;
        }
      } else if (this.selectTaxData.nsqxDm == '10') {
        var oldSelNbCwbb = allKjzdData.oldSelNbCwbb;
        if (oldSelNbCwbb != undefined && oldSelNbCwbb != 'undefined' && oldSelNbCwbb != null && oldSelNbCwbb != 'null' && oldSelNbCwbb != '') {
          var bblxData = Enumerable.From(allKjzdData.nbCwbbList).Where(function (item, index) { return item.bblxDm == oldSelNbCwbb }).ToArray();
          if (bblxData.length > 0) {
            kjzdMc = bblxData[0].bblxMc
            tipChangeKjzd = true;
          } else {
            tipChangeKjzd = false;
          }
        } else {
          tipChangeKjzd = false;
        }
      } else {
        tipChangeKjzd = false;
      }
      if (tipChangeKjzd) {
        this.$confirm("已设置企业会计制度：" + kjzdMc + "，是否重新设置？", '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.qykjzdAllData = kjzdObj // 给组件推全量数据
          this.dialogVisible = true;
        }).catch(() => {
          this.getBbList(this.selectTaxData);
        });
      } else {
        if (showNb || showYjb) {
          this.qykjzdAllData = kjzdObj // 给组件推全量数据
          this.dialogVisible = true
        } else {
          this.getBbList(this.selectTaxData);
        }
      }
    },
    //申报成功后按钮置灰、报表不可编辑
    sbSuccessFun() {
      this.sbResult = 'success'//控制按钮
      var menuList = this.$store.state.data.menuList;
      menuList.forEach(element => {
        element.sbzt = "Y"
      });
      var defaultMenu = this.$store.state.data.defaultMenu;
      var menu = Enumerable.From(menuList).Where(function (val) { return val.bbDm + '_' + val.detailPcdm == defaultMenu }).ToArray()[0];
      this.menuSelect(menu)
    }
  },
  beforeCreate() {
    // 读取文件
    FileReader.prototype.reading = function ({ encode } = pms) {
      let bytes = new Uint8Array(this.result); //无符号整型数组
      let text = new TextDecoder(encode || "UTF-8").decode(bytes);
      return text;
    };
    /* 重写readAsBinaryString函数 */
    FileReader.prototype.readAsBinaryString = function (f) {
      if (!this.onload)
        //如果this未重写onload函数，则创建一个公共处理方式
        this.onload = e => {
          //在this.onload函数中，完成公共处理
          let rs = this.reading();
        };
      this.readAsArrayBuffer(f); //内部会回调this.onload方法
    };
  },
  created() {
    let arr = [];
    let that = this;
    document.onkeydown = function (e) {
      if (arr.length > 0) {
        // a-z按键长按去重
        if (arr.indexOf(e.key.toLowerCase()) >= 0) {
          return;
        }
      }
      arr.push(e.key.toLowerCase());
      this.keyboardShortcut = arr.join("+");
      if (this.keyboardShortcut == "control+shift+v") {
        that.hideDownload();
      }
      if (this.keyboardShortcut == "control+alt+p") {
        that.downloadPDF("PDF");
      }
      if (this.keyboardShortcut == "control+alt+e") {
        that.downloadPDF("EXCEL");
      }
    };
    document.onkeyup = function (e) {
      arr.splice(arr.indexOf(e.key.toLowerCase()), 1);
      this.keyboardShortcut = arr.join("+");
    };
    this.keyboardShortcut = "";
    this.$store.commit("platform", "1");
  },
  mounted: function () {
    // 接收税种列表数据
    var openData = window.opener.mlistener.selectRowData;
    var urlList = window.opener.mlistener.urlList;
    for (var code in openData) {
      this.selectTaxData[code] = openData[code];//开表参数
    }
    for (var code in urlList) {
      config.requestAddress[code] = urlList[code];//开表接口
    }
    console.log("开表", this.selectTaxData, config.requestAddress);
    this.$store.commit("openData", this.selectTaxData);
    sessionStorage.setItem("zsDjxh", this.selectTaxData.zsDjxh);
    sessionStorage.setItem("djxh", this.selectTaxData.djxh);
    /**
 * 29852 财务报表-一般企业-已执行/未执行
 * 29857 财务报表-政府-会计制度
 * 只有财务报表需要调用企业会计制度接口，其他税种不需要
 * */
    if ((this.selectTaxData.bblxDm == '29857' || this.selectTaxData.bblxDm == '29852') && this.selectTaxData.fillingFlag != 'corrections') {
      var sksssjzM = this.calculatingDate(this.selectTaxData.sksssjz.slice(0, 6), this.selectTaxData.nsqxdm, '+1')
      var nsrsbq = ""
      if (sksssjzM < this.selectTaxData.nsrsbq) {
        nsrsbq = sksssjzM
      } else if (sksssjzM > this.selectTaxData.nsrsbq) {
        nsrsbq = this.calculatingDate(this.selectTaxData.nsrsbq, this.selectTaxData.nsqxdm, '+1')
      } else {
        nsrsbq = this.selectTaxData.nsrsbq
      }
      this.$store.commit("nsrsbq", nsrsbq);
      this.isAccountingSystem(this.selectTaxData);
    } else {
      this.getBbList(this.selectTaxData);
    }
    // 修改浏览器title
    // $("#title").text(this.selectTaxData.bblxMc);
    // 调整高度
    var height = document.documentElement.clientHeight;
    this.$refs.taxLeft.style.height = height - 32 + "px";
    this.menuHeight = (height - 76) + 'px';
    this.$refs.taxRight.style.height = height - 32 + "px";
    this.$refs.tableBox.style.height = height - 130 + "px";
    this.$refs.taxForm.style.height = height - 135 + "px";
    this.$store.commit("parent", this);
  }
};
</script>
<style scoped>
.taxTableList {
  padding-top: 15px;
  width: 100%;
  overflow: hidden;
}
.taxLeft {
  min-height: 600px;
  border: 1px solid #e4e4e4;
  position: relative;
  width: 19%;
  border-radius: 3px;
  float: left;
}
.taxRight {
  padding-top: 0;
  width: 80%;
  min-height: 600px;
  float: right;
}
/* 报表清单 样式 */
.tex_title {
  width: 90%;
  padding: 0 5% !important;
  border-bottom: 1px solid #e4e4e4;
  border-radius: 3px 3px 0px 0px;
  line-height: 46px;
  background-color: #f7f7f7;
  font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
  font-weight: 400;
  text-align: left;
  color: #333333;
}
.tableList {
  margin: 0;
  padding: 0;
}
.tableList li {
  padding: 0 10px;
  text-align: left;
  direction: inherit;
  cursor: pointer;
}
.tableList li:hover {
  color: #0994dc;
}
.menu_line {
  padding: 10px 5px;
  border-bottom: 1px solid #e4e4e4;
}
.btbz {
  color: #ff1133;
  display: inline;
}
.bbmc {
  display: inline;
}
.xtbz {
  color: #ffaa33;
}
.activeMenu {
  color: #0994dc;
  background: #d1ecff;
}
.menu_icon {
  position: absolute;
  top: 50%;
  right: -14px;
  width: 14px;
  height: 52px;
  margin-top: -26px;
  background: #73b0ed;
  border-radius: 0px 3px 3px 0px;
  color: #ffffff;
  line-height: 52px;
}
/* 按钮list */
.btnList {
  padding: 10px 0;
}
.btn {
  margin: 0 5px;
}
.btn1 {
  margin: 0 5px;
}
.stausXX {
  padding: 0 16px;
  color: #333333;
  line-height: 46px;
  text-align: left;
  background: #f0f1f2;
  border-radius: 3px;
  overflow: hidden;
}
.staus_left {
  margin-right: 40px;
}
.now_bbmc,
.now_ssq {
  font-weight: 900;
  font-family: "微软雅黑";
}
.now_state {
  font-weight: 900;
  font-family: "微软雅黑";
}
.success {
  color: #4ec87c;
}
.error {
  color: #ff3d33;
}
.warning {
  color: orange;
}
.tableBox {
  min-height: 503px;
  background: #ffffff;
  border: 1px solid #d7d8d9;
  border-radius: 3px;
}
.taxForm {
  margin: 0;
  padding: 0;
  border: 0;
  width: 100%;
  height: 100%;
  min-height: 503px;
  float: left;
}
.but {
  margin-top: 20px;
  text-align: right;
}
.message {
  max-height: 400px;
  overflow-y: auto;
}
.sbTip {
  margin: 0 10px 10px;
}
.specialTxt {
  margin: 0 10px 15px;
  line-height: 30px;
}
.writeStatement {
  margin: 10px;
}
.p_lineHeight {
  line-height: 30px;
}
.zcfxTipBox {
  text-align: justify;
  margin: 0 20px;
}
.zzsldtsTipBox {
  text-align: justify;
  margin-bottom: 20px;
}
.zzsldtsBtn {
  padding: 5px 10px;
  text-align: center;
}
</style>
<style>
.btn-custom-cancel {
  float: right;
  margin-left: 10px;
}
.el-message-box__message {
  overflow: auto;
}
</style>

