<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"
            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" 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>
        <!--        <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>-->
        <div class="chart">
          <Chart ref="Chart1" style="width: 100%; height: 100%" :chartOption="getChart()" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { useDict } from '@/utils/dict';
import { listRecordIOTInstant, getRecordIOTInstant, iotInstantList } 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/Charts/Chart';
import * as echarts from 'echarts';

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

const { proxy } = getCurrentInstance() as any;

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

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

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

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  list: [],
  //下拉树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: {
    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
  },
  // 表单参数
  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: `温度`,
      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
    }
  ]
} as any);

const {
  baseMonitorInfoList,
  baseMonitorInfoOptions,
  columns,
  dataList,
  daterangeCollectTime,
  form,
  ids,
  list,
  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.monitorId,
    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,
    monitorId: null,
    collectTime: null,
    recordTime: null,
    collectType: 1
  };
  form.value?.resetFields();
};

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

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

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

const getTreeselect = () => {
  getMonitorInfoTree({
    monitorTypeList: [5, 6, 7, 8, 9],
    monitorType: proxy?.$route.query.monitorType
  }).then((response) => {
    monitorInfoOptions.value = response.data;
  });
};

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

const handleNodeClick = async (a, datas) => {
  // console.log(datas.checkedKeys)
  const { data } = await iotInstantMonitoring({
    monitorCodeList: datas.checkedKeys.toString()
  });
  list.value = data;
  // console.log(data)
  // queryParams.value.monitorTypeList = type
  // queryParams.value.monitorId = data.code
  // selectMonitorName.value = data.label
  // handleQuery()
};

const getChart = (e) => {
  // if(!e)return
  function Pie() {
    const dataArr = [];
    for (let i = 0; i < 150; i++) {
      if (i % 2 === 0) {
        dataArr.push({
          name: (i + 1).toString(),
          value: 50,
          itemStyle: {
            normal: {
              color: '#00AFFF',
              borderWidth: 0,
              borderColor: 'rgba(0,0,0,0)'
            }
          }
        });
      } else {
        dataArr.push({
          name: (i + 1).toString(),
          value: 100,
          itemStyle: {
            normal: {
              color: 'rgba(0,0,0,0)',
              borderWidth: 0,
              borderColor: 'rgba(0,0,0,0)'
            }
          }
        });
      }
    }
    return dataArr;
  }
  const option = {
    backgroundColor: 'rgba(255, 255, 255)',
    // title: {
    //   text: '',
    //   textStyle: {
    //     fontWeight: 'normal',
    //     fontSize: 25,
    //     color: 'rgb(97, 142, 205)'
    //   }
    // },
    series: [
      {
        // value: 50, //  内容 配合formatter
        type: 'liquidFill',
        radius: '70%',
        // 控制中间圆球的尺寸（此处可以理解为距离外圈圆的距离控制）
        center: ['50%', '50%'],
        data: [
          0.6,
          {
            value: 0.6,
            direction: 'left' //波浪方向
          }
        ],
        // data个数代表波浪数
        backgroundStyle: {
          borderWidth: 1,
          color: 'rgba(62, 208, 255, 1)' // 球体本景色
        },
        amplitude: '6  %',
        //波浪的振幅
        // 修改波浪颜色
        // color: ['#0286ea', 'l#0b99ff'], // 每个波浪不同颜色，颜色数组长度为对应的波浪个数
        color: [
          {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 1,
                color: '#6CDEFC'
              },
              {
                offset: 0,
                color: '#429BF7'
              }
            ],
            globalCoord: false
          }
        ],
        label: {
          normal: {
            // formatter: 0.87 * 100 + '\n%',
            formatter: 0.6 * 100 + '\n{d|%}',
            //  formatter: function(params){
            //     return params.value* 100 + " \n%";
            // },
            rich: {
              d: {
                fontSize: 36
              }
            },
            textStyle: {
              fontSize: 48,
              color: '#fff'
            }
          }
        },
        outline: {
          show: false
        }
      },
      {
        type: 'pie',
        z: 1,
        center: ['50%', '50%'],
        radius: ['72%', '73.5%'],
        // 控制外圈圆的粗细
        hoverAnimation: false,
        data: [
          {
            name: '',
            value: 500,
            labelLine: {
              show: false
            },
            itemStyle: {
              color: '#00AFFF'
            },
            emphasis: {
              labelLine: {
                show: false
              },
              itemStyle: {
                color: '#00AFFF'
              }
            }
          }
        ]
      },
      {
        //外发光
        type: 'pie',
        z: 1,
        zlevel: -1,
        radius: ['70%', '90.5%'],
        center: ['50%', '50%'],
        hoverAnimation: false,
        clockWise: false,
        itemStyle: {
          normal: {
            borderWidth: 20,
            color: 'rgba(224,242,255,1)'
          }
        },
        label: {
          show: false
        },
        data: [100]
      },
      {
        //底层外发光
        type: 'pie',
        z: 1,
        zlevel: -2,
        radius: ['70%', '100%'],
        center: ['50%', '50%'],
        hoverAnimation: false,
        clockWise: false,
        itemStyle: {
          normal: {
            borderWidth: 20,
            color: 'rgba(224,242,255,.4)'
          }
        },
        label: {
          show: false
        },
        data: [100]
      },
      {
        type: 'pie',
        zlevel: 0,
        silent: true,
        radius: ['78%', '80%'],
        z: 1,
        label: {
          normal: {
            show: false
          }
        },
        labelLine: {
          normal: {
            show: false
          }
        },
        data: Pie()
      }
    ]
  };
  return option;
  // Chart1.value.setData(option)
};

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>
.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>
