<template>
  <customHeader
    :fieldNames="{ label: 'systemname', value: 'id', options: 'children' }"
    :options="options"
    :optionValue="optionValue"
    @change="changeSelectRow"
  >
    {{ mainTitle }}
  </customHeader>
  <slot :monitor-data="monitorData"></slot>
  <div class="scene-box">
    <div class="center-container">
      <template v-if="activeKey == 'monitor'">
        <slot name="monitor">
          <ModuleCommon
            v-for="cfg in mainConfig.configs"
            :key="cfg.deviceType"
            :show-style="cfg.showStyle"
            :module-data="cfg.moduleData"
            :module-name="cfg.moduleName"
            :device-type="cfg.deviceType"
            :data="monitorData"
            :visible="true"
          />
        </slot>
      </template>
      <div v-else class="history-group">
        <div v-if="showDeviceList && deviceList.length > 0" class="device-button-group">
          <div
            v-for="(device, index) in deviceList"
            :class="{ 'device-button': true, 'device-active': deviceActive == device.deviceType }"
            :key="index"
            @click="deviceChange(index)"
          >
            {{ device.deviceName }}
          </div>
        </div>
        <div class="history-container">
          <slot name="history" :device-type="deviceType" :device-id="optionValue">
            <HistoryTable
              v-if="activeKey == 'monitor_history'"
              class="vent-margin-t-20"
              :columns-type="deviceType"
              :device-type="deviceType"
              :sysId="optionValue"
              :scroll="{ y: 650 }"
              v-bind="monitorHistoryConfig"
            />
          </slot>
          <slot name="handler" :device-type="deviceType" :device-id="optionValue">
            <HandlerHistoryTable
              v-if="activeKey == 'handler_history'"
              class="vent-margin-t-20"
              columns-type="operator_history"
              :deviceType="deviceType"
              v-bind="handlerHistoryConfig"
            />
          </slot>
          <slot name="alarm" :device-type="deviceType" :device-id="optionValue">
            <AlarmHistoryTable
              v-if="activeKey == 'faultRecord'"
              columns-type="alarm"
              :device-type="deviceType"
              :sys-id="optionValue"
              v-bind="alarmHistoryConfig"
            />
          </slot>
        </div>
      </div>
    </div>
    <BottomMenu @change="changeActive" />
  </div>
</template>

