<template>
  <div class="history-table" v-if="loading">
    <BasicTable ref="historyTable" @register="registerTable" :data-source="dataSource">
      <template #form-submitBefore>
        <a-button type="primary" preIcon="ant-design:search-outlined" @click="getDataSource">查询</a-button>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" setup>
//ts语法
import { watchEffect, ref, watch, defineExpose, inject, nextTick, onMounted, computed } 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 { defHttp } from '/@/utils/http/axios';
import dayjs from 'dayjs';
import { getAutoScrollContainer } from '/@/utils/common/compUtils';

const props = defineProps({
  columnsType: {
    type: String,
  },
  columns: {
    type: Array,
    // required: true,
    default: () => [],
  },
  historyColumns: {
    type: Array,
    default: () => [],
  },
  id: {
    type: String,
  },
  scroll: {
    type: Object,
    default: { y: 0 },
  },
  formSchemas: {
    type: Array<FormSchema>,
    default: () => [],
  },
});
//获取分站数据
const getDeviceListApi = (params) => defHttp.get({ url: '/safety/ventanalySubStation/alllist', params });
const historyTable = ref();
const loading = ref(false);
const dataSource = ref([]);

const emit = defineEmits(['change']);

const historyType = ref('');
const deviceKide = ref('');
const columns = ref([]);
const deviceList = ref([]);
const tableScroll = props.scroll.y ? ref({ y: props.scroll.y - 100 }) : ref({});
// let deviceList = ref([]);
const deviceTypeStr = ref('');
loading.value = true;

watch(
  () => {
    return props.columnsType;
  },
  async (newVal) => {
    debugger;
    if (!newVal) return;
    deviceKide.value = newVal;
    if (historyTable.value) {
      getForm().resetFields();
      // getForm().updateSchema();
      // getForm();
    }
    dataSource.value = [];
    // const column = getTableHeaderColumns(newVal.includes('_history') ? newVal : newVal + '_history');
    // if (column && column.length < 1) {
    //   const arr = newVal.split('_');
    //   console.log('历史记录列表表头------------>', arr[0] + '_monitor');
    //   columns.value = getTableHeaderColumns(arr[0] + '_history');
    //   if (columns.value.length < 1) {
    //     if (historyType.value) {
    //       columns.value = getTableHeaderColumns(historyType.value + '_history');
    //     }
    //   }
    // } else {
    //   columns.value = column;
    // }
    await getDeviceList();
    nextTick(() => {
      getDataSource();
    });

    if (historyTable.value) reload();
  },
  {
    immediate: true,
  }
);

// watch(historyType, (type) => {
//   if (!type) return;
//   // if (historyTable.value) getForm().resetFields()
//   const column = getTableHeaderColumns(type.includes('_history') ? type : type + '_history');
//   if (column && column.length < 1) {
//     // const arr = type.split('_');
//     // columns.value = getTableHeaderColumns(arr[0] + '_history');
//   } else {
//     // columns.value = column;
//   }
//   setColumns(columns.value);
// });

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

watch(
  () => props.deviceId,
  async () => {
    await getForm().setFieldsValue({});
    await getDeviceList();
  }
);

async function getDeviceList() {
  let result;
  const res = await getDeviceListApi({ column: 'createTime', pageNo: 1, pageSize: 10000 });
  console.log(res, 'ssssssssssssssssssssss');
  result = res.result;
  deviceList.value = result;
}

function resetFormParam() {
  const formData = getForm().getFieldsValue();
  const pagination = getPaginationRef();
  formData['pageNo'] = pagination['current'];
  formData['pageSize'] = pagination['pageSize'];
  formData['column'] = 'createTime';
  const params = {
    pageNum: pagination['current'],
    pageSize: pagination['pageSize'],
    column: pagination['createTime'],
    starttime_begin: formData['starttime_begin'],
    starttime_endtime: formData['starttime_endtime'],
    nsubstationid: formData['gdeviceid'],
    nwartype: 1001,
  };
  return params;
}

