<template>
  <div class="p-2">
    <el-row :gutter="28">
      <el-col :span="4.3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入物联网设备名称"
            clearable

            prefix-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" :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="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @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" name="CurrentIOTCurve">
import { ref, reactive, watch, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { iotInstantList } from '@/api/ems/record/recordIOTInstant';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { parseTime } from '@/utils/ruoyi';
import Chart from '@/components/chart.vue';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const monitorInfoOptions = ref<any[]>([]);
const workUnitName = ref<string | undefined>(undefined);
const selectMonitorName = ref<string | null>(null);
const daterangeCollectTime = ref<string[]>([]);
const loading = ref(true);
const ids = ref<any[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dataList = ref<any[]>([]);
const dialogTitle = ref('');
const dialogOpen = ref(false);

const queryParams = ref<any>({
  monitorId: null,
  collectTime: null,
  tempreture: null,
  humidity: null,
  illuminance: null,
  noise: null,
  concentration: null,
  recordTime: null,
  glys: null,
  zxyg: null,
  activePower: null,
  reactivePower: null,
  collectType: null
});

const monitorProps = { children: 'children', label: 'label' };

const rules = reactive({
  objId: [{ required: true, message: '编号不能为空', trigger: 'blur' }]
});

const columns = ref([
  { key: 0, label: '主键标识', visible: false },
  { key: 1, label: '计量设备编号', visible: true },
  { key: 2, label: '采集时间', visible: true },
  { key: 3, label: '温度', visible: true },
  { key: 4, label: '湿度', visible: true },
  { key: 5, label: '照度', visible: true },
  { key: 6, label: '噪声', visible: true },
  { key: 7, label: '硫化氢浓度', visible: true },
  { key: 8, label: '记录时间', visible: true },
  { key: 9, label: '报警类型', visible: true },
  { key: 10, label: '', visible: true },
  { key: 11, label: '', visible: false },
  { key: 12, label: '', visible: false },
  { key: 13, label: '', visible: true },
  { key: 14, label: '', visible: true }
]);

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

function filterNode(value: string, data: any) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

function getTreeselect() {
  getMonitorInfoTree({ monitorTypeList: [5, 6, 7, 8, 9] }).then((response: any) => {
    monitorInfoOptions.value = response.data;
  });
}

function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (daterangeCollectTime.value && daterangeCollectTime.value.length) {
    queryParams.value.params['beginCollectTime'] = daterangeCollectTime.value[0];
    queryParams.value.params['endCollectTime'] = daterangeCollectTime.value[1];
  }
  getChart();
}

function handleQuery() {
  getList();
}

function resetQuery() {
  queryParams.value.monitorId = null;
  queryForm.value?.resetFields();
  handleQuery();
}

function handleNodeClick(data: any, node: any, comp: any) {
  queryParams.value.monitorId = data.code;
  selectMonitorName.value = data.label;
  handleQuery();
}

async function getChart() {
  if (queryParams.value.monitorId == null) {
    loading.value = false;
    return;
  }
  const query = JSON.parse(JSON.stringify(queryParams.value));
  const { data } = await iotInstantList(query);

  const option1: any = {
    title: {
      text: '物联网设备曲线',
      x: 'center'
    },
    legend: {
      data: data.monitorTypeArr,
      right: 0
    },
    grid: {
      top: 60,
      bottom: 80,
      left: 60,
      right: 40,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis'
    },
    dataZoom: [
      { type: 'slider', height: 20, bottom: 10, start: 0, end: 100 },
      { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: true }
    ],
    xAxis: {
      type: 'category',
      data: data.dataList.map((e: any) => e.collectTime),
      axisLine: { show: true, lineStyle: { color: '#000' } },
      axisTick: { alignWithLabel: true },
      axisLabel: {
        show: true,
        color: '#000',
        rotate: data.dataList.length > 20 ? 45 : 0,
        interval: 'auto',
        formatter: (value: string) => {
          if (value && value.length > 16) {
            return value.substring(11, 19);
          }
          return value;
        }
      }
    },
    yAxis: [{
      type: 'value',
      name: '数值',
      nameTextStyle: { color: '#000' },
      splitLine: { show: true, lineStyle: { type: 'dashed', color: '#e0e0e0' } },
      axisTick: { show: true },
      axisLine: { show: true, lineStyle: { color: '#000' } },
      axisLabel: {
        show: true,
        color: '#000',
        formatter: (value: number) => {
          if (Math.abs(value) >= 10000) return (value / 1000).toFixed(1) + 'k';
          if (Math.abs(value) >= 1) return value.toFixed(1);
          return value.toFixed(2);
        }
      },
      scale: true,
      splitNumber: 5
    }],
    series: [
      {
        tooltip: { show: data.monitorTypeArr.includes('温度') },
        name: '温度',
        type: data.type,
        smooth: data.smooth,
        showAllSymbol: data.showAllSymbol,
        symbol: data.symbol,
        symbolSize: data.symbolSize,
        data: data.monitorTypeArr.includes('温度') ? data.dataList.map((e: any) => e.tempreture) : []
      },
      {
        tooltip: { show: data.monitorTypeArr.includes('湿度') },
        name: '湿度',
        type: data.type,
        smooth: data.smooth,
        showAllSymbol: data.showAllSymbol,
        symbol: data.symbol,
        symbolSize: data.symbolSize,
        data: data.monitorTypeArr.includes('湿度') ? data.dataList.map((e: any) => e.humidity) : []
      },
      {
        tooltip: { show: data.monitorTypeArr.includes('噪声') },
        name: '噪声',
        type: data.type,
        smooth: data.smooth,
        showAllSymbol: data.showAllSymbol,
        symbol: data.symbol,
        symbolSize: data.symbolSize,
        data: data.monitorTypeArr.includes('噪声') ? data.dataList.map((e: any) => e.noise) : []
      },
      {
        tooltip: { show: data.monitorTypeArr.includes('照度') },
        name: '照度',
        type: data.type,
        smooth: data.smooth,
        showAllSymbol: data.showAllSymbol,
        symbol: data.symbol,
        symbolSize: data.symbolSize,
        data: data.monitorTypeArr.includes('照度') ? data.dataList.map((e: any) => e.illuminance) : []
      },
      {
        tooltip: { show: data.monitorTypeArr.includes('气体浓度') },
        name: '气体浓度',
        type: data.type,
        smooth: data.smooth,
        showAllSymbol: data.showAllSymbol,
        symbol: data.symbol,
        symbolSize: data.symbolSize,
        data: data.monitorTypeArr.includes('气体浓度') ? data.dataList.map((e: any) => e.concentration) : []
      }
    ]
  };

  Chart1.value?.setData(option1);
  if (Chart1.value?.chart) {
    echarts.connect(Chart1.value.chart);
    Chart1.value.chart.off('datazoom');
    Chart1.value.chart.on('datazoom', (e: any) => {
      option1.dataZoom[0].start = e.start;
      option1.dataZoom[0].end = e.end;
      Chart1.value?.setData(option1);
    });
  }
  loading.value = false;
}

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 scoped>
.chart1 {
  width: 100%;
  height: calc(100vh - 200px);
  min-height: 400px;
  max-height: 800px;
}

.chart2 {
  width: 100%;
  height: calc(50vh - 100px);
  min-height: 300px;
}

@media screen and (max-width: 768px) {
  .chart1 {
    height: 60vh;
    min-height: 300px;
  }
  .chart2 {
    height: 40vh;
    min-height: 250px;
  }
}
</style>
