<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <div class="parent-container">
    <div class="ns-tree-title">
      <span>设备列表</span>
    </div>
    <a-tree-select
      v-model:value="value"
      style="width: 100%"
      :tree-line="treeLine && { showLeafIcon }"
      :tree-data="treeData1"
      @change="changeDeviceType" />

    <a-spin :spinning="treeLoading">
      <a-tree
        v-model:expandedKeys="expandedKeys"
        v-model:selectedKeys="selectedKeys"
        v-model:checkedKeys="checkedKeys"
        checkable
        :height="340"
        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
        ref="select"
        v-model:value="selectedValue"
        placeholder="请选择点位"
        style="width: 100%; margin-bottom: 10px"
        :options="options1" />
      <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>
    </div>
  </div>
</template>

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

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

      const orgId = ref('');
      const result = JSON.parse(sessionStorage.getItem('ORGID')!);
      orgId.value = result;

      const treeData1 = ref<TreeSelectProps['treeData']>([]);

      http.post(device.queryDeviceTree, { orgId: orgId.value }).then((res) => {
        treeData1.value = formatTreeData(res.data);
      });

      const formatTreeData = (data: any) => {
        return data.map((item: any) => ({
          title: item.code + '.' + item.deviceType,
          value: item.code,
          children: item.children ? formatTreeData(item.children) : [],
        }));
      };

      const treeData2 = ref<TreeSelectProps['treeData']>([]);

      const changeDeviceType = (val: any, label: any) => {
        treeLoading.value = true;
        http
          .post(device.queryDevicePage, {
            code: val,
            orgId: orgId.value,
            pageNum: 1,
            pageSize: 1000,
          })
          .then((res) => {
            if (!val) {
              val = '999999999';
            }
            if (!label) {
              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[0], key: val, children: records }];
            treeData2.value = a;
            expandedKeys.value = [val];
          })
          .finally(() => {
            treeLoading.value = false;
          });
      };

      const expandedKeys = ref<string[]>([]);
      const selectedKeys = ref<string[]>([]);
      const checkedKeys = ref<string[]>([]);

      const options1 = ref<SelectProps['options']>([]);
      const options2 = ref<SelectProps['options']>([
        {
          value: '1',
          label: '5分钟',
        },
        {
          value: '2',
          label: '10分钟',
        },
        {
          value: '3',
          label: '30分钟',
        },
        {
          value: '4',
          label: '1小时',
        },
      ]);
      const selectedValue = ref<string | undefined>();
      const frequencyValue = ref<string | undefined>();
      const dateRange = ref<[Dayjs, Dayjs] | undefined>();

      const getDianWeiList = () => {
        console.log('getDianWeiList 被调用');
        options1.value = [
          { value: '1', label: 'A 项电压' },
          { value: '2', label: 'B 项电压' },
          { value: '3', label: 'C 项电压' },
          { value: '4', label: 'AB 线电压' },
          { value: '5', label: 'BC 线电压' },
          { value: '6', label: 'A 项电流' },
          { value: '7', label: 'B 项电流' },
        ];
      };

      interface PageData {
        tableList: any[];
        tableColumns: any[];
        graphList: any[];
        XData: any[];
      }
      const pageData = inject<PageData>('pageData');
      if (!pageData) {
        throw new Error('pageData is not provided');
      }
      // 查询数据后放入pageData
      const getSelect = () => {
        http
          .post(deviceMonitor.getDeviceGraph, {
            deviceIds: ['HLlmTZp8-0601-0001', 'HLlmTZp-0804-0001'],
            devicePointCode: 'ua',
            devicePointId: 32,
            endDate: '2024-07-02',
            startDate: '2024-07-01',
            timeRate: '2',
          })
          .then((res) => {
            pageData.tableList = res.data.tableList;
            pageData.tableColumns = res.data.tableHeaderList;

            pageData.graphList = res.data.graphData;
            pageData.XData = res.data.XData;
          });
        // pageData.tableList = [
        //   {
        //     key: '1',
        //     name: 'AC_002（暖通电表）',
        //     position: 'A 相电压',
        //     unit: 'V',
        //     date: '2023-12-01',
        //     '1:00': '3626',
        //   },
        //   {
        //     key: '1',
        //     name: 'AC_002（暖通电表）',
        //     position: 'A 相电压',
        //     unit: 'V',
        //     date: '2023-12-01',
        //     '1:00': '3626',
        //   },
        //   {
        //     key: '2',
        //     name: 'AC_003（照明电表）',
        //     position: 'A 相电压',
        //     unit: 'V',
        //     date: '2023-12-01',
        //     '1:00': '3626',
        //   },
        //   {
        //     key: '2',
        //     name: 'AC_003（照明电表）',
        //     position: 'A 相电压',
        //     unit: 'V',
        //     date: '2023-12-01',
        //     '1:00': '3626',
        //   },
        //   {
        //     key: '3',
        //     name: 'AC_004（给排水电表）',
        //     position: 'A 相电压',
        //     unit: 'V',
        //     date: '2023-12-01',
        //     '1:00': '3626',
        //   },
        // ];
        // pageData.tableColumns = [
        //   {
        //     title: '00:00',
        //     dataIndex: '00:00',
        //   },
        // ];
        // pageData.graphList = [
        //   {
        //     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',
        //       },
        //     ],
        //   },
        //   {
        //     date: '2023-12-06 0:00',
        //     unit: 'V',
        //     data: [
        //       {
        //         name: 'AC_002（暖通电表）',
        //         value: '15',
        //       },
        //       {
        //         name: 'AC_003（照明电表）',
        //         value: '18',
        //       },
        //       {
        //         name: 'AC_004（给排水电表）',
        //         value: '15',
        //       },
        //     ],
        //   },
        // ];
      };

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

      const onChange = (val: RangeValue) => {
        dateRange.value = val;
      };
      const onOpenChange = (open: boolean) => {
        if (open) {
          dates.value = [] as any;
          hackValue.value = [] as any;
        } else {
          hackValue.value = undefined;
        }
      };
      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 onCalendarChange = (val: RangeValue) => {
        dates.value = val;
      };

      onMounted(() => {
        getDianWeiList();
        changeDeviceType(null, null);
        getSelect();
      });

      return {
        treeLine,
        showLeafIcon,
        value,
        treeData1,
        treeData2,
        expandedKeys,
        selectedKeys,
        checkedKeys,
        options1,
        options2,
        selectedValue,
        frequencyValue,
        dateRange,
        getDianWeiList,
        getSelect,
        disabledDate,
        onCalendarChange,
        onOpenChange,
        onChange,
        hackValue,
        pageData,
        changeDeviceType,
        treeLoading,
      };
    },
  });
</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>
