<template>
  <div class="app-container">
    <el-row :gutter="28">
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入计量设备名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="monitorInfoOptions"
            :props="monitorProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <!--          <el-form-item label="计量设备编号" prop="monitorCode">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.monitorCode"-->
          <!--              placeholder="请输入计量设备编号"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="采集时间">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 340px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <Chart ref="Chart1" class="chart1" />
        <Chart ref="Chart2" class="chart2" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { useDict } from '@/utils/dict';
import { listRecordDnbInstant, getRecordDnbInstant, dnbInstantList } from '@/api/ems/record/recordDnbInstant';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { parseTime } from '@/utils/ruoyi';
import Chart from '@/components/Charts/Chart';
import * as echarts from 'echarts';

defineOptions({
  name: 'CurrentVoltageCurve',
  dicts: ['collect_type']
} as any);

const { proxy } = getCurrentInstance() as any;

const dict = reactive({
  type: useDict('collect_type') as any
});

const Chart1 = ref<any>();
const Chart2 = ref<any>();
const queryForm = ref<any>();
const tree = ref<any>();

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objId: null,
  monitorCode: null,
  collectTime: null,
  recordTime: null,
  collectType: 1
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  //下拉树List
  baseMonitorInfoOptions: [],
  //左侧树结构List
  monitorInfoOptions: [],
  workUnitName: undefined,
  //左侧树结构 检索设备名称
  selectMonitorName: null,
  //计量设备信息
  baseMonitorInfoList: [],
  // 采集方式时间范围
  daterangeCollectTime: [],
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 电实时数据表格数据
  dataList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    monitorCode: null,
    collectTime: null,
    recordTime: null,
    glys: null,
    zxyg: null,
    activePower: null,
    reactivePower: null,
    collectType: null
  },
  // 表单参数
  form: createFormData(),
  monitorProps: {
    children: 'children',
    label: 'label'
  },
  // 表单校验
  rules: {
    objId: [
      {
        required: true,
        message: '编号不能为空',
        trigger: 'blur'
      }
    ]
  },
  columns: [
    {
      key: 0,
      label: `主键标识`,
      visible: false
    },
    {
      key: 1,
      label: `计量设备编号`,
      visible: true
    },
    {
      key: 2,
      label: `采集时间`,
      visible: true
    },
    {
      key: 3,
      label: `A项电压`,
      visible: true
    },
    {
      key: 4,
      label: `B项电压`,
      visible: true
    },
    {
      key: 5,
      label: `C项电压`,
      visible: true
    },
    {
      key: 6,
      label: `A项电流`,
      visible: true
    },
    {
      key: 7,
      label: `B项电流`,
      visible: true
    },
    {
      key: 8,
      label: `C项电流`,
      visible: true
    },
    {
      key: 9,
      label: `记录时间`,
      visible: true
    },
    {
      key: 10,
      label: `功率因数`,
      visible: true
    },
    {
      key: 11,
      label: `正向有功`,
      visible: true
    },
    {
      key: 12,
      label: `有功功率`,
      visible: false
    },
    {
      key: 13,
      label: `无功功率`,
      visible: false
    },
    {
      key: 14,
      label: `采集方式`,
      visible: true
    },
    {
      key: 15,
      label: `计量设备名称`,
      visible: true
    }
  ]
} as any);

const {
  baseMonitorInfoList,
  baseMonitorInfoOptions,
  columns,
  dataList,
  daterangeCollectTime,
  form,
  ids,
  loading,
  monitorInfoOptions,
  monitorProps,
  multiple,
  open,
  queryParams,
  rules,
  selectMonitorName,
  showSearch,
  single,
  title,
  total,
  workUnitName
} = toRefs(state);

const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.monitorCode,
    label: node.monitorName,
    children: node.children
  };
};

const getList = () => {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCollectTime.value && '' != daterangeCollectTime.value) {
    queryParams.value.params['beginCollectTime'] = daterangeCollectTime.value[0];
    queryParams.value.params['endCollectTime'] = daterangeCollectTime.value[1];
  }
  console.log(monitorInfoOptions.value);
  getChart();
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    objId: null,
    monitorCode: null,
    collectTime: null,
    recordTime: null,
    collectType: 1
  };
  form.value?.resetFields();
};

const handleQuery = () => {
  getList();
};

