<template>
  <div class="history-table" v-if="loading">
    <BasicTable ref="historyTable" @register="registerTable" :data-source="dataSource">
      <template #bodyCell="{ column, record }">
        <a-tag v-if="column.dataIndex === 'warnFlag'" :color="record.warnFlag == '0' ? 'green' : 'red'">{{
          record.warnFlag == '0' ? '正常' : '报警'
        }}</a-tag>
        <a-tag v-if="column.dataIndex === 'netStatus'" :color="record.netStatus == '0' ? '#f00' : 'green'">{{
          record.netStatus == '0' ? '断开' : '连接'
        }}</a-tag>
        <slot name="filterCell" v-bind="{ column, record }"></slot>
      </template>

      <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 } 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';
  import { onMounted } from 'vue';
  import { safetyDeviceList } from './safety.api';

  const globalConfig = inject('globalConfig');
  const props = defineProps({
    columnsType: {
      type: String,
    },
    columns: {
      type: Array,
      // required: true,
      default: () => [],
    },
    deviceType: {
      type: String,
      required: true,
    },
    deviceListApi: {
      type: Function,
    },
    deviceArr: {
      type: Array,
      // required: true,
      default: () => [],
    },
    designScope: {
      type: String,
    },
    sysId: {
      type: String,
    },
    deviceId: {
      type: String,
    },
    scroll: {
      type: Object,
      default: { y: 0 },
    },
    formSchemas: {
      type: Array<FormSchema>,
      default: () => [],
    },
  });

  const getDeviceListApi = (params) => defHttp.post({ url: '/ventanaly-device/monitor/device', params });
  const historyTable = ref();
  const loading = ref(false);
  const stationType = ref('plc1');
  const dataSource = ref([]);
  const dataTypeName = ref('');
  const intervalMap = new Map([
    ['1', '1s'],
    ['2', '5s'],
    ['3', '10s'],
    ['4', '30s'],
    ['5', '1m'],
    ['6', '10m'],
    ['7', '30m'],
    ['8', '1h'],
  ]);

  const getExportXlsUrl = () => {
    if (stationType.value !== 'redis') {
      return '/safety/ventanalyMonitorData/exportXls';
    } else {
      return '/ventanaly-device/history/getHistoryData/exportXls';
    }
  };
  const emit = defineEmits(['change']);

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

  watch(
    () => {
      return props.columnsType;
    },
    async (newVal) => {
      if (!newVal) return;
      if (historyTable.value) getForm().resetFields();
      await getDeviceList();
      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');
      } else {
        columns.value = column;
      }
      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({ devicetype: props.deviceType, filterParams: { dataTypeName: dataTypeName.value }, pageSize: 10000 });
    if (res['records'] && res['records'].length > 0) {
      result = res['records'];
    } else if (res['msgTxt'] && res['msgTxt'][0] && res['msgTxt'][0]['datalist']) {
      result = res['msgTxt'][0]['datalist'];
    }

    if (result && result.length > 0) {
      deviceOptions.value = [];
      deviceOptions.value = result.map((item, index) => {
        return {
          label: item['strinstallpos'],
          value: item['id'] || item['deviceID'],
          strtype: item['strtype'] || item['deviceType'],
          strinstallpos: item['strinstallpos'],
          devicekind: item['devicekind'],
          stationtype: item['stationtype'],
        };
      });
      stationType.value = deviceOptions.value[0]['stationtype'];
    } else {
      deviceOptions.value = [];
      stationType.value = '';
    }
    await getForm().setFieldsValue({ gdeviceid: props.deviceId ? props.deviceId : deviceOptions.value[0] ? deviceOptions.value[0]['value'] : '' });
  }

  async function getDataSource() {
    dataSource.value = [];
    setLoading(true);
    const stationTypeStr = stationType.value;
    const formData = getForm().getFieldsValue();
    const pagination = getPaginationRef();
    formData['pageNo'] = pagination['current'];
    formData['pageSize'] = pagination['pageSize'];
    formData['column'] = 'createTime';
    if (stationTypeStr !== 'redis') {
      formData['strtype'] = deviceTypeStr.value
        ? deviceTypeStr.value
        : deviceOptions.value[0]['strtype']
        ? deviceOptions.value[0]['strtype']
        : props.deviceType + '*';
      if (props.sysId) {
        formData['sysId'] = props.sysId;
      }
      const result = await defHttp.get({ url: '/safety/ventanalyMonitorData/listdays', params: formData });
      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 = [];
      }
    } else {
      const params = {
        pageNum: pagination['current'],
        pageSize: pagination['pageSize'],
        column: pagination['createTime'],
        startTime: formData['ttime_begin'],
        endTime: formData['ttime_end'],
        deviceId: formData['gdeviceid'],
        strtype: props.deviceType + '*',
        sysId: props.sysId,
        interval: intervalMap.get(formData['skip']) ? intervalMap.get(formData['skip']) : '1h',
        isEmployee: props.deviceType.startsWith('vehicle') ? false : true,
      };
      const result = await defHttp.post({ url: '/ventanaly-device/history/getHistoryData', params: params });
      setPagination({ total: Math.abs(result['total']) || 0 });
      dataSource.value = result['records'] || [];
    }
    setLoading(false);
  }

  // 列表页面公共参数、方法
  const { tableContext, onExportXls } = useListPage({
    tableProps: {
      // api: list,
      columns: props.columnsType ? columns : (props.columns 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: [
          {
            field: 'ttime_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: 'ttime_end',
            label: '结束时间',
            component: 'DatePicker',
            defaultValue: dayjs(),
            required: true,
            componentProps: {
              showTime: true,
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              getPopupContainer: getAutoScrollContainer,
            },
            colProps: {
              span: 4,
            },
          },
          {
            label: '设备类型',
            field: 'dataTypeName',
            component: 'ApiSelect',
            componentProps: {
              api: safetyDeviceList.bind(null, { devicetype: 'safetymonitor', code: 'dataTypeName' }),
              labelField: 'name',
              valueField: 'code',
              onChange: async (e, option) => {
                console.log('1111', e, option);
                dataTypeName.value = e;
                await getDeviceList();
              },
            },
            colProps: {
              span: 4,
            },
          },
          {
            label: '查询设备',
            field: 'gdeviceid',
            component: 'Select',
            defaultValue: deviceOptions.value[0] ? deviceOptions.value[0]['value'] : '',
            required: true,
            componentProps: {
              showSearch: true,
              filterOption: (input: string, option: any) => {
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              },
              options: deviceOptions,
              onChange: (e, option) => {
                if (option && (option['strinstallpos'] || option['strtype'] || option['devicekind']))
                  historyType.value = option['strtype'] || option['devicekind'];
                if (option['strtype']) deviceTypeStr.value = option['strtype'];
                stationType.value = option['stationtype'];
                nextTick(async () => {
                  await getDataSource();
                });
              },
            },
            colProps: {
              span: 4,
            },
          },
          {
            label: '间隔时间',
            field: 'skip',
            component: 'Select',
            defaultValue: '8',
            componentProps: {
              options: [
                {
                  label: '1秒',
                  value: '1',
                },
                {
                  label: '5秒',
                  value: '2',
                },
                {
                  label: '10秒',
                  value: '3',
                },
                {
                  label: '30秒',
                  value: '4',
                },
                {
                  label: '1分钟',
                  value: '5',
                },
                {
                  label: '10分钟',
                  value: '6',
                },
                {
                  label: '30分钟',
                  value: '7',
                },
                {
                  label: '1小时',
                  value: '8',
                },
              ],
            },
            colProps: {
              span: 4,
            },
          },
        ],
      },
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: false,
      },
    },
    exportConfig: {
      name: '历史列表',
      url: getExportXlsUrl(),
    },
  });

  //注册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 (deviceOptions.value[0]) {
      stationType.value = deviceOptions.value[0]['stationtype'];
      historyType.value = deviceOptions.value[0]['strtype'] || deviceOptions.value[0]['devicekind'];
      nextTick(async () => {
        await getDataSource();
      });
    }

    watch([() => getPaginationRef()['current'], () => getPaginationRef()['pageSize']], async () => {
      if (deviceOptions.value[0]) {
        if (deviceOptions.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;
      }
    }
  }
  // :deep(.zxm-select-selector){
  //   height: 42px !important;
  // }
</style>
