<template>
  <div class="page-panel">
    <div class="params-panel">
      <div class="head-title">显示设置</div>
      <el-form ref="form" :model="form" label-width="auto" size="small">
        <!-- <el-form-item label="分析范围" label-width="68px">
          <el-radio-group v-model="form.radio">
            <div class="extent-item" style="margin-bottom:15px;margin-top: 10px;">
              <el-radio :label="1">地图范围</el-radio>
            </div>
            <div class="extent-item">
              <el-radio :label="2">自定义范围</el-radio>
              <el-button type="text" class="iconfont icontyhz1" title="圆"></el-button>
              <el-button type="text" class="iconfont iconjx" title="矩形"></el-button>
              <el-button type="text" class="iconfont icondbxhz" title="多边形"></el-button>
            </div>
            <div class="extent-item">
              <el-radio :label="3">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    排水分区
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="a">排水分区</el-dropdown-item>
                    <el-dropdown-item command="b">行政区</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-radio>
              <el-select v-model="model" placeholder="" style="width:125px">
                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="监测站点">
          <el-select v-model="sites" ref="sitesSelect" value-key="id" filterable multiple collapse-tags placeholder="选择站点" style="width: 100%" clearable @change="selectSites" @visible-change="sitesSelectBlur">
            <el-option v-for="(item, index) in siteOptions" :key="index" :label="item.siteName" :value="item"></el-option>
          </el-select>
          <!-- <el-button type="warning">图上选择</el-button> -->
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" style="width:100%" @click="execute">分析</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 结果 -->
    <div class="result-box">
      <div class="head-title">周边管网情况</div>
      <div class="res-items">
        <div class="res-item" @click="showPipe(1)">
          <span>历史管网</span>
          <span v-cloak>{{aroundPipe.oldPipe}}</span>
        </div>
        <!-- <div class="res-item">
          <span>现状管网</span>
          <span>13.24km|32个</span>
        </div> -->
        <div class="res-item" @click="showPipe(2)">
          <span>新建管网</span>
          <span v-cloak>{{aroundPipe.newPipe}}</span>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: 'rgba(45, 116, 231,0.2)', 
      color: '#333333', height: '40px', textAlign: 'center' }" height="200px">
        <template slot="empty">
          <img src="@/assets/icon/null.png" alt="暂无数据" style="width:100px" />
        </template>
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column prop="pipeId" label="新建管网工程" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="completionTime" label="竣工时间" align="center" show-overflow-tooltip></el-table-column>
      </el-table>
      <!-- <div class="head-title">
        <span>缺陷数量统计</span>
        <span type="text" class="link-btn" @click="defectView()">查看详情</span>
      </div>
      <div class="chart-box" id="pipeChart"></div> -->
      <div class="head-title">
        <span>水质监测情况</span>
        <!-- <span type="text" class="link-btn" @click="monitorView()">查看详情</span> -->
        <el-select v-model="targets" value-key="targetCode" filterable multiple collapse-tags placeholder="选择指标" style="width:200px;float:right" size="mini" @change="selectTargets">
          <el-option v-for="(item,index) in targetOptions" :key="index" :label="item.targetName" :value="item"></el-option>
        </el-select>
      </div>
      <!-- <div class="chart-box" id="facilityChart"></div> -->
      <div class="chart-box" v-for="(item,index) in chartsData" :key="index" :ref="`chart_${item.targetCode}`"></div>
    </div>
  </div>
</template>

<script>
import { getSites } from '@/views/spectrum/dynamicMonitor/api/api'
import { getDetectzy, getSiteTargets, getSiteMonitorInfo } from '@/views/spectrum/reform/api/api'

