<template>
  <div class="vent-table">
    <BasicTable ref="ventTableRef" @register="registerTable" :rowSelection="props.isShowSelect ? rowSelection : undefined">
      <template #tableTitle>
        <div></div>
      </template>
      <template #tableTop>
        <div></div>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'nwartype'">
          <!-- 除了 101（蓝色预警）其他都是红色字体 -->
          <span :class="{ 'color-#ff3823': ['102', '103', '104', '201', '1001'].includes(record.nwartype) }">
            {{ render.renderDictText(record.nwartype, 'leveltype') || '-' }}
          </span>
        </template>
        <slot name="filterCell" v-bind="{ column, record }"></slot>
      </template>
      <template #action="{ record }">
        <slot name="action" v-bind="{ record }"></slot>
      </template>
      <template #form-submitBefore>
        <slot name="submitBefore"></slot>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" setup>
  //ts语法
  import { defineExpose, toRaw, watch, ref, onMounted, onUnmounted, nextTick } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
  import { findIndex } from 'lodash-es';
  import { FormProps } from '/@/components/Form';
  import { render } from '/@/utils/common/renderUtils';

  const props = defineProps({
    columnsType: {
      type: String,
    },
    columns: {
      type: Array,
      // required: true,
      default: () => [],
    },
    dataSource: {
      type: Array,
      // default: () => [],
      required: true,
    },
    deviceType: {
      type: String,
    },
    designScope: {
      type: String,
    },
    isShowSelect: {
      type: Boolean,
      default: true,
    },
    isShowPagination: {
      type: Boolean,
      default: true,
    },
    isShowActionColumn: {
      type: Boolean,
      default: false,
    },
    scroll: {
      type: Object,
      default: { y: 0 },
    },
    title: {
      type: String,
    },
    size: {
      type: String,
      default: 'small',
    },
    formConfig: {
      type: Object as PropType<FormProps> | undefined,
      default: undefined,
    },
  });
  const emits = defineEmits(['selectRow']);
  const dataTableSource = ref<any[]>([]);
  // const loading = ref(true);

  const ventTableRef = ref();

  const tableMaxHeight = props.scroll.y ? props.scroll.y : 350;
  const columns = ref([]);
  const tableScroll = props.scroll.y ? ref({ y: props.scroll.y }) : ref({});
  //注册table数据
  // 列表页面公共参数、方法
  const { prefixCls, tableContext, doRequest } = useListPage({
    designScope: props.designScope,
    tableProps: {
      title: props.title,
      dataSource: dataTableSource,
      columns: props.columnsType ? columns : (props.columns as any[]),
      rowSelection: { type: props.isShowSelect ? 'radio' : undefined, columnWidth: 100 },
      size: props.size,
      useSearchForm: props.formConfig ? true : false,
      showTableSetting: false,
      showIndexColumn: true,
      showActionColumn: props.isShowActionColumn,
      minHeight: tableMaxHeight,
      bordered: false,
      scroll: tableScroll,
      rowKey: 'deviceID',
      formConfig: props.formConfig,
      // striped: true,
      loading: true,
      actionColumn: {
        width: 180,
      },
      pagination: props.isShowPagination
        ? {
            current: 1,
            pageSize: 50,
            pageSizeOptions: ['10', '30', '50', '100', '500'],
            showQuickJumper: false,
          }
        : false,
      beforeFetch: (params) => {
        if (props.deviceType?.startsWith('safetymonitor')) {
          return Object.assign(params, {
            filterParams: { dataTypeName: params['dataTypeName'], strinstallpos: '*' + params['strinstallpos'] + '*' },
          });
        } else if (props.deviceType?.startsWith('location')) {
          return Object.assign(params, {
            filterParams: { strinstallpos: '*' + params['strinstallpos'] + '*', userName: '*' + params['strname'] + '*', userJson: '' },
          });
        } else if (props.deviceType?.startsWith('vehicle')) {
          return Object.assign(params, {
            filterParams: { strinstallpos: '*' + params['strinstallpos'] + '*', vehicleName: '*' + params['strname'] + '*' },
          });
        } else {
          return Object.assign(params, { column: 'createTime' });
        }
      },
    },
  });
  const [registerTable, { reload, setLoading, setSelectedRowKeys, getSelectRowKeys, getForm, setPagination }, { rowSelection, selectedRowKeys }] =
    tableContext;

  watch(
    () => {
      return props.dataSource;
    },
    (newVal, oldVal) => {
      if (oldVal && newVal && oldVal.length < 1 && newVal.length > 0) {
        // 第一次
        if (getSelectRowKeys().length < 1) setSelectedRowKeys([newVal[0].deviceID]);
      }
      const list = <any[]>[];
      newVal.forEach((item) => {
        list.push(toRaw(item));
      });
      dataTableSource.value = list;
      nextTick(() => {
        setLoading(false);
      });
    },
    {
      immediate: true,
    }
  );
  watch(
    () => {
      return props.columnsType;
    },
    (newVal) => {
      console.log(newVal, 'val-----');
      if (!newVal) return;
      const column = getTableHeaderColumns(newVal.endsWith('_monitor') ? newVal : newVal + '_monitor');
      console.log('监测列表表头000------------>', newVal);
      if (column && column.length < 1) {
        const arr = newVal.split('_');
        const columnKey = arr.reduce((prev, cur, index) => {
          if (index !== arr.length - 2) {
            return prev + '_' + cur;
          } else {
            return prev;
          }
        });
        columns.value = getTableHeaderColumns(arr[0] + '_monitor');
      } else {
        columns.value = column;
      }
    },
    {
      immediate: true,
    }
  );

  watch(
    () => props.scroll.y,
    (newVal) => {
      if (newVal) {
        tableScroll.value = { y: newVal };
      } else {
        tableScroll.value = {};
      }
    }
  );

  watch(
    selectedRowKeys,
    (newKeys) => {
      console.log('设置的选中id---------->', newKeys, dataTableSource.value);
      const index = findIndex(dataTableSource.value, (data: any) => {
        return data.deviceID == selectedRowKeys.value[0];
      });
      if (index >= 0) emits('selectRow', dataTableSource.value[index], index);
    },
    { immediate: false }
  );

  function resetPagination() {
    if (ventTableRef.value) setPagination({ current: 1, pageSize: 50, total: 0 });
  }

  defineExpose({
    doRequest,
    setSelectedRowKeys,
    getSelectRowKeys,
    setLoading,
    reload,
    getForm,
    resetPagination,
  });

  onMounted(() => {
    // 如果是https
    // 反之是websocket
  });

  onUnmounted(() => {});
</script>

<style scoped lang="less">
  @ventSpace: zxm;

  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
    tr > td {
      background: #ffffff00 !important;
    }
    tr.@{ventSpace}-table-row-selected {
      td {
        background: #007cc415 !important;
      }
    }
  }
  :deep(.jeecg-basic-table .@{ventSpace}-table-wrapper .@{ventSpace}-table-title) {
    min-height: 0;
  }
  :deep(.@{ventSpace}-pagination) {
    margin-right: 20px !important;
  }
</style>
