<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="站点选择">
          <el-select v-model="site" value-key="id" filterable placeholder="选择站点" style="width: 100%" clearable @change="siteSelectChange">
            <el-option v-for="(item, index) in siteOption" :key="index" :label="item.siteName" :value="item"></el-option>
          </el-select>
          <!-- <el-button type="warning">图上选择</el-button> -->
        </el-form-item>
        <el-form-item label="追踪距离">
          <el-input-number v-model="form.num" controls-position="right" :min="1" :max="10000" style="width: 158px" :disabled="noDistance" @blur="inputNumber"></el-input-number>
          <el-checkbox v-model="noDistance">不限距离</el-checkbox>
        </el-form-item>
        <el-form-item label="追踪方式">
          <el-checkbox-group v-model="trackType" :min="1" class="track_type">
            <el-checkbox :label="0">上游追踪</el-checkbox>
            <el-checkbox :label="1">下游追踪</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" style="width: 100%" @click="getConnectivity()">分析</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">
          <span>连通管线</span>
          <span>100.89m</span>
        </div>
        <div class="res-item">
          <span>连通排水设施</span>
          <span>43个</span>
        </div>
        <div class="res-item">
          <span>连通监测设备</span>
          <span>9个</span>
        </div>
      </div> -->
      <div class="head-title">管线</div>
      <!-- <div class="chart-box" id="pipeChart"></div> -->
      <div class="chart-box">
        <el-tabs v-model="pipeType">
          <el-tab-pane :label="`上游管线（${upPipes.length}个）`" name="上游管线">
            <table-widget :tableData="upPipes" @row-dblclick="lineRowClick"></table-widget>
          </el-tab-pane>
          <el-tab-pane :label="`下游管线（${downPipes.length}个）`" name="下游管线">
            <table-widget :tableData="downPipes" @row-dblclick="lineRowClick"></table-widget>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="head-title">排水设施</div>
      <!-- <div class="chart-box" id="facilityChart"></div> -->
      <div class="chart-box">
        <el-tabs v-model="pointType">
          <el-tab-pane :label="`上游管点（${upNodes.length}个）`" name="上游管点">
            <table-widget :tableData="upNodes" type="nodes" @row-dblclick="pointRowClick"></table-widget>
          </el-tab-pane>
          <el-tab-pane :label="`下游管点（${downNodes.length}个）`" name="下游管点">
            <table-widget :tableData="downNodes" type="nodes" @row-dblclick="pointRowClick"></table-widget>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="head-title">
        <span>监测设备</span>
        <span type="text" class="link-btn" @click="monitorView()">监测查看</span>
      </div>
      <el-table :data="siteData" style="width: 100%" :header-cell-style="{
          background: 'rgba(45, 116, 231,0.2)',
          color: '#333333',
          height: '35px',
          textAlign: 'center'
        }" :cell-style="{ padding: '5px 0' }" height="200px">
        <template slot="empty">
          <img src="@/assets/icon/null.png" alt="暂无数据" style="width: 100px" />
        </template>
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="siteName" label="监测点名称" align="center"></el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型" align="center"></el-table-column>
      </el-table>
    </div>
    <!-- 监测曲线 -->
    <historyCurve ref="historyCurve"></historyCurve>
  </div>
</template>

<script>
import { getSites } from '@/views/spectrum/dynamicMonitor/api/api'
import { getConnectivity } from '@/views/spectrum/reform/api/api'

import historyCurve from '@/views/spectrum/common/historyCurve/index'
import tableWidget from './tableWidget/index.vue'

import * as echarts from 'echarts'

