<style scoped lang="less">
.scrollable {
  /*height: 700px;*/
  overflow-x: hidden;
}

::-webkit-scrollbar {
  width: 7px;
}

::-webkit-scrollbar-thumb {
  opacity: 0.5;
  border-radius: 3.5px;
  background-color: #888888;
}

.from-second-title {
  height: 16px;
  line-height: 16px;
  margin-left: 24px;
  /*margin: 15px 0;*/
  margin-bottom: 15px;
  padding-left: 4px;
  border-left: 2px solid #3477cb;
}

.title {
  font-family: Microsoft YaHei;
  margin-left: 4px;
  font-size: 14px;
  color: #222222;
  letter-spacing: 0;
  text-align: left;
}
</style>
<template>
  <div class="modal_content">
    <div v-if="actionParam && actionParam.param.componentName">
      <component :is="componentName" :context="this"> </component>
    </div>
    <div v-else-if="showDetail || (actionParam && actionParam.param.viewName)">
      <!-- 此处处理选择单据 -->
      <Modal
        v-model="modal_visible"
        :title="selectBill ? ' ' : '选择单据'"
        :mask-closable="false"
        :fullscreen="selectBill ? true : false"
        :class-name="selectBill ? 'initHeight' : null"
      >
        <p slot="header">
          <span>{{selectBill ? ' ' : '选择单据'}}</span>
          <a class="ivu-modal-close" @click="handleCancel">
            <Icon type="ios-close"
          /></a>
        </p>
        <div v-if="!selectBill">
          <div class="all-modal">
            <!-- <Select v-model="selectBill" style="width:200px">
							<Option v-for="item in actionParam&&actionParam.param.viewName.split(',')" :value="item" :key="item">{{ item }}</Option>
						</Select> -->
            <Select v-model="selectBill" style="width: 310px">
              <Option
                v-for="(item, index) in actionParam &&
                  actionParam.param.viewArr"
                :value="item.name"
                :key="index"
                >{{ item.title }}</Option
              >
            </Select>
          </div>
        </div>
        <gms-bill-form
          :templateName="selectBill"
          :id="billId"
          :type="billId ? 'load' : 'init'"
          :state="state"
          v-if="selectBill"
          @loadFinish="loadFinishFun"
        ></gms-bill-form>
        <div slot="footer" style="height: 0"></div>
      </Modal>
    </div>
  </div>