const resetQuery = () => {
  queryParams.value.monitorCode = null;
  queryForm.value?.resetFields();
  handleQuery();
};

const handleExport = () => {
  proxy?.download(
    'ems/record/recordDnbInstant/export',
    {
      ...queryParams.value
    },
    `recordDnbInstant_${new Date().getTime()}.xlsx`
  );
};

const getTreeselect = () => {
  getMonitorInfoTree({
    monitorType: 2
  }).then((response) => {
    monitorInfoOptions.value = response.data;
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const handleNodeClick = (data) => {
  queryParams.value.monitorCode = data.code;
  selectMonitorName.value = data.label;
  handleQuery();
};

const getChart = async () => {
  if (queryParams.value.monitorCode == null) {
    return;
  }
  const query = JSON.parse(JSON.stringify(queryParams.value));
  const { data } = await dnbInstantList(query);
  const option1 = {
    title: {
      text: selectMonitorName.value + ' 电流曲线',
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '10%',
      left: '3%',
      right: '3%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    legend: {
      right: 0
    },
    xAxis: {
      data: data.map((e) => e.collectTime),
      axisLine: {
        show: true,
        //隐藏X轴轴线
        lineStyle: {
          color: '#000'
        }
      },
      axisTick: {
        show: true //隐藏X轴刻度
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000' //X轴文字颜色
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '电流（A）',
        nameTextStyle: {
          color: '#000'
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000'
          }
        }
      }
    ],
    series: [
      {
        name: 'A相电流',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   //折线拐点标志的样式
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.ia)
      },
      {
        name: 'B相电流',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   //折线拐点标志的样式
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.ib)
      },
      {
        name: 'C相电流',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.ic)
      }
    ]
  };
  const option2 = {
    title: {
      text: selectMonitorName.value + ' 电压曲线',
      x: 'center'
    },
    grid: {
      top: '15%',
      bottom: '10%',
      left: '3%',
      right: '3%'
    },
    dataZoom: [
      {
        type: 'slider'
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true
        }
      }
    },
    legend: {
      right: 0
    },
    xAxis: {
      data: data.map((e) => e.collectTime),
      axisLine: {
        show: true,
        //隐藏X轴轴线
        lineStyle: {
          color: '#000'
        }
      },
      axisTick: {
        show: true //隐藏X轴刻度
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#000' //X轴文字颜色
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '电压（V）',
        nameTextStyle: {
          color: '#000'
        },
        splitLine: {
          show: false
        },
        axisTick: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#000'
          }
        }
      }
    ],
    series: [
      {
        name: 'A相电压',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   //折线拐点标志的样式
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.va)
      },
      {
        name: 'B相电压',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   //折线拐点标志的样式
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.vb)
      },
      {
        name: 'C相电压',
        type: 'line',
        smooth: true,
        //平滑曲线显示
        showAllSymbol: true,
        //显示所有图形。
        symbol: 'circle',
        //标记的图形为实心圆
        symbolSize: 10,
        //标记的大小
        // itemStyle: {
        //   color: "#058cff",
        // },
        // lineStyle: {
        //   color: "#058cff",
        // },
        // areaStyle: {
        //   color: "rgba(5,140,255, 0.2)",
        // },
        data: data.map((e) => e.vc)
      }
    ]
  };
  Chart1.value.setData(option1);
  Chart2.value.setData(option2);
  echarts.connect(Chart1.value.chart, Chart2.value.chart);
  Chart1.value.chart.on('datazoom', (e) => {
    option2.dataZoom[0].start = e.start;
    option2.dataZoom[0].end = e.end;
    Chart2.value.setData(option2);
  });
  Chart2.value.chart.on('datazoom', (e) => {
    option1.dataZoom[0].start = e.start;
    option1.dataZoom[0].end = e.end;
    Chart1.value.setData(option1);
  });
};

watch(workUnitName, (val) => {
  tree.value.filter(val);
});

onMounted(() => {
  const nowDate = parseTime(new Date(), '{y}-{m}-{d}');
  daterangeCollectTime.value[0] = nowDate + ' 00:00:00';
  daterangeCollectTime.value[1] = nowDate + ' 23:59:59';
  getTreeselect();
  getList();
});
</script>
<style>
.chart1 {
  width: 100%;
  height: 40vh;
}

.chart2 {
  width: 100%;
  height: 40vh;
}
</style>
