<template>
  <!-- <div class="tables2"> -->
  <!-- <sort-cell :optData="optData" @menuclick="handleSortClick" /> -->
  <div ref="wrapper" class="tables2-wrapper bdlite-chart-item"></div>
  <!-- <div class="tables2-footer" v-if="paginationShow">
      <a-config-provider :locale="locale" prefixCls="biAnt">
        <a-pagination
          class="tables2-footer-page"
          size="small"
          :total="total"
          :current="chartStatus.page.pageNum"
          :pageSize="chartStatus.page.pageSize"
          :pageSizeOptions="['10', '20', '30', '50', '100', '200', '500']"
          :show-total="(total) => `共 ${total} 条`"
          :hide-on-single-page="
            chartData.iconConfig.options.style.pagination.autoHide
          "
          @showSizeChange="handleSizeChange"
          @change="handleCurrentChange"
          show-size-changer
          show-quick-jumper
        />
      </a-config-provider>
    </div> -->
  <!-- </div> -->
</template>

<script>
import {
  defineComponent,
  watch,
  ref,
  onMounted,
  computed,
  onUnmounted,
  nextTick,
} from "@vue/composition-api";
// import { Pagination, ConfigProvider } from "ant-design-vue";
import { throttle, cloneDeep } from "lodash-es";

import { TableSheet, S2Event, generatePalette, getPalette } from "@antv/s2";
// import Sort from "./sort.vue";
// import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";

// import { getFormat, getLinkFields } from "./utils";
import { getLinkFields } from "./utils";

