<template>
  <RenderTableColumn v-bind="column" />
</template>

<script setup lang="tsx" name="VxeTableColumn">
import { inject, ref, useSlots, getCurrentInstance } from "vue";
import { ColumnProps, RenderScope, HeaderRenderScope } from "../interface";
import { filterEnum, formatValue, handleProp, handleRowAccordingToProp } from "@/utils";
import { useI18n } from "vue-i18n";
import { isFunction } from "@/utils/is";
// import { Sort, SortUp, SortDown } from "@element-plus/icons-vue";

const props = withDefaults(defineProps<{ column: ColumnProps; editable?: boolean }>(), {
  column: () => ({} as ColumnProps),
  editable: false
});

const slots = useSlots();

const { t } = useI18n();

const enumMap = inject("enumMap", ref(new Map()));
const defaultSort = inject("defaultSort", ref<any>([]));

// 渲染表格数据
const renderCellData = (item: ColumnProps, scope: RenderScope<any>) => {
  return enumMap.value.get(item.field) && item.isFilterEnum
    ? filterEnum(handleRowAccordingToProp(scope.row, item.field!), enumMap.value.get(item.field)!, item.fieldNames)
    : formatValue(handleRowAccordingToProp(scope.row, item.field!, item?.format));
};

// 获取 tag 类型
const getTagType = (item: ColumnProps, scope: RenderScope<any>) => {
  return filterEnum(handleRowAccordingToProp(scope.row, item.field!), enumMap.value.get(item.field), item.fieldNames, "tag");
};

const RenderTableColumn: any = (item: ColumnProps) => {
  let enumData = enumMap.value.get(item.field) ?? [];
  // console.log("RenderTableColumn enumData :>> ", enumData, enumMap.value, item.field);

  // 排序图标
  let sortRender: any = null;
  if (defaultSort.value.length) {
    let _itmIdx = defaultSort.value.findIndex((itm: any) => itm.field == item.field);
    if (_itmIdx > -1) {
      // sortRender = <el-icon class="sort-icon">{defaultSort.value[_itmIdx].order == "asc" ? <SortUp /> : <SortDown />}</el-icon>;
      sortRender = (
        <i
          class={{
            iconfont: true,
            "sort-icon": true,
            "iconarrow-narrow-up": defaultSort.value[_itmIdx].order == "asc",
            "iconarrow-narrow-down": defaultSort.value[_itmIdx].order == "desc"
          }}
        ></i>
      );
    }
  }

  let _vxeCloumnSolt: any = {
    default: (scope: RenderScope<any>) => {
      // if (item?.editColRender && props.editable) {
      //   if (item.editColRender) return item.editColRender({ ...scope, enum: enumData, field: item.field });
      //   if (item.render) return item.render({ ...scope, enum: enumData, field: item.field });
      // }
      if (item.render) return item.render({ ...scope, enum: enumData, field: item.field });
      if (slots[handleProp(item.field!)]) return slots[handleProp(item.field!)]!(scope);
      if (item.tag) return <el-tag type={getTagType(item, scope)}>{renderCellData(item, scope)}</el-tag>;
      if (item?.type == "html") return <div v-html={renderCellData(item, scope)}></div>;
      return renderCellData(item, scope);
    },
    header: (scope: HeaderRenderScope<any>) => {
      if (item.headerRender) return [item.headerRender(scope), sortRender];
      if (slots[`${handleProp(item.field!)}Header`]) return [slots[`${handleProp(item.field!)}Header`]!(scope), sortRender];
      return [<span v-html={item.title}></span>, sortRender];
    }
  };

  // if (item?.editRender && !Object.keys(item.editRender).length) {
  if (item?.editColRender) {
    _vxeCloumnSolt.edit = (scope: RenderScope<any>) => {
      if (item.editColRender) return item.editColRender({ ...scope, enum: enumData, field: item.field });
      if (slots["edit_" + handleProp(item.field!)]) return slots["edit_" + handleProp(item.field!)]!(scope);
      if (item.tag) return <el-tag type={getTagType(item, scope)}>{renderCellData(item, scope)}</el-tag>;
      if (item?.type == "html") return <div v-html={renderCellData(item, scope)}></div>;
      return renderCellData(item, scope);
    };
  }

  return (
    <>
      {item.visible &&
        (item._children ? (
          !item?.parentHidden ? (
            <vxe-colgroup {...item} align={item.align ?? "center"} width={item.width}>
              {{
                default: () => {
                  if (item._children) return item._children.map(child => RenderTableColumn(child));
                },
                header: (scope: HeaderRenderScope<any>) => {
                  if (item.parentHidden) return "";
                  if (item.headerRender) return item.headerRender(scope);
                  if (slots[`${handleProp(item.field!)}Header`]) return slots[`${handleProp(item.field!)}Header`]!(scope);
                  return t(`table.${item.field}`);
                }
              }}
            </vxe-colgroup>
          ) : (
            item._children.map(child => RenderTableColumn(child))
          )
        ) : (
          <vxe-column {...item} align={item.align ?? "center"} header-class-name={sortRender ? "is-sorting" : ""}>
            {_vxeCloumnSolt}
          </vxe-column>
        ))}
    </>
  );
};
</script>

<style lang="scss">
.sort-icon {
  color: $color-primary-600;
}
.is-sorting,
.is--filter-active {
  background-color: $color-primary-000;
}
</style>
