<template>
  <div class="history-table" v-if="loading">
    <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, inject } 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';

  const globalConfig = inject('globalConfig');
  
  const historyTable = ref();
  const dataSource = ref([])
  const loading = ref(false)
  const list = (params) => {
    if(globalConfig.History_Type == 'vent') {
      return defHttp.get({ url: '/safety/ventanalyMonitorData/list', params })
    } else {
      return defHttp.post({ url: '/ventanaly-device/history/getHistoryData', params })
    }
  };
  const emit = defineEmits(['change']);
  const props = defineProps({
    columnsType: {
      type: String,
    },
    columns: {
      type: Array,
      // required: true,
      default: () => [],
    },
    deviceType: {
      type: String,
      required: true,
    },
    deviceListApi: {
      type: Function,
    },
    designScope: {
      type: String,
    },
    sysId: {
      type: String,
    },
    scroll: {
      type: Object,
      default: { y: 0 }
    },
    formSchemas: {
      type: Array<FormSchema>,
      default: () => []
    }
  });
  const historyType = ref('')
  const columns = ref([])
  const tableScroll = props.scroll.y ? ref({ y: props.scroll.y - 100 }) : ref({})
  let deviceOptions = <any[]>[]
  let deviceList = <any[]>[]

  watch(
    () => {
      return props.columnsType;
    },
    (newVal) => {
      if (!newVal) return
      if(historyTable.value) getForm().resetFields()
      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) => {
    debugger
    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 = {}
    }
  })

  async function getDeviceList() {
    let result;
    if(globalConfig.History_Type == 'vent'){
      result = await defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType } })
    }else {
      result = await defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType.startsWith('vehicle') ? 'location_normal' : props.deviceType } })
    }
    if(result){
      deviceOptions = []
      deviceOptions = result.map((item) => {
        return {label: item['strname'], value: item['id'], strtype: item['strtype'], devicekind: item['devicekind'] }
        // return { label: item['strname'], value: item['id']}
      })
      
    }
  }
  
  await getDeviceList()
  loading.value = true
  // 列表页面公共参数、方法
  const { tableContext } = useListPage(
    globalConfig.History_Type == 'vent' ? {
      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,
        formConfig: {
          labelAlign: 'left',
          showAdvancedButton: false,
          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: 'tData',
              component: 'DatePicker',
              defaultValue: dayjs(),
              colProps: {
                span: 4,
              },
              componentProps: {
                valueFormat: 'YYYY-MM-DD',
              },
            },
            {
              label: '时间区间',
              field: 'tickectDate',
              component: 'TimeRangePicker',
              componentProps: {
                placeholder: ['开始时间', '结束时间'],
                valueFormat: 'HH:mm:ss',
              },
              colProps: {
                span: 4,
              },
            },
            {
              label: '查询设备',
              field: 'gdeviceid',
              component: 'Select',
              defaultValue: deviceOptions[0] ?  deviceOptions[0]['value'] : '',
              required: true,
              // componentProps: ({ formModel }) => {
              //   return {
              //     options: deviceOptions.value,
              //     // api: () => defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType } }),
              //     // resultField: 'result',
              //     // labelField: 'strinstallpos',
              //     // valueField: 'id',
              //     // onChange: (e, option) => {
              //     //   if (option && (option['strtype'] || option['devicekind'])) historyType.value = option['strtype'] || option['devicekind']
              //     // },
              //   }
              // },
              componentProps: {
                options: deviceOptions,
                // api: () => defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType } }),
                // // resultField: 'result',
                // labelField: 'strinstallpos',
                // valueField: 'id',
                onChange: (e, option) => {
                  debugger
                  if (option && (option['strtype'] || option['devicekind'])) historyType.value = option['strtype'] || option['devicekind']
                },
              },
              colProps: {
                span: 4,
              },
            },
            {
              label: '间隔时间',
              field: 'skip',
              component: 'Select',
              componentProps: {
                options: [
                  {
                    label: '5秒',
                    value: '1',
                  },
                  {
                    label: '10秒',
                    value: '2',
                  },
                  {
                    label: '1分钟',
                    value: '3',
                  },
                  {
                    label: '5分钟',
                    value: '4',
                  },
                  {
                    label: '10分钟',
                    value: '5',
                  },
                ],
              },
              colProps: {
                span: 4,
              },
            },
          ],
          fieldMapToTime: [['tickectDate', ['ttime_begin', 'ttime_end'], '']],
        },
        fetchSetting: {
          listField:  'datalist',
          totalField: 'datalist.total',
        },
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '30', '50', '100'],
          showQuickJumper: false
        },
        beforeFetch(params) {
          params.strtype = props.deviceType + '*';
          if(props.sysId){
            params.sysId = props.sysId;
          }
        },
        afterFetch(result) {
          const resultItems = result['records']
          resultItems.map((item) => {
            Object.assign(item, item['readData']);
          });
          console.log('result---------------->', result)
          return resultItems;
        },
      },
    }: {
      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,
      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 : [
          {
            field: 'startTime',
            label: '开始时间',
            component: 'DatePicker',
            required: true,
            componentProps: {
              showTime: true,
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              getPopupContainer: getAutoScrollContainer,
            },
          },
          {
            field: 'endTime',
            label: '结束时间',
            component: 'DatePicker',
            required: true,
            componentProps: {
              showTime: true,
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              getPopupContainer: getAutoScrollContainer,
            },
          },
          {
            label: '查询设备',
            field: 'deviceId',
            component: 'Select',
            defaultValue: deviceOptions[0] ? deviceOptions[0]['value'] : '',
            required: true,
            componentProps: {
              options: deviceOptions,
              // api: () => defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType.startsWith('vehicle') ? 'location_normal' : props.deviceType } }),
              // // resultField: 'result',
              // labelField: 'strinstallpos',
              // valueField: 'id',
              // numberToString: true,
              onChange: (e, option) => {
                if(option && (option['strtype'] || option['devicekind'])) historyType.value = option['strtype'] || option['devicekind']
              },
            },
            // componentProps: ({ formModel }) => {
            //   return {
            //     options: deviceOptions.value,
            //     // api: () => defHttp.get({ url: '/safety/ventanalyManageSystem/linkdevicelist', params: { sysId: props.sysId, deviceType: props.deviceType.startsWith('vehicle') ? 'location_normal' : props.deviceType } }),
            //     // resultField: 'result',
            //     // labelField: 'strinstallpos',
            //     // valueField: 'id',
            //     // onChange: (e, option) => {
            //     //   if(option && (option['strtype'] || option['devicekind'])) historyType.value = option['strtype'] || option['devicekind']
            //     // },
            //   }
            // },
          },
          {
            label: '间隔时间',
            field: 'interval',
            component: 'Select',
            defaultValue: '30s',
            componentProps: {
              options: [
                {
                  label: '1秒',
                  value: '1s',
                },
                {
                  label: '5秒',
                  value: '5s',
                },
                {
                  label: '10秒',
                  value: '10s',
                },
                {
                  label: '30秒',
                  value: '30s',
                },
                {
                  label: '1分钟',
                  value: '1m',
                },
                {
                  label: '10分钟',
                  value: '10m',
                },
                {
                  label: '30分钟',
                  value: '30m',
                },
                {
                  label: '1小时',
                  value: '1h',
                },
              ],
            },
          },
        ],
      },
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: false
      },
      // pagination: false,
      fetchSetting: {
        totalField: 'total',
         // 每页显示多少条
        sizeField: 'pageSize',
        // 请求结果列表字段  支持 a.b.c
        pageField: 'pageNo'
      },
      beforeFetch(params) {
        params.strtype = props.deviceType + '*';
        if (props.sysId) {
          params.sysId = props.sysId;
        }
        if(params.interval){
          params.interval = params.interval
        }else{
          params.interval = '1m'
        }
        if (props.deviceType.startsWith('vehicle')) {
          params['isEmployee'] = false
        } else if (props.deviceType.startsWith('location')) {
          params['isEmployee'] = true
        }
      },
      afterFetch(result) {
        return result;
      },
    },
    } 
  );

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

  watchEffect(() => {
    if (historyTable.value && getDataSource) {
      const data = getDataSource() || [];
      emit('change', data);
      console.log('[ data ] >', data);
    }
  });
  onMounted(() => {
    if (!props.columnsType) {
      historyType.value = deviceOptions[0]['strtype'] || deviceOptions[0]['devicekind']
    }
  })
  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>