<script setup lang="ts">
  import customHeader from '/@/components/vent/customHeader.vue';
  import { ref, onMounted, onUnmounted } from 'vue';
  import { getDevice, sysList } from '../comment/comment.api';
  import BottomMenu from '/@/views/vent/comment/components/bottomMenu.vue';
  import ModuleCommon from '../../home/configurable/components/ModuleCommon.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import { useRouter } from 'vue-router';
  import { Config } from '../../deviceManager/configurationTable/types';
  import { message } from 'ant-design-vue';
  import _ from 'lodash';

  type DeviceType = { deviceType: string; deviceName: string; datalist: any[] };

  const props = withDefaults(
    defineProps<{
      mainTitle: string;
      /** 是否显示历史数据上方的设备列表 */
      showDeviceList?: boolean;
      /** 请求场景数据传入的类型字符 */
      strtype: string;
      /** 请求场景数据传入的页面类型字符 */
      pagetype?: string;
      /** 获取各表格配置时依赖的设备类型 */
      // deviceType: string;
      /** 主要模块配置 */
      mainConfig: {
        configs: Config[];
        /** 获取该场景所含设备及其监测信息的API */
        monitorApi?: (params: { deviceType: string; deviceId: number | string }) => Promise<any>;
        /** 定时获取监测信息的配置，单位为毫秒，不传入即默认，传0即停用 */
        timer?: number;
      };
      /** 历史数据配置 */
      monitorHistoryConfig: {
        /** 请求历史数据时传入的类型字符 */
        columnsType?: string;
        /** 如果默认的设备类型不适用，可以传递固定的类型 */
        deviceType?: string;
        /** 仅展示已绑定设备，选择是则从系统中获取sysId下已绑定设备。仅能查询到已绑定设备的历史数据 */
        onlyBounedDevices?: boolean;
        /** 显示历史数据曲线图 */
        showHistoryCurve?: boolean;
      };
      /** 操作历史配置 */
      handlerHistoryConfig: {
        /** 请求操作历史时传入的类型字符 */
        columnsType?: string;
        /** 如果默认的设备类型不适用，可以传递固定的类型 */
        deviceType?: string;
        /** 获取操作历史的API，可以不提供以使用默认的请求 */
        deviceListApi?: (params: any) => Promise<any[]>;
      };
      /** 报警历史配置 */
      alarmHistoryConfig: {
        /** 请求报警历史时传入的类型字符 */
        columnsType?: string;
        /** 如果默认的设备类型不适用，可以传递固定的类型 */
        deviceType?: string;
        /** 获取报警历史的API，可以不提供以使用默认的请求 */
        list?: (params: any) => Promise<any[]>;
        /** 获取设备以供报警历史过滤的API，可以不提供以使用默认的请求 */
        deviceListApi?: (params: any) => Promise<any[]>;
      };
    }>(),
    {
      mainConfig: () => ({
        configs: [],
      }),
      monitorHistoryConfig: () => ({}),
      handlerHistoryConfig: () => ({}),
      alarmHistoryConfig: () => ({}),
      pagetype: 'normal',
      showDeviceList: true,
    }
  );

  const { currentRoute } = useRouter();

  const activeKey = ref('monitor');

  function changeActive(activeValue) {
    activeKey.value = activeValue;
  }

  const options = ref([]);
  const optionValue = ref('');

  /** 获取左上角场景选择框数据的方法，如果此时初始场景未赋值则选择首项做初始化 */
  async function getSysDataSource() {
    const res = await sysList({ strtype: props.strtype, pagetype: props.pagetype }).catch(() => {
      message.error('获取场景数据时发生了错误');
    });
    // 初始时选择第一条数据
    options.value = res.records || [];
    if (!optionValue.value) {
      changeSelectRow(options.value[0]['id']);
    }
  }

  // 切换检测数据
  function changeSelectRow(deviceID) {
    optionValue.value = deviceID;
    getDeviceList();
  }

  //关联设备
  const deviceList = ref<DeviceType[]>([]);
  const deviceActive = ref('');
  const deviceType = ref('');

  function deviceChange(index) {
    deviceType.value = deviceList.value[index]?.deviceType || '';
    deviceActive.value = deviceList.value[index]?.deviceType || '';
  }

  // 查询关联设备列表
  async function getDeviceList() {
    const { msgTxt = [] } = await getDevice({ devicetype: 'sys', systemID: optionValue.value }).catch(() => {
      message.error('获取已绑定设备时发生了错误');
    });

    deviceList.value = msgTxt.reduce((arr, item) => {
      const data = item.datalist.map((data: any) => {
        return Object.assign(data, data.readData);
      });
      // sys代表场景本身，应该过滤掉去处理该场景下的关联设备
      if (item.type != 'sys') {
        arr.unshift({
          deviceType: item.type,
          deviceName: item.typeName || item.datalist[0].typeName,
          datalist: data,
        });
      }

      return arr;
    }, []);
    if (!deviceActive.value) {
      deviceChange(0);
    }
  }

  let timer: NodeJS.Timeout;
  const monitorData = ref<any>({});
  /** 获取本场景下所绑定的设备，将监测数据赋值 */
  async function getMonitor() {
    if (props.mainConfig.monitorApi) {
      monitorData.value = await props.mainConfig
        .monitorApi({
          deviceType: deviceType.value,
          deviceId: optionValue.value,
        })
        .catch(() => {
          message.error('获取已绑定设备时发生了错误');
        });
    } else if (optionValue.value) {
      const { msgTxt = [] } = await getDevice({ devicetype: 'sys', systemID: optionValue.value }).catch(() => {
        message.error('获取已绑定设备时发生了错误');
      });
      const temp = {};
      msgTxt.forEach((item) => {
        _.set(temp, item.type, item.datalist);
      });
      monitorData.value = temp;
    }
  }

  onMounted(async () => {
    if (currentRoute.value && currentRoute.value['query'] && currentRoute.value['query']['id']) {
      optionValue.value = currentRoute.value['query']['id'] as string;
    }
    await getSysDataSource();
    if (props.mainConfig.timer !== 0) {
      timer = setInterval(() => {
        getMonitor();
      }, props.mainConfig.timer || 5000);
    } else {
      getMonitor();
    }
  });

  onUnmounted(() => {
    clearInterval(timer);
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  @ventSpace: zxm;
  .scene-box {
    margin-top: 40px;
    pointer-events: none;
    .history-group {
      margin-top: 80px;
      padding: 0 10px;
      .history-container {
        pointer-events: auto;
        background: #6195af1a;
        // width: 100%;
        border: 1px solid #00fffd22;
        padding: 10px 0;
        box-shadow: 0 0 20px #44b4ff33 inset;
      }
    }
    .device-button-group {
      // margin: 0 20px;
      padding: 0 10px;
      display: flex;
      pointer-events: auto;
      position: relative;
      &::after {
        position: absolute;
        content: '';
        width: 100%;
        height: 2px;
        top: 30px;
        left: -1px;
        border-bottom: 1px solid #0efcff;
      }
      .device-button {
        padding: 4px 15px;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;

        color: #fff;
        cursor: pointer;
        margin: 0 3px;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          border: 1px solid #6176af;
          transform: skewX(-38deg);
          background-color: rgba(0, 77, 103, 85%);
          z-index: -1;
        }
      }
      .device-active {
        // color: #0efcff;
        &::before {
          border-color: #0efcff;
          box-shadow: 1px 1px 3px 1px #0efcff inset;
        }
      }
    }
  }
  .center-container {
    width: 100%;
    height: calc(100% - 150px);
  }

  .input-box {
    display: flex;
    align-items: center;
    padding-left: 10px;

    .input-title {
      color: #73e8fe;
      width: auto;
    }

    .@{ventSpace}-input-number {
      border-color: #ffffff88 !important;
    }

    margin-right: 10px;
  }
</style>