import PipeQueryHelper from '@/utils/mapCommon/PipeQueryHelper'
export default {
  components: {
    historyCurve,
    tableWidget
  },
  data() {
    return {
      site: null,
      trackType: [0],
      form: {
        num: 200
      },
      siteData: [],
      pipeType: '上游管线',
      pointType: '上游管点',
      noDistance: true,
      siteOption: [],
      upPipes: [],
      upNodes: [],
      downPipes: [],
      downNodes: [],
      resultEntities: [] // 分析结果地图实例
    }
  },
  created() { },
  mounted() {
    this.getSites()
    // this.loadPipeLineChart()
    // this.loadFacilityChart()
  },
  computed: {
    AppX() {
      return this.$store.getters.AppX
    }
  },
  destroyed() {
    this.clearMapShow()
  },
  methods: {
    /**
     * 获取站点
     */
    getSites() {
      getSites({ projectId: this.$store.state.project.project.id, size: 1000 }).then((res) => {
        if (res.code && res.code == 1) {
          this.siteOption = res.result.records
          // if (this.siteOption.length > 0) this.$set(this.form, 'siteId', this.siteOption[0].id)
        }
      })
    },
    /**
     * 站点选择
     */
    siteSelectChange(site) {
      console.log('site站点', site)
      Object.assign(this.$data, this.$options.data())
      this.site = site
    },
    /**
     * 获取连通性分析结果
     */
    getConnectivity() {
      if (!this.site) {
        this.$message.warning("还未选择监测站点")
        return
      }
      const { drainageId, layerName } = this.site
      if (!drainageId || !layerName) {
        this.$message.error("该站点还未关联谱排水设施！")
        return
      }
      // 连通性分析参数
      let params = {
        prjId: this.$store.state.project.project.id,
        smid: drainageId,
        tablename: layerName.replace(/NODE/g, 'PIPE'),
        tablename2: layerName,
        mode: this.trackType.join(',')
      }
      if (!this.noDistance) params['distance'] = this.form.num
      getConnectivity(params).then((res) => {
        if (res.code == 1) {
          const pipeData = res.result.pipeData || []
          const nodeData = res.result.nodeData || []
          this.siteData = res.result.siteData || []
          // 上游管线
          this.upPipes = pipeData.filter(item => { return item.model == '上游' })
          // 下游管线
          this.downPipes = pipeData.filter(item => { return item.model == '下游' })
          // 上游管点
          this.upNodes = nodeData.filter(item => { return item.model == '上游' })
          // 下游管点
          this.downNodes = nodeData.filter(item => { return item.model == '下游' })
          // 上游管线smid
          const upPipeSmidArray = this.upPipes.map(item => { return item.smid })
          // 下游管线smid
          const downPipeSmidArray = this.downPipes.map(item => { return item.smid })
          // 上游管点smid
          const upNodeSmidArray = this.upNodes.map(item => { return item.smid })
          // 上游管点smid
          const downNodeSmidArray = this.downNodes.map(item => { return item.smid })

          this.clearMapShow()

          const { layerName: nodeDataSetName } = this.site
          const pipeDataSetName = nodeDataSetName.replace(/NODE/g, 'PIPE')
          // 查询上游管线空间数据
          this.queryMap(upPipeSmidArray, pipeDataSetName, response => { this.showLine(response, 0) })
          // 查询下游管线空间数据
          this.queryMap(downPipeSmidArray, pipeDataSetName, response => { this.showLine(response, 1) })
          // 查询上游管点空间数据
          this.queryMap(upNodeSmidArray, nodeDataSetName, response => { this.showPoint(response, 0) })
          // 查询下游管点空间数据
          this.queryMap(downNodeSmidArray, nodeDataSetName, response => { this.showPoint(response, 1) })
        }
      })
    },
    /**
     * 距离数据检查
     */
    inputNumber() {
      if (!this.form.num) this.$set(this.form, "num", 200)
    },
    // loadPipeLineChart() {
    //   let chartDom = document.getElementById('pipeChart')
    //   let myChart = echarts.init(chartDom)
    //   let option = {
    //     tooltip: {
    //       trigger: 'item'
    //     },
    //     legend: {
    //       orient: 'horizontal',
    //       left: 'center',
    //       itemWidth: 10,
    //       itemHeight: 10,
    //       icon: 'circle',
    //       bottom: 2,
    //       textStyle: {
    //         color: '#959595',
    //         fontSize: 11,
    //         fontWeight: '500'
    //       }
    //     },
    //     series: [
    //       {
    //         name: '管线',
    //         type: 'pie',
    //         radius: '55%',
    //         itemStyle: {
    //           borderColor: '#fff',
    //           normal: {
    //             color: function (colors) {
    //               var colorList = ['#4ecb73', '#3aa1ff', '#36cbcb', '#ebb563', '#e97a20', '#237cc0']
    //               return colorList[colors.dataIndex]
    //             },
    //             label: {
    //               show: true,
    //               formatter: '{b}:{d}%'
    //             }
    //           }
    //         },
    //         center: ['50%', '40%'],
    //         data: [
    //           { value: 1048, name: '雨水' },
    //           { value: 580, name: '污水' },
    //           { value: 735, name: '雨污合流' }
    //         ]
    //       }
    //     ]
    //   }
    //   option && myChart.setOption(option)
    // },
    // loadFacilityChart() {
    //   let chartDom = document.getElementById('facilityChart')
    //   let myChart = echarts.init(chartDom)
    //   let option = {
    //     tooltip: {
    //       trigger: 'axis',
    //       axisPointer: {
    //         type: 'shadow'
    //       }
    //     },
    //     grid: {
    //       top: '8%',
    //       left: '3%',
    //       right: '4%',
    //       bottom: '3%',
    //       containLabel: true
    //     },
    //     xAxis: [
    //       {
    //         type: 'category',
    //         data: ['阀门', '排放口', '污水厂入口', '污水厂出口', '泵站'],
    //         axisTick: {
    //           alignWithLabel: true
    //         }
    //       }
    //     ],
    //     yAxis: [
    //       {
    //         type: 'value'
    //       }
    //     ],
    //     series: [
    //       {
    //         name: '排水设施',
    //         type: 'bar',
    //         barWidth: '60%',
    //         data: [90, 160, 200, 334, 390, 330, 220],
    //         itemStyle: {
    //           color: '#3aa1ff'
    //         }
    //       }
    //     ]
    //   }
    //   option && myChart.setOption(option)
    // },
    /**
     * 监测查看
     */
    monitorView() {
      if (this.site) this.$refs.historyCurve.show(this.site.id)
    },
    /**
     * 查询设施空间数据
     */
    queryMap(smidArray, dataSet, cellBack) {
      // 数据服务地址
      const URL = this.AppX.appConfig.gisResource.tiplayers.config.sjfw.url
      // 属性查询
      PipeQueryHelper.queryByAttribute({
        url: URL,
        datasetNames: [`sxgk:${dataSet}`],
        whereclause: `SMID in (${smidArray.join(',')})`,
        completed: cellBack,
        failed: (error) => {
          console.error('查询失败', error)
        }
      })
    },
    /**
     * 显示线要素
     *@param{type} 0上游，1下游
     */
    showLine(response, type) {
      const viewer = window.viewer
      const features = response.result.features
      for (let index = 0; index < features.length; index++) {
        const feature = features[index]
        const geometry = feature.geometry
        let entity = new Cesium.Entity({
          id: `line_${feature.fid}`,
          name: '管线',
          show: true,
          polyline: new Cesium.PolylineGraphics({
            positions: [
              new Cesium.Cartesian3.fromDegrees(geometry.components[0].x, geometry.components[0].y),
              new Cesium.Cartesian3.fromDegrees(geometry.components[1].x, geometry.components[1].y)
            ],
            width: 8,
            material: type == 0 ? Cesium.Color.RED : Cesium.Color.GREEN, //红色表示上游，绿色下游
            clampToGround: true
          })
        })
        this.resultEntities.push(entity)
        viewer.entities.add(entity)
      }
    },
    /**
     * 显示点要素
     * @param{type} 0上游，1下游
     */
    showPoint(response, type) {
      const { drainageId: smid } = this.site
      const viewer = window.viewer
      const features = response.result.features
      for (let index = 0; index < features.length; index++) {
        const feature = features[index]
        const geometry = feature.geometry
        let entity = new Cesium.Entity({
          id: `point_${feature.fid}`,
          name: '管点',
          show: true,
          position: Cesium.Cartesian3.fromDegrees(geometry.x, geometry.y),
          point: {
            pixelSize: 6, //点的大小
            color: type == 0 ? Cesium.Color.RED : Cesium.Color.GREEN, //红色表示上游，绿色下游
            outlineColor: Cesium.Color.YELLOW, //外圈颜色
            outlineWidth: 3, //外圈大小
            disableDepthTestDistance: Number.MAX_VALUE,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        this.resultEntities.push(entity)
        viewer.entities.add(entity)
        // 定位到站点关联的排水设施
        if (feature.fid == smid) {
          viewer.flyTo(viewer.entities.getById(`point_${feature.fid}`))
        }
      }
    },
    /**
     * 管线表格行双击
     */
    lineRowClick(row) {
      const viewer = window.viewer
      let entity = viewer.entities.getById(`line_${row.smid}`)
      viewer.flyTo(entity)
    },
    /**
     * 管点表格行双击
     */
    pointRowClick(row) {
      const viewer = window.viewer
      let entity = viewer.entities.getById(`point_${row.smid}`)
      viewer.flyTo(entity)
    },
    /**
     * 清除地图显示
     */
    clearMapShow() {
      this.resultEntities.forEach(entity => {
        viewer.entities.remove(entity)
      });
    }
  }
}
</script>

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