<template>
  <el-dialog
    :title="$t1('导出数据')"
    width="355px"
    custom-class="dialog-style list-dialog"
    :visible.sync="showDialog"
    :modal="false"
    :append-to-body="false"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    v-el-dialog-center
    :before-close="handleBeforeClose"
  >
    <div class="cont" style="max-height: 500px">
      <div class="tit" style="margin-bottom: 5px">
        <b>{{ $t1("导出字段") }}</b>
      </div>
      <el-tree
        :props="defaultProps"
        :data="data"
        show-checkbox
        node-key="id"
        ref="tree"
        default-expand-all
        check-on-click-node
        :expand-on-click-node="false"
        icon-class="el-icon-arrow-right"
        :default-checked-keys="defaultCheckedKeys"
      ></el-tree>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" plain class="button-sty" @click="handleDialogClose">
        <i class="el-icon-close el-icon"></i>
        {{ $t1("取 消") }}
      </el-button>
      <el-button type="primary" @click="dialogConfirm" class="button-sty">
        <i class="el-icon-check el-icon"></i>
        {{ $t1("确 定") }}
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import xeUtils from "xe-utils";
export default {
  name: "exportFieldDialog",
  props: ["param"],
  data() {
    return {
      showDialog: true,
      data: [],
      defaultProps: {
        label: "title", //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: "children",
      },
      defaultCheckedKeys: [],
      columns: [],
      allFields: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    loopColumnHandle(items, handler) {
      items.forEach((item) => {
        handler(item);
        if (item.children && item.children.length) {
          this.loopColumnHandle(item.children, handler);
        }
      });
    },
    generateId() {
      return Math.floor(
        Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
      );
    },
    filterExportVisible(items) {
      if (!Array.isArray(items)) return [];

      return items
        .filter((item) => item.exportItemVisible === true) // 只保留 exportItemVisible 严格等于 true 的项
        .map((item) => {
          // 如果有 children，递归过滤
          if (Array.isArray(item.children)) {
            return {
              ...item,
              children: this.filterExportVisible(item.children),
            };
          }
          return item;
        });
    },
    init() {
      let target = this.getGrid();
      let { fullColumn, collectColumn: column1s } = target.getTableColumn();

      let checkMethod = target.$refs.xTable.customOpts?.checkMethod;
      // var checkMethod = $xetable ? $xetable.customOpts.checkMethod : null;
      // let columns = target.getTableColumn().collectColumn;
      let columns = [];
      let allFields = [];
      if (checkMethod) {
        const handleColumnVisible = (column) => {
          if (!column.title) return false;
          let visible = true;

          let isColGroup = column.children && column.children.length;

          if (isColGroup) {
            // 如果是分组字段，则根据子字段的显示状态来处理
            let parentVisible = false;
            column.children.forEach((item) => {
              let itemVisible = handleColumnVisible(item);
              if (itemVisible) {
                parentVisible = true;
              }
            });
            visible = parentVisible;
            /* visible = column.children.some((item) => {
              return handleColumnVisible(item);
            }); */
          } else {
            let isDisabled = !checkMethod({
              column: column,
            });
            if (isDisabled) {
              // 如果字段被禁用勾选，根据显示状态来处理
              visible = column.visible;
            }
            if (column.field && visible) {
              allFields.push(column.field);
            }
          }
          column.exportItemVisible = visible;
          return visible;
        };
        column1s.forEach((column) => {
          return handleColumnVisible(column);
        });
        columns = this.filterExportVisible(column1s);
      } else {
        columns = column1s;
      }

      let exportItem = this.param.type === "exportItem";

      let defaultCheckedKeys = [];
      let cols = [];

      let yesFields = [];
      let noFields = [];

      let exportColumns = !exportItem
        ? target.exportColumns || []
        : target.exportItemColumns || [];

      this.loopColumnHandle(exportColumns, (item) => {
        if (item.field) {
          if (item.export) {
            yesFields.push(item.field);
          } else {
            noFields.push(item.field);
          }
        }
      });

      if (!exportItem) {
        //导出主表数据

        fullColumn.forEach((column) => {
          if (column.field) {
            if (yesFields.includes(column.field)) {
              defaultCheckedKeys.push(column.id);
            } else if (!noFields.includes(column.field) && column.visible) {
              defaultCheckedKeys.push(column.id);
            }
          }
        });
        columns.forEach((column) => {
          if (column.title) {
            cols.push(column);
          }
        });
      } else {
        //导出子表数据
        let exportItemColumns = target.exportItemColumns || [];
        let originOption = target.params.originOption;
        let oriExportItemColumns = originOption.exportItemConfig?.columns || [];

        this.loopColumnHandle(oriExportItemColumns, (item) => {
          item.id = this.generateId();
          if (item.field && allFields.includes(item.field)) {
            if (yesFields.includes(item.field)) {
              defaultCheckedKeys.push(item.id);
            } else if (!noFields.includes(item.field)) {
              defaultCheckedKeys.push(item.id);
            }
            // allFields.push(item.field);
          }
        });
        oriExportItemColumns.forEach((column) => {
          if (column.title) {
            cols.push(column);
          }
        });
      }

      this.allFields = allFields;
      this.defaultCheckedKeys = defaultCheckedKeys;
      /* let data = [
        {
          label: this.$t1("全部字段"),
          id: -1,
          leaf: true,
          children: this.$baseLodash.cloneDeep(cols),
        },
      ]; */
      this.data = this.$baseLodash.cloneDeep(cols);
    },
    addTableExportColumns() {
      let exportItem = this.param.type === "exportItem";

      let $grid = this.getGrid();
      let originOption = $grid.params.originOption;
      let leafColumns = this.$refs.tree.getCheckedNodes(true);
      let checkLeafIds = leafColumns.map((item) => item.id);

      // let syncEportItemColumns = $grid.exportItemColumns || [];
      // let syncExportColumns = $grid.exportColumns || [];

      if (!exportItem) {
        //导出主表数据
        let exportColumns = [];
        let { fullColumn } = $grid.getTableColumn();
        fullColumn.map((column) => {
          if (column.field && column.title) {
            let item = {
              field: column.field,
              export: checkLeafIds.includes(column.id),
            };
            exportColumns.push(item);
          }
        });
        $grid.exportColumns = exportColumns;
      } else {
        //导出子表数据
        let exportItemColumns = [];
        if (originOption.exportItemConfig?.columns?.length) {
          this.loopColumnHandle(originOption.exportItemConfig?.columns, (column) => {
            if (column.field && column.title) {
              let item = {
                field: column.field,
                export: checkLeafIds.includes(column.id),
              };
              exportItemColumns.push(item);
            }
          });
          $grid.exportItemColumns = exportItemColumns;
        }
      }
      this.$vxeTableUtil.addTableJson(originOption.vue, $grid, originOption.tableName);
    },
    handleBeforeClose(hide) {
      // this.$emit('cancel');
      this.handleDialogClose();
      hide();
    },
    handleDialogClose() {
      this.$emit("close");
      this.dialogClose();
    },
    dialogClose() {
      this.showDialog = false;
      this.$emit("update:visiable", false);
    },
    dialogConfirm() {
      let target = this.getGrid();
      let originOption = target.params.originOption;
      let leafColumns = this.$refs.tree.getCheckedNodes(true);
      let checkIds = this.$refs.tree.getCheckedNodes(false, true).map((item) => item.id);
      let exportItem = this.param.type == "exportItem";
      let collectColumn = !exportItem
        ? target.getTableColumn().collectColumn
        : originOption.exportItemConfig?.columns;
      let maxRowspan = 1;
      leafColumns.forEach((item) => {
        maxRowspan = Math.max(maxRowspan, item.level);
      });

      let loopDo = (items, parent) => {
        let datas = [];
        items.forEach((item) => {
          if (checkIds.includes(item.id)) {
            let column = this.$baseLodash.cloneDeep(item);
            if (item.children && item.children.length > 0) {
              let children = this.$baseLodash.cloneDeep(loopDo(item.children));
              column.children = children;
              if (children.length) {
                column.colSpan = children.length;
              } else {
                column.colSpan = 1;
              }
            } else if (!column.parentId) {
              column.rowSpan = maxRowspan;
            }
            datas.push(column);
          }
        });
        return datas;
      };
      let columns = loopDo(collectColumn, null);
      this.$emit("confirm", { columns, leafColumns });
      this.addTableExportColumns();
      this.dialogClose();
    },
    /* getExportTitleJson() {
      let target = this.getGrid();
      let columns = target.getColumns();
      let cols = [];
      columns.forEach((column) => {
        if (column.title && column.visible) {
          cols.push(column);
        }
      });
      return cols;
    }, */
    getGrid() {
      let that = this.param.vue;
      let tableRef = this.param.targetRef;
      let $grid;
      if (Array.isArray(that.$refs[tableRef])) {
        $grid = that.$refs[tableRef][0];
      } else {
        $grid = that.$refs[tableRef];
      }
      return $grid;
    },
    revert() {},
  },
};
</script>

<style scoped></style>