import * as echarts from 'echarts'
import { getSiteIcon } from '@/views/spectrum/common/siteIcon/siteIcon' // 站点图标
export default {
  data() {
    return {
      form: {
        num: 200
      },
      tableData: [],
      siteOptions: [],
      targetOptions: [],
      sites: [],
      targets: [],
      aroundPipe: {
        oldPipe: '暂无管网信息',
        newPipe: '暂无管网信息',
        oldPipeArray: [],
        newPipeArray: []
      },
      pipeEntities: [],
      chartsData: [],
      _sites: []
    }
  },
  created() { },
  mounted() {
    this.getSites()
    // this.loadPipeLineChart()
    // this.loadFacilityChart()
  },
  destroyed() {
    this.clearMapShow();
  },
  methods: {
    /**
     * 获取站点
     */
    getSites() {
      getSites({ projectId: this.$store.state.project.project.id, size: 1000 }).then((res) => {
        if (res.code && res.code == 1) {
          this.siteOptions = res.result.records
          // if (this.siteOption.length > 0) this.$set(this.form, 'siteId', this.siteOption[0].id)
        }
      })
    },
    /**
     * 获取周边管网情况
     */
    getDetectzy() {
      const siteIds = this.sites.map(item => { return item.id })
      getDetectzy({ siteIds: siteIds.join(',') }).then(res => {
        if (res.code == 1) {
          const result = res.result;
          if (Object.keys(result).length > 0) {
            const { "存量": oldPipe, "新建": newPipe, "列表": projList } = result;
            this.aroundPipe = {
              oldPipe: `${oldPipe.pipeLength > 1 ?
                oldPipe.pipeLength.toFixed(2) + 'km' :
                (oldPipe.pipeLength * 1000).toFixed(2) + 'm'} | ${oldPipe.num}个`,
              newPipe: `${newPipe.pipeLength > 1 ?
                newPipe.pipeLength.toFixed(2) + 'km' :
                (newPipe.pipeLength * 1000).toFixed(2) + 'm'} | ${newPipe.num}个`,
              oldPipeArray: oldPipe.detectzyVo,
              newPipeArray: newPipe.detectzyVo
            }
            this.tableData = projList;
          } else {
            this.aroundPipe = {
              oldPipe: `暂无管网信息`,
              newPipe: `暂无管网信息`,
              oldPipeArray: [],
              newPipeArray: []
            }
          }
        }
      })
    },
    /**
     * 获取站点指标
     */
    getSiteTargets() {
      const siteIds = this.sites.map(item => { return item.id })
      getSiteTargets({ siteIds: siteIds.join(',') }).then(res => {
        if (res.code == 1) {
          this.targetOptions = res.result;
          if (this.targetOptions.length == 0) return;
          this.targets = [this.targetOptions[0]];
        }
      })
    },
    /**
     * 获取水质监测1情况曲线数据
     */
    getSiteMonitorInfo() {
      // 站点
      const siteInfoDtos = this.sites.map(item => {
        return {
          siteId: item.id,
          siteName: item.siteName
        }
      })
      // 指标
      const checkCodes = this.targets.map(item => {
        return {
          checkCode: item.targetCode,
          codeName: item.targetName
        }
      })
      const data = {
        checkCodes: checkCodes,
        siteInfoDtos: siteInfoDtos
      }
      getSiteMonitorInfo(data).then(res => {
        console.log('---->88899', res);
        if (res.code == 1) {
          const object = res.result;
          let newObj = {}
          for (const key in object) {
            object[key].forEach(item => {
              if (item.siteAndIndicateVo.monthData.length > 0) {
                const monitorInfo = {
                  siteName: item.name,
                  data: item.siteAndIndicateVo.monthData.map(v => { return v.avgValue })
                }
                if (newObj.hasOwnProperty(item.checkCode)) {
                  newObj[item.checkCode].monitorInfo.push(monitorInfo)
                } else {
                  newObj[item.checkCode] = {
                    targetName: item.codeName,
                    targetCode: item.checkCode,
                    xAxis: item.siteAndIndicateVo.monthData.map(v => { return v.xposition }),
                    monitorInfo: [monitorInfo]
                  }
                }
              }
            });
          }
          this.chartsData = Object.values(newObj)

          this.$nextTick(() => {
            this.chartsData.forEach(item => {
              this.loadFacilityChart(`chart_${item.targetCode}`, item.targetName, item.xAxis, item.monitorInfo)
            });
          })
        }
      })
    },
    /**
     * 选择指标
     */
    selectTargets(targets) {
      console.log('选择指标：', targets);
    },
    /**
     * 选择站点
     */
    selectSites(sites) {
      if (sites.length > 0) this.getSiteTargets();
      else {
        this.targets = []
        this.chartsData = []
      }
    },
    /**
     * 站点选择完成显示站点
     */
    sitesSelectBlur(visible) {
      if (visible) return
      const sites = this.sites;
      const viewer = window.viewer;
      this.clearMapShow();
      sites.forEach(site => {
        console.log(site);
        const position = Cesium.Cartesian3.fromDegrees(site.longitude, site.latitude, 0)
        let entity = new Cesium.Entity({
          position: position,
          billboard: {
            image: getSiteIcon(site),
            width: 48,
            height: 70,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            eyeOffset: Cesium.Cartesian3.ZERO,
            disableDepthTestDistance: Number.POSITIVE_INFINITY
          }
        })
        this._sites.push(entity)
        viewer.entities.add(entity)
        viewer.flyTo(_sites)
      });
    },
    /**
     * 分析
     */
    execute() {
      if (this.sites.length == 0) {
        this.$message.warning("还未选择监测站点！")
        return
      }
      this.clearMapShow();
      this.getDetectzy()
      this.getSiteMonitorInfo()
    },
    /**
     * 地图显示管网
     */
    showPipe(type) {
      const viewer = window.viewer;
      const { oldPipeArray, newPipeArray } = this.aroundPipe;
      let pipeArray = []
      if (type == 1) pipeArray = oldPipeArray;
      else pipeArray = newPipeArray;
      this.clearMapShow();
      // 向地图中添加管线
      for (let index = 0; index < pipeArray.length; index++) {
        const pipe = pipeArray[index];
        let entity = new Cesium.Entity({
          id: type == 1 ? `ls_${index}` : `xj_${index}`,
          name: '管线',
          show: true,
          polyline: new Cesium.PolylineGraphics({
            positions: [
              new Cesium.Cartesian3.fromDegrees(pipe.longitude, pipe.latitude),
              new Cesium.Cartesian3.fromDegrees(pipe.longitude2, pipe.latitude2)
            ],
            width: 8,
            material: type == 1 ? Cesium.Color.RED : Cesium.Color.GREEN, //红色表示历史，绿色新建
            clampToGround: true
          })
        })
        this.pipeEntities.push(entity)
        viewer.entities.add(entity)
      }
      viewer.flyTo(this.pipeEntities[this.pipeEntities.length - 1], { duration: 3 })
    },
    /**
     * 清除地图显示
     */
    clearMapShow() {
      const viewer = window.viewer;
      this.pipeEntities.forEach(entity => {
        viewer.entities.remove(entity)
      });
      this._sites.forEach(_s => {
        viewer.entities.remove(_s)
      });
    },
    // loadPipeLineChart() {
    //   let chartDom = document.getElementById('pipeChart')
    //   let myChart = echarts.init(chartDom)
    //   let option = {
    //     tooltip: {
    //       trigger: 'axis',
    //       axisPointer: {
    //         type: 'shadow'
    //       }
    //     },
    //     legend: {
    //       data: ['jgqx', 'gnqx'],
    //       orient: 'horizontal',
    //       left: 'center',
    //       itemWidth: 10,
    //       itemHeight: 10,
    //       bottom: 0,
    //       textStyle: {
    //         color: '#959595',
    //         fontSize: 11,
    //         fontWeight: '500'
    //       }
    //     },
    //     grid: {
    //       top: '8%',
    //       left: '3%',
    //       right: '4%',
    //       bottom: '15%',
    //       containLabel: true
    //     },
    //     xAxis: [
    //       {
    //         type: 'category',
    //         data: ['历史管网', '现状管网', '新建管网'],
    //         axisTick: {
    //           alignWithLabel: true
    //         }
    //       }
    //     ],
    //     yAxis: [
    //       {
    //         type: 'value'
    //       }
    //     ],
    //     series: [
    //       {
    //         name: 'jgqx',
    //         type: 'bar',
    //         barWidth: '30%',
    //         data: [90, 160, 20],
    //         itemStyle: {
    //           color: '#3aa1ff'
    //         }
    //       },
    //       {
    //         name: 'gnqx',
    //         type: 'bar',
    //         barWidth: '30%',
    //         data: [20, 80, 9],
    //         itemStyle: {
    //           color: '#4ecb73'
    //         }
    //       }
    //     ]
    //   }
    //   option && myChart.setOption(option)
    // },
    loadFacilityChart(dom, title, xAxis, seriesData) {
      let legendData = []
      let series = []
      seriesData.forEach(item => {
        legendData.push(item.siteName);
        series.push({ name: item.siteName, type: 'line', smooth: true, data: item.data })
      });
      let chartDom = this.$refs[dom][0];
      let myChart = echarts.init(chartDom);
      let option = {
        title: {
          text: title,
          textStyle: {
            fontSize: '14'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          type: 'scroll',
          data: legendData,
          orient: 'horizontal',
          left: 'center',
          // itemHeight: 10,
          top: 27,
          textStyle: {
            color: '#959595',
            fontSize: 11,
            fontWeight: '500'
          }
        },
        grid: {
          top: '25%',
          left: '3%',
          right: '4%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xAxis,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: series
      }
      myChart.clear()
      option && myChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
@import './css.scss';
</style>
