<template>

  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <!--          <el-tag-->
          <!--            :key="item.monitorId"-->
          <!--            v-for="item in dynamicTags"-->
          <!--            closable-->
          <!--            :disable-transitions="false"-->
          <!--            @close="handleClose(item.id)"-->
          <!--          >-->
          <!--            {{ item.label }}-->
          <!--          </el-tag>-->
          <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="workUnitOptions"
            :props="workUnitProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :check-strictly="true"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            show-checkbox
            @node-click="handleNodeClick"
            @check="handleTreeCheck"
          />
        </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="dateType">
            <el-select v-model="queryParams.dateType" placeholder="请选择日期类型">
              <el-option
                v-for="item in dateTypeList"
                :key="item.dateTypeCode"
                :label="item.dateTypeName"
                :value="item.dateTypeCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采集日期">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
            ></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 style="margin-bottom: 24px;">
          <div id="barChart" style="height: 350px; width: 100%;"></div>
        </div>
        <div>
          <div id="lineChart" style="height: 350px; width: 100%;"></div>
        </div>

      </el-col>
    </el-row>
  </div>
</template>

<script>

import { getWorkUnitTrees } from '@/api/ems/base/baseWorkUnit'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { comparativeAnalysisReport } from '@//api/ems/report/reportPort.js'
import { parseTime } from '@//utils/ruoyi'
import * as echarts from 'echarts'

export default {
  name: 'ComparativeAnalysisReport',
  components: {
    Treeselect
    // Chart 不再注册
  }, data() {
    return {
      monitorInfoOptions: [],
      workUnitOptions: [],
      workUnitName: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计计量信息表格数据
      monitorWorkUnitList: [],
      daterangeCollectTime: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      dynamicTags: [],
      queryParams: {
        monitorCode: null,
        workUnitCode: null,
        monitorStatus: null,
        workUnitCodeList: null,
        monitorType: 2,
        dateType: 10
      },
      // 表单参数
      form: {},
      workUnitProps: {
        children: 'children',
        label: 'label'
      },
      dateTypeList: [
        { dateTypeCode: 10, dateTypeName: '日' },
        { dateTypeCode: 7, dateTypeName: '月' },
        { dateTypeCode: 4, dateTypeName: '年' }
      ],
      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: `仪表值(kwh)`, visible: true },
        { key: 6, label: `价格`, visible: true }
      ],
      barChartOption: {
        title: {
          text: '耗量柱状图'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['耗量']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '耗量',
          type: 'bar',
          data: []
        }]
      },
      lineChartOption: {
        title: {
          text: '耗量折线图'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['耗量']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '耗量',
          type: 'line',
          data: []
        }]
      }
    }
  },
  created() {
    // 其余初始化逻辑
    const nowDate = parseTime(new Date(), '{y}-{m}-{d}')
    this.daterangeCollectTime[0] = nowDate
    this.daterangeCollectTime[1] = nowDate
    this.getWorkUnitTrees()
  },
  mounted() {
    this.initCharts()
  },
  watch: {
    // 根据名称筛选部门树
    workUnitName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 转换统计单元信息数据结构 */
    workUnitOptionsNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id2: node.workUnitCode,
        label2: node.workUnitName,
        children2: node.children
      }
    },
    /** 查询计量设备下拉树结构 */
    getWorkUnitTrees() {
      getWorkUnitTrees().then(response => {
        this.workUnitOptions = []
        this.workUnitOptions = JSON.parse(JSON.stringify(response.data).replaceAll('id', 'id2').replaceAll('code', 'id'))
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.queryParams.workUnitCode = data.id;
      //
    },
    handleTreeCheck(data) {
      const isExisting = this.dynamicTags.some(item => data.id === item.value)
      if (isExisting) {
        const index = this.dynamicTags.findIndex(item => data.id === item.value)
        if (index !== -1) {
          this.dynamicTags.splice(index, 1)
        }
      } else {
        this.dynamicTags.push({ label: data.label, value: data.id })
      }
      this.handleQuery()
    },
    //删除左上头部的tag
    handleClose(item) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(item), 1)
      console.log('handleClose:', this.dynamicTags)

      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList(true)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.workUnitCode = null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.objId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 渲染柱状图
    renderBarChart(option) {
      const barDom = document.getElementById('barChart')
      if (barDom) {
        const barChart = echarts.init(barDom)
        barChart.setOption(option)
        window.addEventListener('resize', () => barChart.resize())
      }
    },
    // 渲染折线图
    renderLineChart(option) {
      const lineDom = document.getElementById('lineChart')
      if (lineDom) {
        const lineChart = echarts.init(lineDom)
        lineChart.setOption(option)
        window.addEventListener('resize', () => lineChart.resize())
      }
    },
    getChartOption({ title, deviceNames, times, series }) {
      return {
        title: { text: title },
        tooltip: { trigger: 'axis' },
        legend: { data: deviceNames },
        xAxis: { type: 'category', data: times },
        yAxis: { type: 'value' },
        series
      }
    },
    /** 查询统计计量信息列表 */
    getList(updateChart = false) {
      this.loading = true
      this.queryParams.beginCollectTime = null
      this.queryParams.endCollectTime = null
      if (this.daterangeCollectTime != null && this.daterangeCollectTime !== '') {
        this.queryParams.beginCollectTime = this.daterangeCollectTime[0]
        this.queryParams.endCollectTime = this.daterangeCollectTime[1]
      }

      const valueList = this.dynamicTags.map(item => item.value)
      this.queryParams.workUnitCodeList = valueList.toString()

      comparativeAnalysisReport(this.queryParams).then(response => {
        // 表格数据
        this.monitorWorkUnitList = response.rows || []
        this.total = response.total || 0
        this.loading = false
        // 图表数据
        if (updateChart && response.data) {
          const { deviceNames, times, seriesBar, seriesLine } = response.data
          const barOption = this.getChartOption({
            title: '耗量对比分析',
            deviceNames,
            times,
            series: seriesBar
          })
          const lineOption = this.getChartOption({
            title: '能耗曲线',
            deviceNames,
            times,
            series: seriesLine
          })
          this.renderBarChart(barOption)
          this.renderLineChart(lineOption)
        }
      })
    },
    // 初始化图表
    initCharts() {
      this.getList(true)
    }
  }
}
</script>
