<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <div class="parent-container">
    <div class="ns-tree-title">
      <span>数据点位</span>
    </div>
    <a-select
      ref="select"
      v-model:value="selectedValue"
      placeholder="请选择能耗类型"
      style="width: 100%; margin-bottom: 10px"
      :options="options1"
      @change="changeEnergyType" />
    <a-radio-group
      v-model:value="mode"
      @change="changeMode"
      style="padding-bottom: 10px; width: 100%">
      <a-radio-button value="1" style="width: 50%; text-align: center" :disabled="shebei"
        >设备</a-radio-button
      >
      <a-radio-button value="2" style="width: 50%; text-align: center">节点</a-radio-button>
    </a-radio-group>
    <a-input
      v-model:value="deviceName"
      placeholder="请输入设备名称"
      v-if="mode == '1'"
      @change="changeMode" />
    <a-input v-model:value="pointName" placeholder="请输入节点名称" v-else @change="changeMode" />
    <a-spin :spinning="treeLoading">
      <a-tree
        v-model:expandedKeys="expandedKeys"
        v-model:selectedKeys="selectedKeys"
        v-model:checkedKeys="checkedKeys"
        checkable
        :height="300"
        style="width: 100%; overflow-y: auto; margin-bottom: 10px; margin-top: 10px"
        :tree-data="treeData2" />
    </a-spin>

    <div class="fixed-bottom">
      <a-divider />
      <a-select
        v-model:value="frequencyValue"
        placeholder="请选择采集频率"
        style="width: 100%; margin-bottom: 10px"
        :options="options2" />
      <a-range-picker
        :value="hackValue || dateRange"
        :disabled-date="disabledDate"
        @change="onChange"
        @openChange="onOpenChange"
        @calendarChange="onCalendarChange"
        style="width: 100%; margin-bottom: 10px"
        :placeholder="['请选择日期', '请选择日期']" />
      <a-button type="primary" style="width: 100%; margin-bottom: 10px" @click="getSelect">
        查询
      </a-button>
      <!-- <a-button type="primary" style="width: 100%; margin-bottom: 10px" @click="getSelect11">
        模拟不同数据查询
      </a-button> -->
    </div>
  </div>
</template>

