import formOplogTable from "@base/components/formOplog/index.vue";
import preformDialog from "@base/views/bd/setting/form_template/preformDialog.vue";
import projectTagView from "@base/components/projectTag/view.vue";
import szTaMbDialog from "@base/views/bd/setting/table_model/dialog.vue";
import MenuKindDialog from "@base/views/bd/setting/menu_kind/dialog.vue";
import zdDialog from "@base/views/bd/setting/table_model/zdDialog.vue";
import {getBdFlag} from "@base/api/user";
import {getJsxBtn} from "@base/views/bd/setting/utils/index";
import otherAuthDialog from "../otherAuthDialog.vue";
import { mapGetters } from "vuex";

let modules = {};
modules = {
  name: "szTaMbEdit",
  props: {
    _dataId: [String, Number],
    currentFormType: Object,
    // readonly: Boolean,
    otherFlag:Boolean,
    hData: Object,
    compareHData: Object,
    extractedObj: Object,
  },
  components: {
    formOplogTable,
    preformDialog,
    projectTagView,
    szTaMbDialog,
    MenuKindDialog,
    zdDialog,
    otherAuthDialog
  },
  data() {
    return {
      tabIndex: 0,
      isEdit: false,
      dataId: "",
      szTaMb: {
        enabled: true,
        taType: 0,
        szTaZdMbDTOs: [],
        menuKindName: null,
        menuKindCode: null,
        serviceName: null,
        taRule: 0,
        dataRange: 0,
        szTaMbTagDTOs: [],
        fromTable: false,
        taCh: null,
        sszstEn: null,
        taEn: null,
        taBm: null,
        sszstBm: null,
      },
      oldSzTaMb: {
        enabled: true,
        taType: 0,
        szTaZdMbDTOs: [],
        menuKindName: null,
        menuKindCode: null,
        serviceName: null,
        taRule: 0,
        dataRange: 0,
        szTaMbTagDTOs: [],
        fromTable: false,
        taCh: null,
        sszstEn: null,
        taEn: null,
        taBm: null,
        sszstBm: null,
      },
      treeDefaultZds: [],
      productOption: {},
      showSzTaMbDialog: false,
      showItemSzTaMbDialog: false,
      showMenuKindDialog: false,
      productCategoryCodes: [],
      zdEnIndex: "",

      referenceEntity: null,
      referenceKey: null,
      referenceShowFields: null,
      refServiceName: null,
      currentIndex: 0,
      showReferenceZdDialog: false,

      showEntityDialog: false,
      showEntityFieldDialog1: false,
      showEntityFieldDialog2: false,
      referenceShowRows: [],
      createdTableColumnStr: null,
      createdTableColumnArray: [],
      isDev: true,
      showPreformDialog: false,
      menuKindAuth: {
        editAuth: 0,
      },

      dbTable: null,
      showDtDialog: false,
      showTmDialog: false,

      showToTaBmZdDialog: false,
      toTaBmZdEntity: null,
      toTaBmZdField: null,
      showEntityDialog3: false,
      showEntityFieldDialog3: false,

      inputValue: null,     // 当前值
      preValue: null,        // 上一次的值（变更前的值）

      sid: null,
      showOtherAuthDialog:false,

      zdTypeMap: {
        Boolean: "布尔",
        Integer: "整数",
        Long: "长整数",
        Decimal: "精度小数",
        Money: "金额",
        Text: "文本",
        TextArea: "长文本",
        DateTime: "日期时间",
        Reference: "关联表(文本)",
        ReferenceLong: "关联表(长整型)",
      },

      treeFlagMap:{
        name: "名称",
        wbs: "WBS码",
        parent: "上级ID",
        treePath: "树ID路径",
        treePathName: "树名称路径",
        hasChild: "是否有下级",
        grade: "层级",
      },

      readonly: false,
      isCompare: false,
    };
  },
  computed: {
    ...mapGetters([
      "userFlag",
    ]),
  },
  created() {
    if(this.hData){
      this.readonly = true;
    }else{
      this.readonly = this.$attrs.readonly || false;
    }
    if (this._dataId && !isNaN(this._dataId)) {
      this.dataId = this._dataId;
    } else {
      this.szTaMb.menuKindName = this.currentFormType?.name || null;
      this.szTaMb.menuKindCode = this.currentFormType?.menuKindCode || null;
      this.szTaMb.serviceName = this.currentFormType?.serviceName || null;
    }
  },
  mounted() {
    this.getBdEnv();
    this.getTreeDefaultZds();
    this.initTableProduct();
    this.getData();
  },
  methods: {
    initData(formData){
      if(!!formData?.id)this.isEdit = true;
      this.szTaMb = formData;
      this.getMenuKindAuth(formData.menuKindCode);
      if(!!formData?.id)this.getCreatedTableColumns();
    },
    getData(callback) {
      if(this.extractedObj){
        this.dataId = this.extractedObj.id;
        this.initData(this.extractedObj)
        //获取操作日志数据
        this.$refs["oplogTable"].initData({
          param: () => {
            return {
              logType: "SzTaMb",
              logObjCode: this.szTaMb.taCode,
            };
          },
        });
      }else if (this.dataId && !isNaN(this.dataId)) {
        this.isEdit = true;
        this.$http({
          aes: true,
          url: USER_PREFIX + `/szTaMb/get`,
          method: `post`,
          data: {
            id: this.dataId,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            if (!callback) {
              let szTaMb = res.objx || {};
              szTaMb.szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs;
              szTaMb.attachmentDTOs = this.szTaMb.attachmentDTOs;
              szTaMb.oplogDTOs = this.szTaMb.oplogDTOs;

              // this.szTaMb = szTaMb;
              // this.getCreatedTableColumns();
              // this.getMenuKindAuth(this.szTaMb.menuKindCode);
              this.initData(szTaMb);
            } else {
              callback(res);
            }
            //获取操作日志数据
            this.$refs["oplogTable"].initData({
              param: () => {
                return {
                  logType: "SzTaMb",
                  logObjCode: this.szTaMb.taCode,
                };
              },
            });
          },
        });
      } else if (this.hData){
        this.dataId = this.hData.id
        /* this.isEdit = true;
        this.szTaMb = this.$baseLodash.cloneDeep(this.hData);
        this.getMenuKindAuth(this.szTaMb.menuKindCode);
        this.getCreatedTableColumns(); */
        this.initData(this.$baseLodash.cloneDeep(this.hData));
        if (this.compareHData && this.$attrs.isCompare) {
          this.oldSzTaMb = this.$baseLodash.cloneDeep(this.compareHData);
          let oldSzTaZdMbDTOs = this.$baseLodash.cloneDeep(this.compareHData.szTaZdMbDTOs) || [];
          this.szTaMb.szTaZdMbDTOs.forEach((item, index) => {
            let oldItem = oldSzTaZdMbDTOs.find((pItem) => pItem.zdEn === item.zdEn);
            item.hData = oldItem || {};
          })
          this.isCompare = true;
        }
      } else {
        this.getMenuKindAuth(this.szTaMb.menuKindCode);
      }
    },
    updateStatus(status) {
      let text;
      if (status === 3) {
        text = this.$t1("您确定要作废吗？");
      }
      this.$baseConfirm(text).then(() => {
        this.$http({
          aes: true,
          url: USER_PREFIX + `/szTaMb/updateStatus`,
          method: `post`,
          data: {
            id: this.dataId,
            status: status,
          },
          isLoading: true,
          success: (res) => {
            this.$message({
              message: res.content,
              type: "success",
              duration: 500,
              onClose: (t) => {
                this.$baseReload();
              },
            });
          },
        });
      });
    },
    saveData() {
      this.$refs.editForm.$baseValidate((valid) => {
        if (valid) {
          const szTaZdMbDTOs =
            this.$refs["table-szTaZdMb"].getTableData().fullData;
          if (szTaZdMbDTOs.length === 0) {
            this.$baseAlert(this.$t1("明细不能为空！"));
            return false;
          }
          this.szTaMb.szTaZdMbDTOs = szTaZdMbDTOs;
          this.openPreformDialog();
        }
      });
    },
    saveDataHandle(preformData) {
      let formData = {
        ...this.szTaMb,
        logContent: preformData.logContent,
      };
      // const formData = this.szTaMb;
      // formData.szTaZdMbDTOs = szTaZdMbDTOs;

      var url = USER_PREFIX + (this.isEdit ? `/szTaMb/update` : `/szTaMb/save`);
      this.$http({
        aes: true,
        url: url,
        method: `post`,
        data: formData,
        isLoading: true,
        success: (res) => {
          this.$message({
            message: res.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              if (this.isEdit) {
                this.$baseReload();
              } else {
                this.$baseReload({
                  updateParam: {
                    _dataId: res.objx,
                  },
                });
              }
            },
          });
        },
      });
    },
    openPreformDialog() {
      this.showPreformDialog = true;
    },
    confirmPreformDialog(preformData) {
      this.saveDataHandle(preformData);
    },
    initTableProduct() {
      const tableOption = {
        vue: this,
        tableRef: "table-szTaZdMb",
        tableName: "edit-szTaMb-szTaZdMb",
        config: {
          maxHeight: "600px",
        },
        columns: [
          {type: "checkbox", fixed: "left", width: 48, resizable: false},
          {
            title: this.$t1("实体字段名称"),
            field: "zdEn",
            width: 150,
            fixed: "left",
            slots: {
              default: "zdEn",
            },
          },
          {
            title: this.$t1("数据库表字段名"),
            field: "taZdMc",
            width: 150,
            fixed: "left",
          },
          {
            title: this.$t1("数据库表字段是否已创建"),
            field: "isFieldCreated",
            width: 200,
            slots: {
              default: ({row, rowIndex, $table}) => {
                let taZdMc = row.taZdMc;
                let createdTableColumnArray = this.createdTableColumnArray;
                let oldResult = createdTableColumnArray.includes(row?.hData?.taZdMc)
                  ? "是"
                  : "_";
                let result = taZdMc && createdTableColumnArray.includes(taZdMc)
                  ? "是"
                  : "_";
                  return [
                    <el-form-item>
                      <fieldCompare
                        isCompare={this.isCompare}
                        oldVal={oldResult}
                        newVal={result}
                      >
                        {result}
                      </fieldCompare>
                    </el-form-item>
                  ]
              },
            },
          },
          {
            title: this.$t1("字段描述"),
            field: "zdCh",
            width: 150,
            slots: {
              default: "zdCh",
            },
          },
          {
            title: this.$t1("字段类型"),
            field: "zdType",
            width: 150,
            slots: {
              default: "zdType",
            },
          },
          {
            title: this.$t1("字段长度"),
            field: "zdLength",
            width: 150,
            slots: {
              default: "zdLength",
            },
          },
          {
            title: this.$t1("树标识"),
            field: "treeFlag",
            width: 150,
            slots: {
              default: "treeFlag",
            },
          },
          {
            title: this.$t1("关联字段"),
            field: "referenceZd",
            width: 250,
            slots: {
              default: "referenceZd",
            },
          },
          {
            title: this.$t1("来源关联字段"),
            field: "relationZd",
            width: 250,
          },
          {
            title: this.$t1("关联表对应服务名"),
            field: "refServiceName",
            width: 200,
          },
          {
            title: this.$t1("数据值对应表的字段"),
            field: "toTaBmZd",
            width: 250,
            slots: {
              default: "toTaBmZd",
            },
          },
          {
            title: this.$t1("字段类型对应的默认值"),
            field: "zdTypeValues",
            width: 200,
            slots: {
              default: "zdTypeValues",
            },
          },
          {
            title: this.$t1("是否必填项"),
            field: "required",
            width: 140,
            params: {
              exportVal:({row,column})=>{
                return this.$t1(row[column.field]? "是": "否")
              }
            },
            slots: {
              default: "required",
            },
          },
          {
            title: this.$t1("是否启用"),
            field: "enabled",
            width: 120,
            params: {
              exportVal:({row,column})=>{
                return this.$t1(row[column.field]? "是": "否")
              }
            },
            slots: {
              default: "enabled",
            },
          },

          {
            title: this.$t1("是否自动生成编码"),
            field: "generateCode",
            width: 180,
            params: {
              exportVal:({row,column})=>{
                return this.$t1(row[column.field]? "是": "否")
              }
            },
            slots: {
              default: "generateCode",
            },
          },
          {
            title: this.$t1('数据库字段加密'),
            field: 'atened',
            width: 180,
            params: {
              exportVal:({row,column})=>{
                return this.$t1(row[column.field]? "是": "否")
              }
            },
            slots: {
              default: "atened"
            }
          },
          {
            title: this.$t1('是否更新忽略字段'),
            field: 'updateIgnore',
            width: 180,
            params: {
              exportVal:({row,column})=>{
                return this.$t1(row[column.field]? "是": "否")
              }
            },
            slots: {
              default: "updateIgnore"
            }
          },
          {
            title: this.$t1("编码类型"),
            field: "codeType",
            width: 150,
            slots: {
              default: "codeType",
            },
          },
          {
            title: this.$t1("序号"),
            field: "orders",
            width: 150,
            slots: {
              default: "orders",
            },
          },
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({row, rowIndex, $table}) => {
                let taZdMc = row.taZdMc;
                let createdTableColumnArray =
                  this.createdTableColumnArray || [];
                let hasCreated =
                  !!taZdMc && createdTableColumnArray.includes(taZdMc);
                // let style = !row.relationZd ? "margin-left:20px" : "";
                if (!row.systems && !hasCreated && !this.readonly) {
                  //非内置，未创建字段，非关联表带出来的字段
                  return getJsxBtn({
                    iconName: "el-icon-delete",
                    content: this.$t1("删除"),
                    onclick: () => {
                      this.deleteItem(row, rowIndex);
                    },
                  });
                }
              },
            },
          },
        ],
        config:{
          // rowConfig:{
          //   height: 60,
          // }
        }
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.productOption = opts;
      });
      if (this.dataId) {
        this.$http({
          aes: true,
          url: USER_PREFIX + `/szTaMb/getSzTaZdMbs`,
          method: `post`,
          data: {
            id: this.dataId,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            this.szTaMb.szTaZdMbDTOs = res.objx || [];
          },
        });
      }
    },
    addTaMbItems() {
      // let tacitly = true;
      // if (this.customer.szTaZdMbDTOs.length > 0) {
      //   tacitly = false;
      // }
      // this.customer.szTaZdMbDTOs.push({tacitly: tacitly});
      let newIndex = this.getNewIndex();
      /* let item = {
        zdEn: null,
        zdCh: null,
        taZdMc: null,
        zdTypeValues: null,
        required: false,
        codeType: null,
        referenceZd: null,
        zdType: "Text",
        zdLength: "255",
        enabled: true,
        orders: newIndex,
        relationZd:null,
        refServiceName:null,

        generateCode: false,
        fromTable: false,
        toTaBmZd: null,
        treeFlag: null,
        atened: false,
        updateIgnore: false
      }; */
      let item = this.createRow();
      item.orders = newIndex,
      this.szTaMb.szTaZdMbDTOs.splice(0, 0, item);
    },
    deleteItem(row, rowIndex) {
      if (row.referenceZd) {
        this.clearReferenceZd(row);
      }
      this.szTaMb.szTaZdMbDTOs.splice(rowIndex, 1);
    },
    confirmInsertSzTaMb(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        this.$set(this.szTaMb, "sszst", row.taCode);
        this.$set(this.szTaMb, "sszstEn", row.taEn);
        this.$set(this.szTaMb, "sszstBm", row.taBm);
      }
    },
    confirmInsertItemSzTaMb(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        let szTaZdMbDTO = this.szTaMb.szTaZdMbDTOs[this.zdEnIndex];
        this.$set(szTaZdMbDTO, "zdEn", row.taBm + "." + szTaZdMbDTO.zdEn);
        this.$set(szTaZdMbDTO, "dybm", row.taEn);
      }
    },
    confirmInsertMenuKind(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        this.$set(this.szTaMb, "menuKindCode", row.menuKindCode);
        this.$set(this.szTaMb, "menuKindName", row.name);
      }
    },
    getNewData(callback) {
      this.getData((res0) => {
        let szTaMb = res0.objx;
        this.$http({
          aes: true,
          url: USER_PREFIX + `/szTaMb/getSzTaZdMbs`,
          method: `post`,
          data: {
            id: this.dataId,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res1) => {
            szTaMb.szTaZdMbDTOs = res1.objx || [];
            callback(szTaMb);
          },
        });
      });
    },
    createModifyTable() {
      let text = this.$t1("您确定要创建/更新数据表吗？");
      this.$baseConfirm(text).then(() => {
        this.getNewData((data) => {
          this.$http({
            aes: true,
            url: "/" + this.szTaMb.serviceName + `/dbTable/createUpdateTable`,
            method: `post`,
            data: data,
            isLoading: true,
            success: (res) => {
              this.$message({
                message: res.content,
                type: "success",
                duration: 500,
                onClose: (t) => {
                  this.$baseReload();
                },
              });
            },
          });
        });
      });
    },
    isReferenceZdType(zdType) {
      return zdType === "Reference" || zdType === "ReferenceLong";
    },
    openReferenceZdDialog(row, rowIndex, $table) {
      let referenceZd = row.referenceZd;
      let referenceZd2 = row.referenceZd + "." + row.zdEn;
      let referenceEntity = null;
      let referenceKey = null;
      let referenceShowFields = [];

      if (referenceZd) {
        let index = referenceZd.indexOf(".");
        referenceEntity = referenceZd.substring(0, index);
        referenceKey = referenceZd.substr(index + 1);
        referenceShowFields = this.szTaMb.szTaZdMbDTOs
          .filter((item) => {
            let flag = false;
            if (item.relationZd === referenceZd || item.relationZd === referenceZd2) {
              flag = true
            }
            return flag;
          })
          .map((item) => {
            return item.referenceZd.substr(index + 1);
          });
      }

      this.referenceEntity = referenceEntity;
      this.referenceKey = referenceKey;
      this.referenceShowFields = referenceShowFields;
      this.refServiceName = row.refServiceName ?? null;

      this.referenceShowRows = referenceShowFields.map((item) => {
        return {
          taZdMc: item,
        };
      });

      this.currentIndex = rowIndex;
      this.showReferenceZdDialog = true;
    },
    changeZdType(row) {
      let map = {
        "Integer": "11",
        "Long": "20",
        "ReferenceLong": "20",
        "Decimal": "21,6",
        "Money": "21,2",
        "Text": "255"
      }
      row.zdLength = map[row.zdType] || null;
      if (!this.isReferenceZdType(row.zdType)) {
        this.clearReferenceZd(row);
      }
    },
    getReferenceChildRows(row) {
      let referenceZd = row.referenceZd;
      if (!referenceZd && !row.zdEn) {
        return [];
      }
      let referenceZd2 = referenceZd ? referenceZd + "." + row.zdEn : null;
      let relationZdSuffix = row.zdEn ? "." + row.zdEn : null;
      return this.szTaMb.szTaZdMbDTOs.filter((item) => {
        if (referenceZd && (referenceZd === item.relationZd || referenceZd2 === item.relationZd)) {
          return true;
        }
        if (relationZdSuffix && item.relationZd && item.relationZd.endsWith(relationZdSuffix)) {
          return true;
        }
        return false;
      });
    },
    confirmClearReferenceZd(row) {
      if (!row.referenceZd) {
        return;
      }
      if (this.hasFieldCreated(row)) {
        this.$baseAlert(this.$t1("该字段已在数据库中创建，不能清空关联配置"));
        return;
      }
      let childRows = this.getReferenceChildRows(row);
      if (childRows.some((item) => this.hasFieldCreated(item))) {
        this.$baseAlert(this.$t1("关联显示字段已在数据库中创建，不能清空关联配置"));
        return;
      }
      let text = this.$t1("清空关联配置将同时删除关联显示字段，您确定要继续吗？");
      this.$baseConfirm(text).then(() => {
        this.clearReferenceZd(row);
      });
    },
    clearReferenceZd(row) {
      let referenceZd = row.referenceZd;
      if (referenceZd) {
        let referenceZd2 = referenceZd + "." + row.zdEn;
        this.szTaMb.szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs.filter((item) => {
          return referenceZd !== item.relationZd && referenceZd2 !== item.relationZd;
        });
      } else if (row.zdEn) {
        let relationZdSuffix = "." + row.zdEn;
        this.szTaMb.szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs.filter((item) => {
          return !(item.relationZd && item.relationZd.endsWith(relationZdSuffix));
        });
      }
      row.referenceZd = null;
      row.refServiceName = null;
    },
    confirmReferenceZdDialog() {
      let row = this.szTaMb.szTaZdMbDTOs[this.currentIndex];
      let oldReferenceZd = row.referenceZd;
      let oldReferenceZd2 = row.referenceZd + "." + row.zdEn;

      let referenceEntity = this.referenceEntity;
      let refServiceName = this.refServiceName;
      let referenceKey = this.referenceKey
      let referenceZd = referenceEntity && referenceKey ? (referenceEntity + "." + referenceKey) : null;

      let referenceShowFields = this.referenceShowFields;

      let keys = referenceShowFields.map((item) => {
        return referenceEntity + "." + item;
      });
      if (oldReferenceZd) {
        let index0 = oldReferenceZd.indexOf(".");
        let oldReferenceEntity = oldReferenceZd.substring(0, index0);
        let delIndex = [];
        if (referenceEntity !== oldReferenceEntity) {
          this.szTaMb.szTaZdMbDTOs.forEach((item, index) => {
            if (item.relationZd && (oldReferenceZd === item.relationZd || oldReferenceZd2 === item.relationZd)) {
              delIndex.push(index);
            }
          });
        } else {
          this.szTaMb.szTaZdMbDTOs.forEach((item, index) => {
            if (oldReferenceZd === item.relationZd || oldReferenceZd2 === item.relationZd) {
              if (!keys.includes(item.referenceZd)) {
                delIndex.push(index);
              } else {
                item.refServiceName = refServiceName;
              }
            }
          });
        }
        if (delIndex.length) {
          delIndex.reverse().forEach((i) => {
            this.szTaMb.szTaZdMbDTOs.splice(i, 1);
          });
        }
      }

      let oldKeys = this.szTaMb.szTaZdMbDTOs
        .filter((item) => (referenceZd === item.relationZd || (referenceZd + "." + item.zdEn) === item.relationZd))
        .map((item) => item.referenceZd);
      let addReferenceShowFields = referenceShowFields.filter((item, index) => {
        return !oldKeys.includes(referenceEntity + "." + item);
      });

      let addIndex = -1;
      let lastIndex = this.szTaMb.szTaZdMbDTOs.findLastIndex((item) => {
        return referenceZd === item.relationZd || (referenceZd + "." + item.zdEn) === item.relationZd;
      });
      addIndex = lastIndex >= 0 ? lastIndex + 1 : this.currentIndex + 1;

      let referenceShowRows = this.referenceShowRows;

      let addReferenceShowRows = referenceShowRows.filter((item, index) => {
        return addReferenceShowFields.includes(item.taZdMc);
      });
      addReferenceShowRows.forEach((item, index) => {
        let rIndex = addIndex + index;
        let orders = (row.orders || 0) + index + 1;

        let newItem = this.createRow();
        Object.assign(newItem, {
          zdEn: "ref_" + item.zdEn,
          zdCh: item.zdCh,
          required: false,
          referenceZd: referenceEntity + "." + item.taZdMc,
          zdType: "Text",
          zdLength: "255",
          enabled: true,
          orders,
          relationZd: referenceZd + "." + row.zdEn,
          refServiceName,
        })

        this.szTaMb.szTaZdMbDTOs.splice(rIndex, 0, newItem);
      });
      row.referenceZd = referenceZd;
      row.refServiceName = refServiceName;
      this.handleReferenceOrders(row);
      this.showReferenceZdDialog = false;
    },
    createRow(){
      let row = {
        "orders": null,
        "taCode": null,
        "zdCode": null,
        "zdEn": null,
        "zdCh": null,
        "taZdMc": null,
        "zdType": "Text",
        "zdLength": "255",
        "referenceZd": null,
        "relationZd": null,
        "refServiceName": null,
        "zdTypeValues": null,
        "required": false,
        "requiredMsg": null,
        "regexpVal": null,
        "regexpMsg": null,
        "enabled": true,
        "systems": false,
        "generateCode": false,
        "codeType": null,
        "toTaBmZd": null,
        "fromTable": false,
        "treeFlag": null,
        "atened": false,
        "updateIgnore": false,
        "abc": null
      }
      return row;
    },
    changeOrders(row) {
      this.handleReferenceOrders(row);
    },
    handleReferenceOrders(row) {
      let referenceZd = row.referenceZd;
      let orders = row.orders || 0;
      if (referenceZd) {
        this.szTaMb.szTaZdMbDTOs
          .filter((item) => referenceZd === item.relationZd || (referenceZd + "." + item.zdEn === item.relationZd))
          .forEach((item, index) => {
            if (referenceZd === item.relationZd || (referenceZd + "." + item.zdEn === item.relationZd)) {
              item.orders = orders + index + 1;
            }
          });
      }
    },
    confirmEntityDialog(rows) {
      if (rows.length) {
        let row = rows[0];
        if (this.referenceEntity !== row.taBm) {
          this.referenceKey = null;
          this.referenceShowFields = [];
        }
        this.referenceEntity = row.taBm;
        this.refServiceName = row.serviceName;
      }
    },
    openEntityFieldDialog1() {
      if (!this.referenceEntity) {
        this.$baseAlert("关联表不能为空");
        return;
      }
      this.showEntityFieldDialog1 = true;
    },
    confirmEntityFieldDialog1(rows) {
      if (rows.length) {
        let row = rows[0];
        this.referenceKey = row.taZdMc;
      }
    },
    openEntityFieldDialog2() {
      if (!this.referenceEntity) {
        this.$baseAlert("关联表不能为空");
        return;
      }
      this.showEntityFieldDialog2 = true;
    },
    confirmEntityFieldDialog2(rows) {
      if (rows.length) {
        this.referenceShowRows = rows;
        this.referenceShowFields = rows.map((row) => {
          return row.taZdMc;
        });
      }
    },
    getCreatedTableColumns() {
      if (!this.szTaMb.taBm) return;
      this.$http({
        aes: true,
        url: "/" + this.szTaMb.serviceName + "/dbTable/getTableColumns",
        method: `post`,
        data: {
          stringOne: this.szTaMb.taBm,
        },
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          if (res.objx) {
            this.createdTableColumnStr = res.objx;
            let createdTableColumnArray = res.objx
              .split(",")
              .filter((item) => !!item);
            this.createdTableColumnArray = createdTableColumnArray;
          }
        },
      });
    },
    getTreeDefaultZds() {
      this.$http({
        aes: true,
        url: USER_PREFIX + `/szTaMb/getTreeDefaultZds`,
        method: `post`,
        data: {},
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          let rows = res.objx || [];
          this.treeDefaultZds = rows;
        },
      });
    },
    hasFieldCreated(row) {
      let taZdMc = row.taZdMc;
      let createdTableColumnArray = this.createdTableColumnArray || [];
      let hasCreated = !!taZdMc && createdTableColumnArray.includes(taZdMc);
      return hasCreated;
    },
    changeTaRule(val) {
      let treeDefaultZds = this.$baseLodash.cloneDeep(this.treeDefaultZds);
      let szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs;
      if (val === 1) {
        let zdEns = szTaZdMbDTOs
          .filter((item) => !!item.zdEn)
          .map((item) => item.zdEn);
        if (zdEns.length) {
          treeDefaultZds = treeDefaultZds.filter((item) => {
            return !zdEns.includes(item.zdEn);
          });
        }
        let newIndex = this.getNewIndex();
        treeDefaultZds.forEach((item, index) => {
          item.orders = newIndex + index;
        });
        szTaZdMbDTOs.push(...treeDefaultZds);
      } else {
        let zdEns = szTaZdMbDTOs
          .filter((item) => !!item.zdEn)
          .map((item) => item.zdEn);
        let createdFields = szTaZdMbDTOs
          .filter((item) => {
            return !!item.zdEn && this.hasFieldCreated(item);
          })
          .map((item) => item.zdEn);
        if (zdEns.length) {
          treeDefaultZds = treeDefaultZds.filter((item) => {
            return (
              !createdFields.includes(item.zdEn) && zdEns.includes(item.zdEn)
            );
          });
        }
        let delFields = treeDefaultZds.map((item) => item.zdEn);
        this.szTaMb.szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs.filter(
          (item) => !delFields.includes(item.zdEn)
        );
      }
    },
    getNewIndex() {
      let min = 100;
      let szTaZdMbDTOs = this.szTaMb.szTaZdMbDTOs;
      let value = 0;
      let allOrders = szTaZdMbDTOs
        .filter((item) => item.orders !== null && item.orders !== undefined)
        .map((item) => item.orders);
      szTaZdMbDTOs.forEach((item) => {
        let orders = item.orders;
        if (orders !== null && orders !== undefined && orders < 9000) {
          value = Math.max(value, orders);
        }
      });
      let newIndex = Math.max(min, value + 10);
      return newIndex;
    },
    getBdEnv() {
      getBdFlag({
        success: (res) => {
          this.isDev = res.objx === 1;
        },
      });
    },

    getMenuKindAuth(menuKindCode) {
      if(this.otherFlag){
        this.getOtherMenuKindAuth();
      }else if (menuKindCode) {
        this.$http({
          aes: true,
          url: USER_PREFIX + "/menu_kind_auth/getAuth",
          method: `post`,
          data: {stringOne: menuKindCode},
          isLoading: true,
          success: (res) => {
            this.menuKindAuth = res.objx || {};
          },
        });
      }
    },
    openDtDialog() {
      //引用数据库中数据表结构
      this.dbTable = null;
      this.showDtDialog = true;
    },
    confirmDtDialog() {
      let dbTable = this.dbTable;
      if (!dbTable) {
        this.$baseAlert(this.$t1("数据表不能为空"));
        return;
      }
      this.showDtDialog = false;
      this.$http({
        // aes: true,
        url: "/" + this.szTaMb.serviceName + `/dbTable/getSzTaZdMbs`,
        method: `post`,
        data: {
          stringOne: dbTable,
        },
        isLoading: true,
        success: (res) => {
          let items = res.objx || [];
          if (!items.length) {
            this.$baseAlert(this.$t1("数据表[{dbTable}]不存在", {dbTable}));
            return;
          }
          let szTaZdMbDTOs = items
            .filter((item) => !item.systems)
            .map((item) => {
              return {
                ...item,
                createBy: null,
                createDate: null,
                fromTable: true,
                id: null,
                modifyBy: null,
                modifyDate: null,
              };
            });
          this.szTaMb.taEn = dbTable;
          this.szTaMb.taBm = dbTable;
          this.szTaMb.szTaZdMbDTOs = szTaZdMbDTOs;
        },
      });
    },
    openTmDialog() {
      //引用数据表定义的结构
      this.showTmDialog = true;
    },
    confirmTmDialog(rows) {
      if (rows.length) {
        let row = rows[0];
        this.$http({
          aes: true,
          url: USER_PREFIX + `/szTaMb/getSzTaZdMbs`,
          method: `post`,
          data: {
            id: row.id,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            let items = res.objx || [];
            let szTaZdMbDTOs = items
              .filter((item) => !item.systems)
              .map((item) => {
                return {
                  ...item,
                  createBy: null,
                  createDate: null,
                  fromTable: true,
                  id: null,
                  modifyBy: null,
                  modifyDate: null,
                };
              });
            let newRow = {
              ...row,
              createBy: null,
              createDate: null,
              fromTable: true,
              id: null,
              modifyBy: null,
              modifyDate: null,
              sid: null,
              // taBm: null,
              taCode: null,
            };
            Object.keys(newRow).forEach((key) => {
              if (key.endsWith("DTOs")) {
                delete newRow[key];
              }
            });
            Object.assign(this.szTaMb, newRow);
            this.szTaMb.szTaZdMbDTOs = szTaZdMbDTOs;
          },
        });
      }
    },
    openToTaBmZdDialog(row, rowIndex, $table) {
      let toTaBmZd = row.toTaBmZd;
      let toTaBmZdEntity = null;
      let toTaBmZdField = null;
      if (toTaBmZd) {
        toTaBmZd.split(".").forEach((item, index) => {
          if (index === 0) {
            toTaBmZdEntity = item;
          } else if (index === 1) {
            toTaBmZdField = item;
          }
        });
      } else {
        if (this.szTaMb.taType === 1 && this.szTaMb.sszstBm) {
          toTaBmZdEntity = this.szTaMb.sszstBm;
        }
      }
      this.toTaBmZdEntity = toTaBmZdEntity;
      this.toTaBmZdField = toTaBmZdField;
      this.currentIndex = rowIndex;
      this.showToTaBmZdDialog = true;
    },
    confirmToTaBmZdDialog() {
      let toTaBmZdEntity = this.toTaBmZdEntity;
      let toTaBmZdField = this.toTaBmZdField;
      if (!toTaBmZdEntity) {
        this.$baseAlert(this.$t1("对应表不能为空"));
        return;
      }
      if (!toTaBmZdField) {
        this.$baseAlert(this.$t1("对应表字段不能为空"));
        return;
      }
      this.szTaMb.szTaZdMbDTOs[this.currentIndex].toTaBmZd =
        toTaBmZdEntity + "." + toTaBmZdField;
      this.showToTaBmZdDialog = false;
    },
    openEntityDialog3() {
      this.showEntityDialog3 = true;
    },
    confirmEntityDialog3(rows) {
      if (rows.length) {
        let row = rows[0];
        if (this.toTaBmZdEntity !== row.taBm) {
          this.toTaBmZdEntity = row.taBm;
          this.toTaBmZdField = null;
        }
      }
    },
    openEntityFieldDialog3() {
      if (!this.toTaBmZdEntity) {
        this.$baseAlert(this.$t1("关联表不能为空"));
        return;
      }
      this.showEntityFieldDialog3 = true;
    },
    confirmEntityFieldDialog3(rows) {
      if (rows.length) {
        let row = rows[0];
        this.toTaBmZdField = row.taZdMc;
      }
    },
    inputZdEn(row) {

      this.preValue = row.zdEn; // 更新旧值
      this.fkey = true
    },
    changeZdEn(val, row) {
      if(!this.fkey)return
      let oldVal = this.preValue;
      let newVal = val
      if (this.isReferenceZdType(row.zdType)) {
        let referenceZd = row.referenceZd;
        if (referenceZd) {
          let referenceZd2 = row.referenceZd + "." + oldVal
          let relationZd = row.referenceZd + "." + newVal
          this.szTaMb.szTaZdMbDTOs.forEach((item, index) => {
            if (referenceZd === item.relationZd || referenceZd2 === item.relationZd) {
              item.relationZd = relationZd;
            }
          });
        }
      }
      this.fkey = false
    },

    getOtherMenuKindAuth() {
      if (this.otherFlag && this.szTaMb.sid) {
        this.$http({
          aes: true,
          url: USER_PREFIX + "/sz_ta_mb_auth/getAuth",
          method: `post`,
          data: {stringOne: this.szTaMb.sid},
          isLoading: true,
          success: (res) => {
            this.menuKindAuth = res.objx || {};
          },
        });
      }
    },
    openOtherAuthDialog(){
      this.sid = this.szTaMb.sid
      this.showOtherAuthDialog = true
    },
    confirmOtherAuthDialog(){
      this.$baseReload()
    },
    excelExport(){
      this.$excelExport({title: '数据表字段明细导出', targetRef: 'table-szTaZdMb', prefix: USER_PREFIX, type: 'selected'})
    },
    getHValue(row, column) {
      if (row.hData && row.hData.id) {
        let result = row.hData[column.property];
        if(column.property === 'zdType'){
          result = this.zdTypeMap[result]
        }else if(column.property === 'treeFlag'){
          result = this.treeFlagMap[result]
        }
        return result
      }/*  else if (!row?.hData?.id) {
        return "HAS_NO_HDATA";
      } */ else {
        return null;
      }
    },
  },
};
export default modules;
