<!-- 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, watch } 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';
  import { Item } from 'ant-design-vue/lib/menu';

  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.snCode + '（' + item.deviceName + '）'),
                (item.key = item.deviceInfoCode);
            });
            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 = () => {
        if (checkedKeys.value && checkedKeys.value.length > 0) {
          http
            .post(deviceMonitor.getDevicePointToMonitor, {
              deviceIds: checkedKeys.value,
              orgId: orgId.value,
            })
            .then((res) => {
              if (res.retcode == 0) {
                options1.value = [];
                res.data.forEach((item: any) => {
                  options1.value?.push({ value: item.code, label: item.name });
                });
              }

              // options1.value = res.data;
            });
        } else {
          options1.value = [];
        }
        // 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: checkedKeys.value,
            devicePointCode: selectedValue.value,

            endDate: endDate.value,
            startDate: startDate.value,
            timeRate: '2',
          })
          .then((res) => {
            pageData.tableList = res.data.tableList;
            pageData.tableColumns = res.data.tableHeaderList;

            pageData.graphList = res.data.graphData;
            pageData.XData = res.data.XData;
          });
      };

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

      const onChange = (val: RangeValue, dateStrings: any) => {
        dateRange.value = val;
        if (dateStrings && dateStrings.length === 2) {
          startDate.value = dateStrings[0];
          endDate.value = dateStrings[1];
        }
      };
      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(() => {
        changeDeviceType(null, null);
        getSelect();
      });
      // 监听 pageData 的变化
      watch(
        () => checkedKeys,
        (_newValue, _oldValue) => {
          getDianWeiList();
        },
        { deep: true },
      );

      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>