<script lang="ts">
  import type { TreeSelectProps, SelectProps } from 'ant-design-vue';
  import { defineComponent, ref, onMounted, inject } from 'vue';
  import { Dayjs } from 'dayjs';
  import { http } from '/nerv-lib/util';
  import { device, group } from '/@/api/deviceManage';
  import { dict } from '/@/api';

  export default defineComponent({
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'Tree',
    setup() {
      const value = ref<string>();
      const deviceName = ref<string>();
      const pointName = ref<string>();
      const treeLoading = ref(false);
      const shebei = ref(false);

      // 树打开节点
      const expandedKeys = ref<string[]>([]);
      // 树勾选节点
      const selectedKeys = ref<string[]>([]);
      // 树点击节点
      const checkedKeys = ref<string[]>([]);

      // 能耗类型list
      const options1 = ref<SelectProps['options']>([]);
      // 采集频率list
      const options2 = ref<SelectProps['options']>([]);
      const mode = ref<String>('1');
      // 能耗类型
      const selectedValue = ref<string | undefined>();
      // 采集频率
      const frequencyValue = ref<string | undefined>();
      // 时间
      const dateRange = ref<[Dayjs, Dayjs] | undefined>();

      // 页面初始化参数
      const getOptionsList = async () => {
        try {
          const options = await dict({ params: { dicKey: 'ENERGY_TYPE' } });
          options.data.data.forEach((item: any) => {
            (item.value = item.cnValue), (item.label = item.cnValue);
          });
          options1.value = options.data.data; // 根据返回数据的结构来更新 options1.value
        } catch (error) {
          console.error('Failed to fetch options:', error);
        }
        options2.value = [
          {
            value: '1',
            label: '5分钟',
          },
          {
            value: '2',
            label: '10分钟',
          },
          {
            value: '3',
            label: '30分钟',
          },
          {
            value: '4',
            label: '1小时',
          },
        ];
      };
      interface PageData {
        graphTableList: any[];
        graphTableColumns: any[];
        graphGraphList: any[];
      }
      const pageData = inject<PageData>('pageData');
      if (!pageData) {
        throw new Error('pageData is not provided');
      }

      // 选择能耗类型
      const changeEnergyType = () => {
        if (selectedValue.value == '8') {
          shebei.value = true;
          mode.value = '2';
        } else {
          shebei.value = false;
        }
        changeMode();
      };
      const getSelect = () => {
        pageData.graphTableList = [
          {
            key: '1',
            name: 'AC_002（暖通电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
          },
          {
            key: '1',
            name: 'AC_002（暖通电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
          },
          {
            key: '2',
            name: 'AC_003（照明电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
          },
          {
            key: '2',
            name: 'AC_003（照明电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
          },
          {
            key: '3',
            name: 'AC_004（给排水电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
          },
        ];
        pageData.graphTableColumns = [
          {
            title: '日期',
            dataIndex: 'date',
          },
          {
            title: '1:00',
            dataIndex: '1:00',
          },
        ];
        pageData.graphGraphList = [
          {
            date: '2023-12-01 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '21',
              },
              {
                name: 'AC_003（照明电表）',
                value: '36',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '5',
              },
            ],
          },
          {
            date: '2023-12-02 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '26',
              },
              {
                name: 'AC_003（照明电表）',
                value: '25',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '47',
              },
            ],
          },
          {
            date: '2023-12-03 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '18',
              },
              {
                name: 'AC_003（照明电表）',
                value: '22',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '26',
              },
            ],
          },
          {
            date: '2023-12-04 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '40',
              },
              {
                name: 'AC_003（照明电表）',
                value: '15',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '12',
              },
            ],
          },
          {
            date: '2023-12-05 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '15',
              },
              {
                name: 'AC_003（照明电表）',
                value: '18',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '15',
              },
            ],
          },
        ];
      };
      const getSelect11 = () => {
        pageData.graphTableList = [
          {
            key: '1',
            name: 'AC_002（暖通电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
            '2:00': '3626',
          },
          {
            key: '1',
            name: 'AC_002（暖通电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
            '2:00': '3626',
          },
          {
            key: '2',
            name: 'AC_003（照明电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
            '2:00': '3626',
          },
          {
            key: '2',
            name: 'AC_003（照明电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
            '2:00': '3626',
          },
          {
            key: '3',
            name: 'AC_004（给排水电表）',
            paramName: '用电量(kWh)',
            date: '2023-12-01',
            '1:00': '3626',
            '2:00': '3626',
          },
        ];
        pageData.graphTableColumns = [
          {
            title: '日期',
            dataIndex: 'date',
          },
          {
            title: '1:00',
            dataIndex: '1:00',
          },
          {
            title: '2:00',
            dataIndex: '2:00',
          },
        ];
        pageData.graphGraphList = [
          {
            date: '2023-12-01 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '21',
              },
              {
                name: 'AC_003（照明电表）',
                value: '36',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '5',
              },
              {
                name: 'AC_005（333333333）',
                value: '22',
              },
            ],
          },
          {
            date: '2023-12-02 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '26',
              },
              {
                name: 'AC_003（照明电表）',
                value: '25',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '47',
              },
              {
                name: 'AC_005（333333333）',
                value: '28',
              },
            ],
          },
          {
            date: '2023-12-03 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '18',
              },
              {
                name: 'AC_003（照明电表）',
                value: '22',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '26',
              },
              {
                name: 'AC_005（333333333）',
                value: '44',
              },
            ],
          },
          {
            date: '2023-12-04 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '40',
              },
              {
                name: 'AC_003（照明电表）',
                value: '15',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '12',
              },
              {
                name: 'AC_005（333333333）',
                value: '26',
              },
            ],
          },
          {
            date: '2023-12-05 0:00',
            unit: 'V',
            data: [
              {
                name: 'AC_002（暖通电表）',
                value: '15',
              },
              {
                name: 'AC_003（照明电表）',
                value: '18',
              },
              {
                name: 'AC_004（给排水电表）',
                value: '15',
              },
              {
                name: 'AC_005（333333333）',
                value: '35',
              },
            ],
          },
        ];
      };

      const orgId = ref('');
      const result = JSON.parse(sessionStorage.getItem('ORGID')!);
      orgId.value = result;
      const treeData2 = ref<TreeSelectProps['treeData']>([]);
      // 切换树结构
      const changeMode = () => {
        treeLoading.value = true;
        if (mode.value == '1') {
          http
            .post(device.queryDevicePage, {
              deviceName: deviceName.value,
              energyType: selectedValue.value,
              orgId: orgId.value,
              pageNum: 1,
              pageSize: 9999,
            })
            .then((res) => {
              let val = '999999999';

              let label = '所有设备';

              let records = res.data.records;
              records.forEach((item: any) => {
                (item.title = item.deviceModel + ' ' + item.deviceName), (item.key = item.id);
              });
              let a: TreeSelectProps['treeData'] = [{ title: label, key: val, children: records }];
              treeData2.value = a;
              expandedKeys.value = [val];
            })
            .finally(() => {
              treeLoading.value = false;
            });
        } else {
          http
            .post(group.queryDeviceGroupTree, {
              pointName: pointName.value,
              energyType: selectedValue.value,
              orgId: orgId.value,
            })
            .then((res) => {
              treeData2.value = [];
              treeData2.value = formatTreeData(pointName.value ? res.data[0].searchList : res.data);

              expandedKeys.value = getAllKeys(treeData2.value);
            })
            .finally(() => {
              treeLoading.value = false;
            });
        }
      };
      const getAllKeys = (data: any) => {
        let keys: any[] = [];
        data.forEach((item: any) => {
          if (item.children) {
            keys.push(item.key);
            keys = keys.concat(getAllKeys(item.children));
          }
        });
        return keys;
      };
      const formatTreeData = (data: any) => {
        return data.map((item: any) => ({
          title: item.pointName,
          key: item.id,
          children: item.children ? formatTreeData(item.children) : [],
        }));
      };

      type RangeValue = [Dayjs, Dayjs];
      const dates = ref<RangeValue>();
      const hackValue = ref<RangeValue>();

      const disabledDate = (current: Dayjs) => {
        if (!dates.value || (dates.value as any).length === 0) {
          return false;
        }
        const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 2;
        const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 2;
        return tooEarly || tooLate;
      };

      const onOpenChange = (open: boolean) => {
        if (open) {
          dates.value = [] as any;
          hackValue.value = [] as any;
        } else {
          hackValue.value = undefined;
        }
      };

      const onChange = (val: RangeValue) => {
        dateRange.value = val;
      };

      const onCalendarChange = (val: RangeValue) => {
        dates.value = val;
      };
      onMounted(() => {
        getOptionsList();
        changeMode();
      });

      return {
        value,
        deviceName,
        pointName,
        treeData2,
        expandedKeys,
        selectedKeys,
        checkedKeys,
        options1,
        options2,
        mode,
        selectedValue,
        frequencyValue,
        dateRange,
        getOptionsList,
        getSelect,
        getSelect11,
        changeMode,
        disabledDate,
        onCalendarChange,
        onOpenChange,
        onChange,
        hackValue,
        treeLoading,
        changeEnergyType,
        shebei,
      };
    },
  });
</script>

<style lang="less" scoped>
  .ns-tree-title {
    user-select: text;
    margin-bottom: 5px;
    padding-bottom: 10px;
    padding-top: 10px;
    border-bottom: 1px solid #e9e9e9;
    > span {
      padding-left: 10px;
      line-height: 20px;
    }
  }
  .parent-container {
    position: relative;
    height: 100%;
  }

  .fixed-bottom {
    position: absolute;
    bottom: 0;
    width: 100%;
    margin-bottom: 10px;
  }
</style>