export default defineComponent({
  name: "shufflTable",
  components: {
    // [Pagination.name]: Pagination,
    // [ConfigProvider.name]: ConfigProvider,
    // "sort-cell": Sort,
  },
  emits: ["loaded"],
  props: {
    chartData: Object,
    id: String,
    sortField: Object,
    chartStatus: Object,
  },

  destroyed() {
    console.log("销毁");
  },
  setup(props, vm) {
    const { dataResult = [] } = props.chartData;

    // 排序字段
    // const calcSortFields = computed(() => {
    //   if (!isEmpty(props.sortField)) {
    //     const { fieldId } = props.sortField;
    //     const originFields = cloneDeep(props.chartData.dataConfig.columns).find(
    //       (i) => i.fieldId === fieldId
    //     );

    //     return originFields
    //       ? [
    //           {
    //             field: originFields.columnName,
    //             fieldId: originFields.fieldId,
    //             orderDirection: props.sortField.orderDirection,
    //           },
    //         ]
    //       : [];
    //   }

    //   return (
    //     props.chartData.dataConfig?.columns
    //       ?.filter((item) => item?.config?.orderDirection)
    //       .map((item) => {
    //         const key = item.editorTitle || item.columnName;
    //         return {
    //           field: key,
    //           fieldId: item.fieldId,
    //           orderDirection: item?.config?.orderDirection,
    //         };
    //       }) || []
    //   );
    // });

    const data = ref([]);
    const total = ref(0);
    const paginationShow = computed(() => {
      return props.chartData.dataConfig?.page.show || false;
    });

    const optData = ref({});

    const s2 = ref(null);
    const widthByFieldValue = ref({});

    const handleSortClick = (fieldId, value) => {
      // console.log('key, value :>> ', fieldId, value)
      optData.value = {};
      if (fieldId === "close") {
        return;
      }

      if (
        props.sortField?.fieldId === fieldId &&
        props.sortField?.orderDirection === value
      ) {
        return;
      }

      const originFields = cloneDeep(props.chartData.dataConfig.columns).find(
        (i) => i.fieldId === fieldId
      );

      vm.emit("handleSortChange", {
        field: originFields.columnName,
        orderDirection: value,
        fieldId,
      });
    };

    // const SortAction = (props) => {
    //   const { meta, event } = props;
    //   // const operator = {
    //   //   // 配置 tooltip 中展示的内容
    //   //   menus: MENUS,
    //   // }
    //   optData.value = {
    //     x: event.clientX,
    //     y: event.clientY,
    //     meta,
    //   };
    // };

    // show
    const setTheme = (s2Ref) => {
      const {
        theme = {},
        content = {},
        header = {},
      } = props.chartData.iconConfig.options.style;
      // 颜色主题
      const { mainColor, basicColors } = theme;
      // 要加判断
      if (!mainColor) return;
      const palette = getPalette("colorful");

      // 使用参考色板 & 主题色值生成新色板
      const newPalette = generatePalette({
        ...palette,
        brandColor: mainColor,
      });

      if (basicColors) {
        basicColors[12] = basicColors[10];
        basicColors[11] = basicColors[10];
        Object.assign(newPalette, { basicColors });
      }

      const colCell = {
        bolderText: {
          ...header,
          textAlign: header.align,
        },
        cell: {},
      };

      const cornerCell = {
        cell: {},
      };
      const rowCell = {
        cell: {
          crossBackgroundColor: newPalette.basicColors[1],
          backgroundColor: newPalette.basicColors[8],
        },
      };

      const { align, horizon, vertical, ...contentRest } = content;

      const dataCell = {
        text: {
          ...contentRest,
          textAlign: align,
        },
        cell: {},
      };

      const borderCell = {};

      // 透明边框
      if (!horizon) {
        Object.assign(borderCell, {
          horizontalBorderColor: "#00000000",
        });
      }
      if (!vertical) {
        Object.assign(borderCell, {
          verticalBorderColor: "#00000000",
        });
      }
      let themeCell = [colCell, cornerCell, rowCell, dataCell];

      themeCell.forEach((item) => {
        Object.assign(item.cell, borderCell);
      });

      s2Ref.setThemeCfg({
        name: "colorful",
        palette: newPalette,
        theme: {
          colCell,
          cornerCell,
          rowCell,
          dataCell,
        },
      });
    };

    // const isShow = (key, orderDirection) => {
    //   return calcSortFields.value.find(
    //     (i) => i.fieldId === key && i.orderDirection == orderDirection
    //   );
    // };
    const debounceRender = throttle((w, h) => {
      s2.value?.changeSheetSize(w, h);
      s2.value?.render(false); // 不重新加载数据
    }, 200);

    const dealData = ({ dimensions, source, total: _total }) => {
      if (!vm.refs.wrapper) return;
      if (!Array.isArray(dimensions)) return;
      const { style } = props.chartData.iconConfig.options;
      total.value = _total || 0;
      data.value = source;

      // const fns = getFormat(props.chartData.dataConfig?.columns);

      const { dataConfig, eventConfig } = props.chartData;
      const { levels = [] } = dataConfig || {};
      const { linkage = [] } = eventConfig || {};

      let needLinkFields = levels.length
        ? linkage.concat(levels.slice(0, levels.length - 1))
        : linkage;

      let columns = [];
      let meta = dimensions.map((item) => ({
        field: item.fieldId,
        fieldId: item.fieldId,
        name: item.editorTitle || item.title || item.columnName,
        isSortCell: true,
        // formatter: (value) => {
        //   return (
        //     fns?.[item.fieldId]?.fn(value, fns[item.fieldId].data) || value
        //   );
        // },
      }));

      // let canSortKey = dimensions.map((item) => item.fieldId);

      const { show, group } = style.superTitle || {};
      if (show) {
        let extraMeta = [];
        group.forEach((item) => {
          if (item?.fieldId) {
            extraMeta.push({
              field: item.fieldId,
              name: item.name,
            });
          }
        });

        meta = meta.concat(extraMeta);

        columns = group.map((item) => {
          if (typeof item === "string") {
            return item;
          } else {
            return {
              key: item.fieldId,
              children: item.children,
            };
          }
        });
      } else {
        columns = meta.map((i) => i.field);
      }

      const linkFields = getLinkFields(needLinkFields);

      const getWidth = (id) => {
        const colWidth = style.colWidth;
        if (
          colWidth?.mode === "custom" &&
          colWidth?.config?.[id]?.auto === false
        ) {
          return colWidth.config[id]?.width || "auto";
        }

        return "auto";
      };

      const s2Options = {
        height: vm.refs.wrapper.offsetHeight,
        width: vm.refs.wrapper.offsetWidth,
        showSeriesNumber: !!style.showSeriesNumber,
        showDefaultHeaderActionIcon: false,
        style: {
          cellCfg: {
            height: 32,
          },
          colCfg: {
            width: (node) => {
              return getWidth(node.field);
            },
            widthByFieldValue: widthByFieldValue.value,
          },
        },
        tooltip: {
          showTooltip: true,
        },
        // 设置自定义 `icon` 的展示条件
        headerActionIcons: [
          // {
          //   iconNames: ["GroupAsc"],
          //   belongsCell: "colCell",
          //   displayCondition: (meta) => {
          //     return isShow(meta.key, "ascending");
          //   },
          //   action: SortAction,
          // },
          // {
          //   iconNames: ["GroupDesc"],
          //   belongsCell: "colCell",
          //   displayCondition: (meta) => {
          //     return isShow(meta.key, "descending");
          //   },
          //   action: SortAction,
          // },
          // {
          //   // 选择icon,可以是 S2 自带的，也可以是自定义的 icon
          //   iconNames: ["SortDown"],
          //   // 通过 belongsCell + displayCondition 设置 icon 的展示位置
          //   belongsCell: "colCell",
          //   displayCondition: (meta) => {
          //     return canSortKey.includes(meta.key);
          //   },
          //   // icon 点击之后的执行函数
          //   action: SortAction,
          // },
        ],
        interaction: {
          linkFields,
          overscrollBehavior: "none",
          // resize: {
          //   rowCellVertical: false,
          //   cornerCellHorizontal: false,
          //   colCellHorizontal: false,
          //   colCellVertical: false,
          // },
        },
        sortFieldIds: meta,
      };

      // s2.value?.destroy(vm.refs.wrapper)
      vm.refs.wrapper.innerHTML = "";
      s2.value = new TableSheet(
        vm.refs.wrapper,
        { fields: { columns }, meta, data: data.value },
        s2Options
      );
      // 滚动两个事件
      s2.value.on(S2Event.GLOBAL_SCROLL, ({ scrollY }) => {
        if (
          s2.value.facet.isScrollToBottom(scrollY) ||
          s2.value.facet.isScrollToTop(scrollY)
        ) {
          s2.value.setOptions({
            interaction: {
              overscrollBehavior: "auto",
            },
          });
        }
      });
      s2.value.on(S2Event.GLOBAL_HOVER, () => {
        s2.value.setOptions({
          interaction: {
            overscrollBehavior: "none",
          },
        });
      });
      s2.value.on(S2Event.DATA_CELL_CLICK, (event) => {
        let { fieldValue: value, colIndex } =
          event.target.attrs?.appendInfo?.cellData || {};

        // 有序号列的情况下, 减去序号列
        if (style.showSeriesNumber) {
          colIndex--;
        }

        const current = meta[colIndex];
        if (!current) return;
        vm.emit("handleChangeChartStatus", {
          key: "page",
          value: {
            ...props.chartStatus.page,
            pageNum: 1,
          },
          dontFetch: true,
        });
        // 仿照echarts的事件结构
        vm.emit("handleChartClick", {
          seriesName: current.fieldId,
          dimensionName: current.fieldId,
          triggerField: current,
          name: value,
          event: {
            event: {
              x: event.clientX,
              y: event.clientY,
            },
          },
        });
      });
      s2.value.on(S2Event.LAYOUT_AFTER_RENDER, () => {
        vm.emit("loaded");
      });
      s2.value.on(S2Event.LAYOUT_RESIZE_COL_WIDTH, (e) => {
        Object.assign(
          widthByFieldValue.value,
          e.style.colCfg.widthByFieldValue
        );
      });

      setTheme(s2.value);

      s2.value.render(true);
      nextTick(() => {
        vm.refs.wrapper.firstChild?.addEventListener("pointerdown", (e) =>
          e.stopPropagation()
        );
      });
    };
    const handleSizeChange = (current, val) => {
      vm.emit("handleChangeChartStatus", {
        key: "page",
        value: {
          pageSize: val,
          pageNum: 1,
        },
      });
    };

    const handleCurrentChange = (value) => {
      vm.emit("handleChangeChartStatus", {
        key: "page",
        value: {
          ...props.chartStatus.page,
          pageNum: value,
        },
      });
    };

    watch(
      () => {
        // 需要重新渲染可点击的字段
        return props.chartData;
      },
      () => {
        // 重置状态
        try {
          console.log("更新 table");
          props.chartData.dataResult &&
            dealData(cloneDeep(props.chartData.dataResult));
        } catch (error) {
          console.log("error :>> ", error);
          return;
        }
      },
      {
        deep: true,
      }
    );

    // watch(
    //   () => {
    //     return props.chartStatus.currentSort;
    //   },
    //   () => {
    //     try {
    //       const newData = pageSceneCom.value[props.id]?.dataResult;
    //       newData && dealData(cloneDeep(newData));
    //     } catch (error) {
    //       console.log("error :>> ", error);
    //       return;
    //     }
    //   }
    // );

    // watch(
    //   () => {
    //     return JSON.stringify(pageSceneCom.value[props.id]?.iconConfig.options);
    //   },
    //   (cur) => {
    //     try {
    //       const newData = pageSceneCom.value[props.id]?.dataResult;
    //       if (cur && JSON.parse(cur) && newData) {
    //         dealData(cloneDeep(newData));
    //       }
    //     } catch (error) {
    //       console.log("error :>> ", error);
    //       return;
    //     }
    //   }
    // );

    const resizeObserver = new ResizeObserver(([entry] = []) => {
      const { clientHeight, clientWidth } = entry.target || {};
      debounceRender(clientWidth, clientHeight);
    });

    onMounted(() => {
      if (!dataResult) {
        vm.emit("loaded");
      }
      dataResult && dealData(dataResult);
      resizeObserver.observe(vm.refs.wrapper);
    });

    onUnmounted(() => {
      resizeObserver.disconnect();
      s2.value.destroy();
      s2.value = null;
    });

    return {
      s2,
      data,
      total,
      paginationShow,
      options: props.chartData.iconConfig.options,
      handleSizeChange,
      handleCurrentChange,
      optData,
      handleSortClick,
      // locale: zhCN,
      // handleClick,
    };
  },
});
</script>
<style lang="less">
.tables2 {
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  // padding-bottom: 16px;
  position: relative;

  & > div:first-child {
    flex: 1;
    overflow: hidden;
    position: relative;
    & > canvas {
      position: absolute;
    }
  }

  &-footer {
    flex: 0;
    &-page {
      float: right;
      // filter: grayscale(1) contrast(999) invert(1) !important;
      // mix-blend-mode: difference;
      padding-top: 16px;
      padding-bottom: 0px;
      & .biAnt-pagination-item {
        & a {
          // filter: grayscale(1) !important;
        }
      }
      & .biAnt-pagination-item-active {
        background-color: transparent;
        & a {
          color: inherit;
        }
      }
      & .biAnt-pagination-prev,
      & .biAnt-pagination-next {
        // filter: grayscale(1) !important;
        & > a {
          color: inherit;
        }
      }
      & .biAnt-select-selection {
        background-color: transparent !important;
        border: 1px solid #000 !important;
      }
      & .biAnt-pagination-options-quick-jumper {
        input {
          background-color: transparent !important;
          border: 1px solid #000 !important;
        }
      }
    }
  }
}
</style>