</template>
<script>
import { compareData } from "./util/dataChange.js";
export default {
  data() {
    return {
      isReadOnly: false,
      showDetail: false,
      state: null,
      billId: "",
      modal_visible: false,
      showBiffForm: false,
      bill: null,
      actionParam: null,
      formName: "",
      zicflObj: {},
      nAssetClass: true,
      addAssetsFormData: {},
      modifyData: false,
      rowData: [],
      loadForm: false,
      fieldState: false,
      componentName: "",
      moadlTitle: "",
      currentRowData: {},
      masterData: {},
      selectBill: "",
      detailItem: "detailItem",
      tableColnum: [],
      subBillData: null,
      masterFieldsObj:{},
    };
  },
  mounted() {
    GMS.vbus.$on("closeModal", (res) => {
      delete GMS.showDetailAction; //删除点击详情按钮记录的参数
      this.modal_visible = false;
      GMS.vbus.$off("closeModal");
    });
    GMS.vbus.$on("cacheEcho", (param) => {
      let controlArr = this.bill.action.filter(
        (v) => v.execute == "searchBillAction"
      );
      if (controlArr.length == 0) {
        return;
      }
      this.detailItem = controlArr[0].param.field[0].targetTableName;
      if (!this.actionParam.param.field) {
        return;
      }
      let obj = this.fieldMatch(param); //此处进行  字段对应关系的对应逻辑
      console.log(
        "obj",
        this.detailItem,
        param,
        obj,
        this.actionParam.param,
        Object.values(obj)
      );
      if (Object.keys(obj).length == 0) {
        //如果没有匹配的字段，则不增行
        this.modal_visible = false;
        this.$message.error("没有匹配的字段");
        return;
      }
      let arr = this.bill.action.filter((v) => v.execute == "editAction");
      if (arr.length > 0) {
        obj["BILLID"] = param.id; //记录一下id
        obj["BILLNAME"] = param.billDefine; //记录一下单据标识;
        obj["BILLEDITNAME"] = this.selectBill; //记录一下表单名称
      }
      setTimeout(() => {
        if (!this.billId) {
          let sub = this.bill.getBuillData()[this.detailItem];
          console.log('sub:',sub);
          if(sub && Object.prototype.toString.apply(sub)==="[object Array]"){
            let arr = sub.filter(v=>v.BILLID==param.id);
            if(arr.length>0){//说明重复了
              this.modal_visible = false;
              delete GMS.editSubIndex;
              GMS.vbus.$off("cacheEcho");
              return;
            }
          }
          this.addSubTableRow(this.detailItem);//增行
        }
        obj.BILLDETAILOBJ = param;
        let index =
        GMS.editSubIndex != undefined
          ? GMS.editSubIndex
          : this.getSubTableLength(this.detailItem)
          ? this.getSubTableLength(this.detailItem) - 1
          : 0;
        console.log("index", index);
        this.refreshSubDataByIndex(this.detailItem, obj, index);
        
        this.modal_visible = false;
        delete GMS.editSubIndex;
        GMS.vbus.$off("cacheEcho");
      }, 500);
    });
  },
  beforeDestroy() {
    GMS.vbus.$off("cacheEcho");
    GMS.vbus.$off("closeModal");
  },
  props: {},
  methods: {
    loadFinishFun(bill) {
      let that = this;
      if (this.subBillData) {
        Object.keys(this.subBillData).forEach((i) => {
          let field = bill.billdata.billTable.masterName + "." + i;
          bill.getMasterData().setValue(field, this.subBillData[i]);
          if (
            Object.prototype.toString.call(this.subBillData[i]) ===
            "[object Array]"
          ) {
            //子表赋值
            while (bill.getSubData(i) && this.subBillData[i].length > 0 &&
              (Object.prototype.toString.call(bill.getSubData(i)) !=
                "[object Array]" ||
              bill.getSubData(i).length < this.subBillData[i].length)
            ) {
              bill.addSubData(i); //先增行
            }
            this.subBillData[i].forEach((v, index) => {
              let subDataObj = bill.getSubData(i);
              Object.keys(v).forEach((colItem) => {
                subDataObj[index].setValue(colItem, v[colItem]);
              });
            });
            setTimeout(() => {
              bill.refreshSubDataRow(i); //刷新表格
            }, 100);
          }
        });
      }
      setTimeout(() => {
        that.billClass = bill;
        that.setFieldFromMaster(bill);//将和主单据关联的主表字段，重新赋值
        that.oldBillData = bill.getBuillData();
      }, 100);
    },
    setFieldFromMaster(bill){
      if(!this.actionParam.param.masterFields) return
      let obj = this.actionParam.param.masterFields.find(
        (v) => v.billName == this.selectBill
      );
      if (Object.keys(obj).length > 0) {
        obj.fieldBillRelation.forEach(v=>{
          let field = bill.billdata.billTable.masterName + "." + v.originalField;
          let value = this.masterFieldsObj[v.targetField];
          bill.getMasterData().setValue(field,value);
        })
      }
    },
    fieldMatch(param) {
      let obj = {};
      let arr1 = this.actionParam.param.field.filter(
        (v) => v.billName == this.selectBill
      );
      if (arr1.length == 0) {
        return obj;
      }
      let targetTableName = arr1[0].targetTableName;
      let controlArr = this.bill.action.filter(
        (v) => v.execute == "searchBillAction"
      );
      let tableName = controlArr[0].param.field[0].targetTableName;
      if (tableName != targetTableName) {
        //同名子表
        return obj;
      }
      let originalField = arr1[0].fieldBillRelation.originalField;
      let targetField = arr1[0].fieldBillRelation.targetField;
      for (let i = 0; i < originalField.length; i++) {
        obj[targetField[i].field] = param[originalField[i].field];
      }
      return obj;
    },
    getAssetsModal() {
      this.componentName = GMS.getContext()
        .getCollector()
        .getElement("billControl", this.actionParam.param.componentName);
    },
    initModal() {
      this.moadlTitle = this.actionParam.param.moadlTitle;
    },
    getCurrentRowData(subName) {
      this.getSubRowDataBy(subName, this.bill.getSubFocus());
      return this.currentRowData;
    },
    getRowDataByIndex(subName, index) {
      this.getSubRowDataBy(subName, index || this.bill.getSubFocus());
      return this.currentRowData;
    },
    getMasterAllData() {
      this.getModalDatas();
      return this.masterData;
    },
    getMasterDataByKey(key) {
      this.getModalDatas();
      return this.masterData[key];
    },
    getSubTableStatus() {
      return this.actionParam.param.isEdit;
    },
    addSubTableRow(name) {
      this.bill.addSubData(name);
    },
    getCurrentIndex() {
      return this.bill.getSubFocus();
    },
    getSubTableLength(name) {
      return this.bill.getSubData(name) ? this.bill.getSubData(name).length : 0;
    },
    refreshMaster(obj) {
      let masterObj = this.bill.getMasterData();
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          this.setTableValue(
            masterObj,
            this.actionParam.param.masterTableName + "." + key,
            obj[key]
          );
        }
      }
    },
    refreshSuCurrentRow(subName, obj) {
      this.refreshSubData(subName, obj, this.bill.getSubFocus());
    },
    refreshSubData(subName, obj, index) {
      let subObj = this.bill.getSubDataRow(subName, index);
      let _obj = {};
      for (const key in obj) {
        this.setTableValue(
          subObj,
          this.actionParam.param.masterSubRelation[subName] + "." + key,
          obj[key]
        );
        _obj[key] = {
          value: obj[key],
          readOnly: true,
        };
      }
      subObj.setValue("currentRowData", obj);
      this.bill.refreshSubDataRow(subName, "", [_obj]);
    },
    refreshSubDataByIndex(subName, obj, index) {
      let subObj = this.bill.getSubDataRow(subName, index);
      if (!subObj) {
        return;
      }
      let masterSubRelation =
        this.actionParam.param && this.actionParam.param.masterSubRelation
          ? this.actionParam.param.masterSubRelation[subName]
          : undefined;
      let _obj = {};
      for (const key in obj) {
        this.setTableValue(subObj, masterSubRelation + "." + key, obj[key]);
        _obj[key] = {
          value: obj[key],
          readOnly: true,
        };
      }
      subObj.setValue("currentRowData", obj);
      this.bill.refreshSubDataRow(subName, "", _obj, index);
    },
    refreshSubDataByIndexCopy(subName, obj, index) {
      let subObj = this.bill.getSubDataRow(subName, index);
      let masterSubRelation =
        this.actionParam.param && this.actionParam.param.masterSubRelation
          ? this.actionParam.param.masterSubRelation[subName]
          : undefined;
      let _obj = {};
      for (const key in obj) {
        this.setTableValue(subObj, masterSubRelation + "." + key, obj[key]);
        _obj[key] = {
          value: obj[key],
          readOnly: true,
        };
      }
      this.bill.refreshSubDataRow(subName, _obj, index);
    },
    getModalDatas() {
      if (!this.masterData || JSON.stringify(this.masterData) === "{}") {
        for (const key in this.bill.getAllMasterFiled()) {
          if (this.bill.getAllMasterFiled().hasOwnProperty(key)) {
            this.masterData[key] = this.bill.getMasterData().getValue(key);
          }
        }
      }
    },
    getSubRowDataBy(subName, index) {
      if (
        index > -1 &&
        (!this.currentRowData || JSON.stringify(this.currentRowData) === "{}")
      ) {
        let rowDataObject = this.bill.getSubDataRow(subName, index);
        if (!rowDataObject) {
          console.log("当前行无数据");
          return;
        }
        this.currentRowData = rowDataObject.getValue("currentRowData");
        if (!this.currentRowData) {
          this.currentRowData = rowDataObject.getRawDataCopy();
        }
        return this.currentRowData;
      } else {
        return this.currentRowData;
      }
    },
    selectAsset(val, type) {
      GAMS.Util.invokeServer({
        path:
          "/gams2/basedata/queryByID/" +
          this.actionParam.param.getAssetclassUrl +
          "/" +
          val,
        type: "POST",
        contentType: "application/json",
      })
        .then(
          function(data, textStatus, response) {
            if (data != 0) {
              this.showBiffForm = false;
              this.formName = JSON.parse(data)[0][
                this.actionParam.param.carddefinename || "carddefinename"
              ];
              //gams_card_gzw  gams_card_jjyjzj gams_card_cl
              // this.formName = 'com.jiuqi.np.gams2.business.form.dynamic_card.gams_card_cl';
              this.refreshView(type);
            }
          }.bind(this)
        )
        .catch((XMLHttpRequest, textStatus, errorThrown) => {
          // this.$Message.error("请求异常,请联系管理员");
        });
    },
    refreshView(type) {
      this.$nextTick(
        function() {
          this.showBiffForm = true;
          this.setFormHeifht();
          this.assingData();
          this.setFormData(type);
        }.bind(this)
      );
    },
    setFormHeifht() {
      $(".all-modal").css("height", document.body.clientHeight - 260);
      $(".all-modal").css("overflow-y", "auto");
      $(".all-modal").css("overflow-x", "hidden");
      $(".modal_content .ivu-modal-content").css(
        "height",
        document.body.clientHeight - 120
      );
    },
    //行业大类
    hangydl(val) {
      this.zicflObj["hangydl"] = val;
    },
    //国标分类
    guobfl(val) {
      this.zicflObj["zicfl"] = val;
      this.$nextTick(
        function() {
          this.getShiynxById(val.id, val.shiynx);
        }.bind(this)
      );
    },
    //国标大类
    guobdl(val) {
      this.zicflObj["sortgb"] = val;
    },
    getShiynxById(id, shiynx) {
      GAMS.Util.invokeServer({
        path: "/depreciation/config/setting/getagebyid/" + id,
        type: "POST",
        contentType: "application/json",
      })
        .then(
          function(data, textStatus, response) {
            if (data) {
              if (data.content.age && data.content.age > 0) {
                this.shiynx = data.content.age;
              } else {
                this.shiynx = shiynx;
              }
            } else {
              this.shiynx = shiynx;
              this.$message.error("请求异常");
            }
            this.setFormValue("yujsmzl", this.shiynx);
          }.bind(this)
        )
        .catch(
          function(XMLHttpRequest, textStatus, errorThrown) {
            this.$Message.error("请求异常,请联系管理员");
          }.bind(this)
        );
    },
    SelectTreeClick() {},
    getCurrentRowDatas() {
      let rowDataObject = this.bill.getSubDataRow(
        this.actionParam.param.tableName,
        this.bill.getSubFocus()
      );
      if (this.actionParam.param.assetsClassField) {
        this.setAssetClassValue(
          rowDataObject.getValue(this.actionParam.param.assetsClassField).id
        );
      } else {
        this.setAssetClassValue(rowDataObject.getValue("zicfl").id);
      }
    },
    loadComplate() {
      if (this.loadForm) {
        if (this.actionParam.param.assetsClassField) {
          alert("TODO");
        } else {
          this.$refs.assetClass.readOnly = true;
          this.setAssetClassValue(this.rowData[0].zicfl.value.id);
        }
      }
    },
    getRowData() {
      setTimeout(
        function() {
          let rowDataObject = this.bill.getSubDataRow(
            this.actionParam.param.tableName,
            this.bill.getSubFocus()
          );
          if (this.actionParam.param.saveRowDataField) {
            let rowData = rowDataObject.getValue("currentRowData");
            this.getAddAssetsFormData(rowData, rowDataObject);
          } else {
            let subFiled = this.bill.getAllSubFiledByName(
              this.actionParam.param.tableName
            );
            this.getAddAssetsFormData(subFiled, rowDataObject);
          }
        }.bind(this),
        800
      );
    },
    getAddAssetsFormData(obj, rowDataObject) {
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (rowDataObject.getValue(key)) {
            this.setFormValue(key, rowDataObject.getValue(key));
          }
        }
      }
    },
    getRowValueByKey() {
      let dataObject = this.bill.getMasterData();
      dataObject.getValue(key);
    },
    setFormData(type) {
      if (this.modifyData) {
        this.getRowData();
      }
      if (this.fieldState) {
        this.$nextTick(function() {
          this.$refs.biffFormRef.context.bill.setGlobalParam("allfieldState", {
            state: this.actionParam.param.state,
          });
          for (const key in this.rowData[0]) {
            if (this.rowData[0].hasOwnProperty(key)) {
              if (key != "id") {
                this.setFormValue(key, this.rowData[0][key].value);
              }
            }
          }
        });
      }
    },
    assingData() {
      setTimeout(
        function() {
          if (!this.modifyData) {
            this.assignFieldValue(this.assignField);
            if (this.actionParam.param.assignFieldList) {
              this.assignFieldValue(this.actionParam.param.assignFieldList);
            }
            if (this.actionParam.param.assetsClassField) {
              this.setFormValue(
                "zicmc",
                this.zicflObj[this.actionParam.param.assetsClassField].title
              );
            } else {
              this.setFormValue("zicmc", this.zicflObj["zicfl"].title);
            }
          }
        }.bind(this),
        800
      );
    },
    assignFieldValue(list) {
      for (const iterator of list) {
        if (iterator.type === "date") {
          this.setFormValue(iterator.key, GAMS.Util.initBnsApplyTime());
        } else {
          this.setFormValue(iterator.key, iterator.value);
        }
      }
    },
    setFormValue(key, val) {
      let dataObject = this.$refs.biffFormRef.context.bill.getMasterData();
      dataObject.setValue("gams_asset_card." + key, val);
    },
    setAssetClassValue(id) {
      this.$nextTick(
        function() {
          this.$refs.assetClass.executeOperation(id);
          this.modifyData = true;
        }.bind(this)
      );
    },
    handleSaveAndNext() {
      let billPath = "/newBillForm/" + this.selectBill;
      let routeData = GMS.routerManager.getRouter().resolve({
        path: billPath,
      });
      window.open(routeData.href, "_blank");
      //this.close();
    },
    handleAddAssetsSave() {
      this.chekData(
        function(code) {
          if (code) {
            this.getModalData();
            this.close();
          }
        }.bind(this)
      );
    },
    isQudrqCompar(type) {
      if (this.more1990formulaPrompt[this.modal]) {
        let _time = this.$refs.addAssetForm.addAssetsFormData.qudrq;
        if (GAMS.Common.getTimetamp(_time) < -2209017943000) {
          this.chenkModel("取得日期过早，请确认是否属实？", type || 2);
          return -2;
        } else {
          return 1;
        }
      } else {
        return 1;
      }
    },
    isHouse(type) {
      if (this.modal === "zGAMS_CARD_FW") {
        let _danj = this.$refs.addAssetForm.addAssetsFormData.danj;
        if (_danj <= 50.0) {
          this.chenkModel("房屋价值均价过低，请确认是否属实?", type || 1);
          return -1;
        } else if (_danj >= 20000.0) {
          this.chenkModel("房屋价值均价一般每平方米不高于2万元!是否继续", 1);
          return -1;
        } else {
          return 1;
        }
      } else {
        return 1;
      }
    },
    chenkModel() {},
    chekData(callBack) {
      if (this.$refs.biffFormRef && this.$refs.biffFormRef.context) {
        this.$refs.biffFormRef.context.bill.runFormulaCheckData(
          "",
          function(msg) {
            if (msg.length == 0) {
              callBack(1);
            } else {
              this.$Modal.warning({
                title: "信息错误",
                content: msg,
              });
            }
          }.bind(this)
        );
      }
    },
    getModalData() {
      if (this.$refs.biffFormRef) {
        let filedObj = this.$refs.biffFormRef.context.bill.getAllMasterFiled();
        let dataObject = this.$refs.biffFormRef.context.bill.getMasterData();
        let rowDataObject = this.bill.getSubDataRow(
          this.actionParam.param.tableName,
          this.bill.getSubFocus()
        );
        let obj = {};
        for (const key in filedObj) {
          if (filedObj.hasOwnProperty(key)) {
            obj[key] = dataObject.getValue(key);
            if (this.zicflObj[key]) {
              obj[key] = this.zicflObj[key];
            }
            if (this.modifyData) {
              this.setTableValue(rowDataObject, key, obj[key]);
              this.bill.refreshSubDataCellValue(
                this.actionParam.param.tableName,
                key,
                obj[key]
              );
            }
          }
        }
        if (!this.modifyData) {
          this.bill.setSubDatas(this.actionParam.param.tableName, [obj]);
        }
      }
    },
    setTableValue(obj, key, val) {
      obj.setValue(key, val);
    },
    addListener(l) {
      this.listener = l;
    },
    close() {
      this.modal_visible = false;
      this.showBiffForm = false;
      if (this.listener) {
        this.$nextTick(
          function() {
            this.$destroy();
            this.listener.close();
          }.bind(this)
        );
      }
    },
    handleCancel() {
      if (!this.selectBill) {
        delete GMS.editSubIndex;
        delete GMS.showDetailAction; //删除点击详情按钮记录的参数
        GMS.vbus.$off("cacheEcho");
        GMS.vbus.$off("closeModal");
        this.modal_visible = false;
        this.close();
      } else {
        let newBill = this.isReadOnly ? this.oldBillData : this.billClass? this.billClass.getBuillData():this.bill.getBuillData();
        let flag = compareData(this.oldBillData, newBill);
        if (flag) {
          delete GMS.editSubIndex;
          delete GMS.showDetailAction; //删除点击详情按钮记录的参数
          GMS.vbus.$off("cacheEcho");
          GMS.vbus.$off("closeModal");
          this.close();
          this.modal_visible = false;
        } else {
          //提示是否保存
          this.$Modal.confirm({
            title: "信息提示",
            content: "信息发生变化，确认关闭？",
            onOk: () => {
              delete GMS.editSubIndex;
              delete GMS.showDetailAction; //删除点击详情按钮记录的参数
              GMS.vbus.$off("cacheEcho");
              GMS.vbus.$off("closeModal");
              this.close();
              this.modal_visible = false;
            },
            onCancel: () => {
              this.modal_visible = true;
            },
          });
        }
      }
    },
  },
  watch: {
    state: {
      handler(newVal, oldVal) {
        this.state = newVal;
      },
    },
    subBillData: {
      handler(newVal, oldVal) {
        this.subBillData = newVal;
      },
    },
    billId: {
      handler(newVal, oldVal) {
        this.billId = newVal;
      },
    },
    selectBill: {
      handler(newVal, oldVal) {
        this.selectBill = newVal;
      },
    },
  },
};
</script>
<style lang="less">
.v-transfer-dom .ivu-modal-mask {
  z-index: 999 !important;
}

.initHeight {
  z-index: 999 !important;
  .ivu-modal-header {
    padding: 7px 16px !important;
  }
  .ivu-modal-close .ivu-icon-ios-close {
    font-size: 31px;
    color: #999;
    -webkit-transition: color 0.2s ease;
    transition: color 0.2s ease;
    position: relative;
    top: -4px;
  }
}
.initHeight .ivu-modal-fullscreen .ivu-modal-body {
  bottom: 0;
}
.initHeight .ivu-modal-footer {
  padding: 0;
}

</style>
