<template>
  <div class="history-table">
    <BasicTable ref="historyTable" @register="registerTable">
      <template #bodyCell="{ column, record }">
        <slot name="filterCell" v-bind="{ column, record }"></slot>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="system-user" setup>
  //ts语法
  import { watchEffect, ref, watch, defineExpose } from 'vue';
  import { FormSchema } from '/@/components/Form/index';
  import { BasicTable } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
  import { warningHistoryList } from './alarm.api';
  import dayjs from 'dayjs';
  import { getAutoScrollContainer } from '/@/utils/common/compUtils';

  const historyTable = ref();

  const emit = defineEmits(['change']);
  const props = defineProps({
    columnsType: {
      type: String,
    },
    columns: {
      type: Array,
      // required: true,
      default: () => [],
    },
    deviceType: {
      type: String,
    },
    designScope: {
      type: String,
    },
    sysId: {
      type: String,
    },
    scroll: {
      type: Object,
      default: { y: 0 },
    },
    formSchemas: {
      type: Array<FormSchema>,
      default: () => [],
    },
  });
  const columns = ref([]);
  const tableScroll = props.scroll.y ? ref({ y: props.scroll.y - 100 }) : ref({});

  watch(
    () => {
      return props.columnsType;
    },
    (newVal) => {
      if (!newVal) return;
      const column = getTableHeaderColumns(newVal + '_history');
      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] + '_history');
      } else {
        columns.value = column;
      }
      if (historyTable.value) reload();
    },
    {
      immediate: true,
    }
  );

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

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    tableProps: {
      api: warningHistoryList,
      columns: props.columnsType ? columns : (props.columns as any[]),
      canResize: true,
      showTableSetting: false,
      showActionColumn: false,
      bordered: false,
      size: 'small',
      scroll: tableScroll,
      formConfig: {
        labelAlign: 'left',
        showAdvancedButton: false,
        // autoAdvancedCol: 2,

        baseColProps: {
          // offset: 0.5,
          xs: 24,
          sm: 24,
          md: 24,
          lg: 9,
          xl: 7,
          xxl: 4,
        },
        schemas:
          props.formSchemas.length > 0
            ? props.formSchemas
            : [
                // {
                //   label: '报警时间区间',
                //   field: 'tickectDate',
                //   component: 'TimeRangePicker',
                //   componentProps: {
                //     placeholder: ['报警开始时间', '报警结束时间'],
                //     valueFormat: 'YYYY-MM-DD HH:mm:ss',
                //   },
                // },
                {
                  field: 'starttime_begin',
                  label: '开始时间',
                  component: 'DatePicker',
                  defaultValue: dayjs().subtract(1, 'day'),
                  required: true,
                  labelWidth: 140,
                  componentProps: {
                    showTime: true,
                    valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    getPopupContainer: getAutoScrollContainer,
                  },
                },
                {
                  field: 'starttime_end',
                  label: '结束时间',
                  component: 'DatePicker',
                  required: true,
                  defaultValue: dayjs(),
                  labelWidth: 140,
                  componentProps: {
                    showTime: true,
                    valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    getPopupContainer: getAutoScrollContainer,
                  },
                },
              ],
        // fieldMapToTime: [['tickectDate', ['starttime_begin', 'starttime_end'], '']],
      },
      fetchSetting: {
        listField: 'records',
        pageField: 'pages',
        sizeField: 'size',
        totalField: 'total',
      },
      beforeFetch(params) {
        params.strtype = props.deviceType + '*';
        if (props.sysId) {
          params.sysId = props.sysId;
        }
        if (params['datalist.pages']) params['pages'] = params['datalist.pages'];
        if (params['datalist.size']) params['pageSize'] = params['datalist.size'];
      },
      afterFetch(resultItems) {
        resultItems.map((item) => {
          Object.assign(item, item['readData']);
        });
        return resultItems;
      },
    },
  });
  //注册table数据
  const [registerTable, { getDataSource, reload, setLoading }] = tableContext;

  watchEffect(() => {
    if (historyTable.value && getDataSource) {
      const data = getDataSource() || [];
      emit('change', data);
      console.log('[ data ] >', data);
    }
  });

  defineExpose({ setLoading });
</script>

<style scoped lang="less">
  @import '/@/design/vent/color.less';

  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
  }
  :deep(.zxm-picker) {
    height: 30px !important;
  }
  .history-table {
    width: 100%;
    :deep(.jeecg-basic-table-form-container) {
      .@{ventSpace}-form {
        padding: 0 !important;
        border: none !important;
        margin-bottom: 0 !important;
        .@{ventSpace}-picker,
        .@{ventSpace}-select-selector {
          width: 100% !important;
          height: 100%;
          background: #00000017;
          border: 1px solid #b7b7b7;
          input,
          .@{ventSpace}-select-selection-item,
          .@{ventSpace}-picker-suffix {
            color: #fff;
          }
          .@{ventSpace}-select-selection-placeholder {
            color: #ffffffaa;
          }
        }
      }
      .@{ventSpace}-table-title {
        min-height: 0 !important;
      }
    }
  }

  ::v-deep .zxm-table-content {
    overflow: hidden !important;
  }
</style>