async function getDataSource() {
  dataSource.value = [];
  setLoading(true);
  const params = await resetFormParam();
  const result = await defHttp.get({ url: '/safety/ventanalyAlarmLog/list', params: params });
  setPagination({ total: Math.abs(result['datalist']['total']) || 0 });
  if (result['datalist']['records'].length > 0) {
    dataSource.value = result['datalist']['records'].map((item: any) => {
      return Object.assign(item, item['readData']);
    });
  } else {
    dataSource.value = [];
  }

  setLoading(false);
}

// 列表页面公共参数、方法
const { tableContext } = useListPage({
  tableProps: {
    // api: list,
    columns: props.historyColumns ? columns : (props.historyColumns as any[]),
    canResize: true,
    showTableSetting: false,
    showActionColumn: false,
    bordered: false,
    size: 'small',
    scroll: tableScroll,
    showIndexColumn: true,
    tableLayout: 'auto',
    formConfig: {
      labelAlign: 'left',
      showAdvancedButton: false,
      showSubmitButton: false,
      showResetButton: false,
      baseColProps: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 9,
        xl: 7,
        xxl: 4,
      },
      schemas:
        props.formSchemas.length > 0
          ? props.formSchemas
          : [
              {
                field: 'starttime_begin',
                label: '开始时间',
                component: 'DatePicker',
                defaultValue: dayjs().startOf('date'),
                required: true,
                componentProps: {
                  showTime: true,
                  valueFormat: 'YYYY-MM-DD HH:mm:ss',
                  getPopupContainer: getAutoScrollContainer,
                },
                colProps: {
                  span: 4,
                },
              },
              {
                field: 'starttime_endtime',
                label: '结束时间',
                component: 'DatePicker',
                defaultValue: dayjs(),
                required: true,
                componentProps: {
                  showTime: true,
                  valueFormat: 'YYYY-MM-DD HH:mm:ss',
                  getPopupContainer: getAutoScrollContainer,
                },
                colProps: {
                  span: 4,
                },
              },
              {
                label: '查询设备',
                field: 'nsubstationid',
                component: 'Select',
                defaultValue: props.id ? props.id : deviceList.value[0] ? deviceList.value[0]['strinstallpos'] : '',
                required: true,
                componentProps: {
                  showSearch: true,
                  filterOption: (input: string, option: any) => {
                    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  },
                  options: deviceList,
                  onChange: (e, option) => {
                    if (option && (option['strinstallpos'] || option['id'])) historyType.value = option['strinstallpos'] || option['id'];
                  },
                },
                colProps: {
                  span: 4,
                },
              },
              {
                field: 'nwartype',
                required: true,
                componentProps: {
                  valueFormat: '1001',
                },
                colProps: {
                  span: 4,
                },
              },
            ],
    },
    // fetchSetting: {
    pagination: {
      current: 1,
      pageSize: 10,
      pageSizeOptions: ['10', '30', '50', '100'],
      showQuickJumper: false,
    },
    beforeFetch() {
      const newParams = { ...resetFormParam() };
      debugger;
      return newParams;
    },
  },
});

//注册table数据
const [registerTable, { reload, setLoading, getForm, setColumns, getPaginationRef, setPagination }] = tableContext;

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

onMounted(async () => {
  await getDeviceList();
  if (deviceList.value[0]) {
    historyType.value = deviceList.value[0]['strinstallpos'] || deviceList.value[0]['id'];
    nextTick(async () => {
      await getDataSource();
    });
  }
  // watch([() => getPaginationRef()['current'], () => getPaginationRef()['pageSize']], async () => {
  //   if (deviceList.value[0]) {
  //     if (deviceList.value[0]) {
  //       await getDataSource();
  //     }
  //   }
  // });
});
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;
    }
  }
  .pagination-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .page-num {
      border: 1px solid #0090d8;
      padding: 4px 8px;
      margin-right: 5px;
      color: #0090d8;
    }
    .btn {
      margin-right: 10px;
    }
  }
}
</style>
