<template>
  <div class="p-2">
    <el-row :gutter="28">
      <el-col :span="4" :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"
            ref="tree"
            show-checkbox
            node-key="code"
            :check-strictly="true"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
            @check="handleNodeClick">
          </el-tree>
        </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>
        <div v-for="item in list" class="chart">
          <Chart ref="Chart1" style="width: 100%;height: 100%" :chartOption="getChart(item)"/>
          <div class="title">{{item.monitorName}}</div>
        </div>
      </el-col>
    </el-row>


  </div>
</template>

<script setup lang="ts" name="TemperatureHumidityMonitoring">
import { ref, reactive, watch, onMounted, getCurrentInstance } from 'vue';
import {
  listRecordIOTInstant,
  getRecordIOTInstant
} from '@/api/ems/record/recordIOTInstant';
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { iotInstantMonitoring } from '@/api/ems/report/TemperatureHumidityMonitoring';
import { parseTime } from '@/utils/ruoyi';
import Chart from '@/components/chart.vue';
import * as echarts from 'echarts';
import type { ElTree } from 'element-plus';

const { proxy } = getCurrentInstance() as any;

// 引用
const tree = ref<InstanceType<typeof ElTree>>();
const queryFormRef = ref();

// 数据
const list = ref<any[]>([]);
const monitorInfoOptions = ref<any[]>([]);
const workUnitName = ref<string>();
const baseMonitorInfoList = ref<any[]>([]);
const daterangeCollectTime = ref<string[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dataList = ref<any[]>([]);
const dialogOpen = ref(false);
const dialogTitle = ref('');

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

const queryParams = reactive({
  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,
  params: {}
});

const form = reactive({
  objId: null,
  monitorId: null,
  collectTime: null,
  recordTime: null,
  collectType: 1
});

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 }
]);

// 监听工作单元名称变化
watch(workUnitName, (val) => {
  tree.value?.filter(val);
});

/** 转换计量设备信息数据结构 */
function normalizer(node: any) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.monitorId,
    label: node.monitorName,
    children: node.children
  };
}

/** 查询电实时数据列表 */
function getList() {
  loading.value = true;
  queryParams.params = {};
  if (daterangeCollectTime.value && daterangeCollectTime.value.length > 0) {
    queryParams.params['beginCollectTime'] = daterangeCollectTime.value[0];
    queryParams.params['endCollectTime'] = daterangeCollectTime.value[1];
  }
  getChart();
}

/** 取消按钮 */
function cancel() {
  dialogOpen.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    objId: null,
    monitorId: null,
    collectTime: null,
    recordTime: null,
    collectType: 1
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.monitorId = null;
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ems/record/recordIOTInstant/export', {
    ...queryParams
  }, `recordIOTInstant_${new Date().getTime()}.xlsx`);
}

/** 查询计量设备信息下拉树结构 */
function getTreeselect() {
  getMonitorInfoTree({ monitorTypeList: [5,6,7,8,9], monitorType: proxy.$route.query.monitorType }).then(response => {
    monitorInfoOptions.value = response.data;
  });
}

/** 筛选节点 */
function filterNode(value: string, data: any) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

/** 节点单击事件 */
async function handleNodeClick(a: any, datas: any) {
  const { data } = await iotInstantMonitoring({ monitorCodeList: datas.checkedKeys.toString() });
  list.value = data;
}

/** 物联网设备曲线 */
function getChart(e?: any) {
  if (!e) return;
  const option = {
    series: [
      {
        name: 'Pressure',
        type: 'gauge',
        detail: {
          formatter: '{value}'
        },
        center: ['25%', '50%'],
        radius: '90%',
        data: [
          {
            value: e.tempreture,
            name: '温度',
            title: {}
          }
        ]
      },
      {
        name: 'Pressure',
        type: 'gauge',
        detail: {
          fontSize: 20,
          formatter: '{value}'
        },
        center: ['65%', '70%'],
        radius: '50%',
        axisTick: {
          distance: 4
        },
        pointer: {
          length: '50%',
          width: 4
        },
        data: [
          {
            value: e.humidity,
            name: '湿度',
            detail: {
              fontSize: 12
            }
          }
        ]
      }
    ]
  };
  return option;
}

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>
.chart {
  display: inline-block;
  width: 50%;
  height: 40vh;
  position: relative;
}
.chart .title {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  font-size: 1vw;
  font-weight: 700;
}
.chart2 {
  width: 100%;
  height: 40vh;
}
</style>
