<template>
  <BasicTable @register="registerTable">
    <template #bodyCell="{ column, record }">
      <div>{{ record[column.dataIndex] }}</div>
      <div class="resize-handle" v-if="rowResize"></div>
    </template>
  </BasicTable>
</template>
<script lang="ts" setup>
  import { inject, watchEffect, watch, onMounted, ref } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { getDicDetailList } from '/@/api/system/dic';
  import { apiConfigFunc, camelCaseString, isValidJSON } from '/@/utils/event/design';
  import { cloneDeep } from 'lodash-es';

  const props = defineProps({
    preloadType: String,
    apiConfig: Object,
    itemId: String,
    isPagination: Boolean,
    showIndex: Boolean,
    showFormBorder: Boolean,
    multiple: Boolean,
    value: String,
    rowSpan: String,
    widths: Array, //表格列宽配置
    rowResize: Boolean,
  });
  const emit = defineEmits(['change', 'update:value', 'colums']);
  const formModel = inject<any>('formModel', null);
  const isCamelCase = inject<boolean>('isCamelCase', false);
  let dataSource = ref<any[]>([]);
  let columns = ref<any[]>([]);
  let dataKeys = ref<string[]>([]);
  watchEffect(async () => {
    if (props.preloadType === 'api' && props.apiConfig?.apiParams) {
      props.apiConfig.apiParams.forEach((params) => {
        params.tableInfo?.forEach((o) => {
          if (o.bindType == 'data') {
            let val = isValidJSON(o.value);
            let field = '';
            if (val && val.bindField) {
              field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
              formModel && formModel[field];
            }
          }
        });
      });
    }

    let rowKey = 'key';
    if (props.preloadType === 'dic') {
      if (props.itemId) dataSource.value = await getDicDetailList({ itemId: props.itemId! });
    } else if (props.preloadType === 'api') {
      dataSource.value = await apiConfigFunc(props.apiConfig, isCamelCase, formModel);
    }
    if (dataSource.value?.length) {
      dataKeys.value = Object.keys(dataSource.value[0]);
      emit('colums', dataKeys.value);
      if (dataKeys.value.includes('id')) rowKey = 'id';
      setCustomColumns(dataKeys.value);
    }
    handleRowSpan();
    setProps({
      dataSource: dataSource.value,
      columns: columns.value,
      rowKey,
      pagination: props.isPagination,
      showIndexColumn: props.showIndex,
      bordered: props.showFormBorder,
      rowResize: props.rowResize,
      afterFetch: () => {
        //搜索完成后 将选中项重新赋值给SelectedRowKeys
        if (props.value) setSelectedRowKeys(props.value.split(','));
      },
      rowSelection: {
        type: props.multiple ? 'checkbox' : 'radio',
        onChange: onSelectChange,
      },
    });
  });
  watch(
    () => props.multiple,
    () => {
      setProps({
        rowSelection: {
          type: props.multiple ? 'checkbox' : 'radio',
          onChange: onSelectChange,
        },
      });
    },
  );
  watch(
    () => props.value,
    (val) => {
      if (val) setSelectedRowKeys(val.split(','));
    },
  );
  watch(
    () => props.rowSpan,
    () => {
      handleRowSpan();
    },
  );
  watch(
    () => props.widths,
    () => {
      setCustomColumns(dataKeys.value);
      setColumns(columns.value);
    },
    {
      deep: true,
    },
  );
  onMounted(() => {
    if (props.value) setSelectedRowKeys(props.value.split(','));
  });
  function onSelectChange(rowKeys: string[], selectedRows) {
    emit('update:value', rowKeys.join(','));
    emit('change', selectedRows);
  }
  function handleRowSpan() {
    if (dataSource.value?.length) {
      if (props.rowSpan) {
        let colName: string = !isCamelCase ? props.rowSpan : camelCaseString(props.rowSpan) || '';
        let curI = 0;
        let cur = dataSource.value[curI][colName];
        let arr: number[] = [];
        dataSource.value.forEach((o, i) => {
          arr.push(1);
          if (i >= 1) {
            if (o[colName] == cur) {
              arr[curI] += 1;
              arr[i] = 0;
            } else {
              curI = i;
              cur = dataSource.value[curI][colName];
            }
          }
        });
        let cols = cloneDeep(columns.value);
        cols.forEach((item) => {
          if (item.dataIndex == colName) {
            item.customCell = (_, index) => {
              let obj = { rowSpan: 1 };
              arr.forEach((o, i) => {
                if (index == i) {
                  obj = { rowSpan: o };
                }
              });
              return obj;
            };
          }
        });
        columns.value = cols;
        setColumns(cols);
      } else {
        setColumns(columns.value);
      }
    }
  }
  function setCustomColumns(dataKeys) {
    columns.value = dataKeys.map((item) => {
      let params: any = {};
      let obj: any = props.widths?.find((k: any) => k.key == item);
      if (obj) {
        let width = obj.resizable
          ? obj.width
          : obj.unit && obj.width
          ? obj.width + obj.unit
          : obj.width;
        if (width === 0 || width) params.width = width;
        if (obj.minWidth === 0 || obj.minWidth) params.minWidth = obj.minWidth;
        if (obj.maxWidth === 0 || obj.maxWidth) params.maxWidth = obj.maxWidth;
        params.resizable = obj.resizable;
      }
      return {
        title: item,
        dataIndex: item,
        ...params,
      };
    });
  }
  const [registerTable, { setProps, setSelectedRowKeys, setColumns }] = useTable({
    striped: false,
    size: 'middle',
  });
</script>
