<template>
  <div class="page-panel">
    <div class="left-panel">
      <mini-map ref="minimap" layerControl projectList partsCheck>
        <template slot="topBar">
          <div @click="viewCurve()">监测查看</div>
          <thematic-map></thematic-map>
        </template>
      </mini-map>
    </div>
    <div class="right-panel">
      <div class="head-title line">评估结果</div>
      <div class="chart-panel">
        <div class="chart-box" style="padding-right:20px">
          <div class="chart-title">
            <span style="color:#2d74e7">管网破损：</span>
            <span v-if="pipeBroken">
              <span style="color:#f59421;font-size:16px;">{{pipeBroken.monitor||0}}</span>
              个监测点发现
              <span style="color:#f59421;font-size:16px;">{{pipeBroken.length.toFixed(3)||0}}</span>
              公里排水管网存在此隐患
            </span>
            <span v-else>暂未发现</span>
          </div>
          <div class="chart" ref="chart1">
            <img src="@/assets/icon/null.png" alt="暂无数据" style="width:100px;" />
          </div>
        </div>
        <div class="chart-box" style="padding-left:20px">
          <div class="chart-title">
            <span style="color:#2d74e7">雨污混接：</span>
            <span v-if="rainHybrid">
              <span style="color:#f59421;font-size:16px;">{{rainHybrid.monitor||0}}</span>
              个监测点发现
              <span style="color:#f59421;font-size:16px;">{{rainHybrid.length.toFixed(3)||0}}</span>
              公里排水管网存在此隐患
            </span>
            <span v-else>暂未发现</span>
          </div>
          <div class="chart" ref="chart2">
            <img src="@/assets/icon/null.png" alt="暂无数据" style="width:100px;" />
          </div>
        </div>
      </div>
      <div class="middle-box">
        <div class="head-title">
          <span>监测点</span>
          <span style="position: absolute;right: 80px;">
            <el-checkbox-group v-model="checkList" @change="getHiddenDangerAnalyse()" class="site-type-list">
              <el-checkbox label="1">发现管网破损（{{pipeBroken.monitor || 0}}）</el-checkbox>
              <el-checkbox label="4">发现雨污混接（{{rainHybrid.monitor || 0}}）</el-checkbox>
              <!-- <el-checkbox label="2,3">其他监测点（{{otherSiteCount || 0}}）</el-checkbox> -->
            </el-checkbox-group>
          </span>
        </div>
        <el-table :data="tableData1" style="width: 100%" stripe :header-cell-style="{ background: 'rgba(45, 116, 231,0.2)', 
      color: '#333333', height: '40px', textAlign: 'center' }" height="240px">
          <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="deviceTypeName" label="监测类型" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="siteName" label="监测点" align="center" show-overflow-tooltip>
            <template slot-scope="{row}">
              <el-button type="text" style="padding:0" @click="locationSite(row)">{{row.siteName}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="upstreamMonitor" label="上游监测点" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="wellName" label="关联检查井" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="hiddenDangerType" label="发现隐患类型" align="center"></el-table-column>
          <el-table-column prop="hiddenDangerTime" label="发现隐患时间" align="center"></el-table-column>
          <el-table-column prop="pipeCount" label="关联管网" align="center" show-overflow-tooltip>
            <template slot-scope="{row}">
              <el-button type="text" style="padding:0" @click="locationPipe(row)">{{row.pipeCount}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom-box">
        <el-tabs v-model="activeName">
          <el-tab-pane label="改造工作量" name="first">
            <el-table :data="tableData2" class="cust-table" style="width: 100%;margin-top:20px" :header-cell-style="{ background: '#f5f5f5', 
      color: '#333333', height: '30px',padding:'6px 0', textAlign: 'center' }" height="260px">
              <template slot="empty">
                <img src="@/assets/icon/null.png" alt="暂无数据" style="width:100px" />
              </template>
              <el-table-column prop="remouldPriority" label="工作优先级" align="center"></el-table-column>
              <el-table-column prop="drainageType" label="排水类型" align="center"></el-table-column>
              <el-table-column prop="pipelineLevel" label="管网等级" align="center"></el-table-column>
              <el-table-column label="路径" align="center">
                <el-table-column prop="leDn" label="小于DN400" align="center"></el-table-column>
                <el-table-column prop="eqDn" label="DN400~DN800" align="center"></el-table-column>
                <el-table-column prop="gtDn" label="大于DN800" align="center"></el-table-column>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="监测点告警情况" name="second">
            <el-form ref="form" :model="form" :inline="true" label-width="auto" size="small" style="margin:10px 0">
              <el-form-item label="监测点" label-width="60px" style="margin:0">
                <el-select v-model="form.siteId" filterable placeholder="选择站点" clearable>
                  <el-option v-for="(item,index) in siteOption" :key="index" :label="item.siteName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="降雨量" label-width="60px" style="margin:0">
                <el-select v-model="form.dailyRainfall" placeholder="请选择" style="width:150px" clearable>
                  <el-option v-for="(item,index) in rainFallOptions" :key="index" :label="item.notes" :value="item.codeValue"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="隐患类型" label-width="70px" style="margin:0 0 10px 0">
                <el-select v-model="form.hiddenDangerType" placeholder="请选择" style="width:150px" clearable>
                  <el-option v-for="(item,index) in dangerTypes" :key="index" :label="item.notes" :value="item.codeValue"></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="是否最新数据" label-width="100px" style="margin:0 0 10px 0">
                <el-select v-model="form.isNew" placeholder="请选择" style="width:150px" clearable>
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="日期范围" style="margin:0">
                <el-date-picker v-model="form.date" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable style="width:260px">
                </el-date-picker>
              </el-form-item> -->
              <el-form-item label-width="20px" style="margin:0">
                <el-button type="primary" @click="queryWarningPage()">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="tableData3" style="width: 100%" :header-cell-style="{ background: 'rgba(45, 116, 231,0.2)', 
      color: '#333333', height: '40px', textAlign: 'center' }" height="calc(100% - 74px)">
              <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="monitorDate" label="监测日期" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="siteName" label="监测点" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="dailyRainfall" label="日降雨量" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="hiddenDangerType" label="隐患类型" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="warningCause" label="告警原因" align="center" width="200" show-overflow-tooltip></el-table-column>
              <el-table-column prop="analyseDate" label="告警时间" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column label="监测曲线" align="center">
                <template slot-scope="{row}">
                  <el-button type="text" style="padding:0" @click="viewCurve(row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination" style="padding-top:10px">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.current" :page-sizes="[100, 200, 300, 400]" :page-size="pagination.size"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
              </el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 监测曲线 -->
    <historyCurve ref="historyCurve"></historyCurve>
  </div>
</template>

<script>
import miniMap from '@/views/widgets/miniMap/index.vue'
import moniterSee from '@/views/spectrum/reform/monitorSee/index.vue'
import thematicMap from '@/views/widgets/thematicMap/index.vue'
import historyCurve from '@/views/spectrum/common/historyCurve/index'
import * as echarts from 'echarts'

import {
  getAsessmentConclusion,
  getHiddenDangerAnalyse,
  getWarningPage,
  getRemouldWorkload,
  getHiddenDangerCount,
  getAssPipeList
} from '@/views/spectrum/reform/api/api'

import { getSites } from '@/views/spectrum/dynamicMonitor/api/api'
import { fetchDictionary } from '@/api/common/index'

import { getSiteIcon } from '@/views/spectrum/common/siteIcon/siteIcon' // 站点图标
export default {
  components: {
    miniMap,
    moniterSee,
    thematicMap,
    historyCurve
  },
  data() {
    return {
      form: { isNew: '1' },
      tableData: [],
      tableData1: [],
      tableData2: [],
      tableData3: [],
      checkList: [],
      dangerTypes: [],
      activeName: 'first',
      moniterVisible: false,
      siteOption: [],
      rainFallOptions: [],
      pagination: { current: 1, size: 100, total: 0 },
      pipeBroken: { length: 0, monitor: 0 },
      rainHybrid: { length: 0, monitor: 0 },
      otherSiteCount: 0
    }
  },
  async mounted() {
    this.getSites()
    await this.getRainFall()
    await this.getDangerTypes()
    this.getRemouldWorkload()
    this.getHiddenDangerAnalyse()
    this.getAsessmentConclusion()
    this.getHiddenDangerCount()
    this.queryWarningPage()
  },
  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
        }
      })
    },
    /**
    * 获取指标
    */
    async getRainFall() {
      const { result } = await fetchDictionary('DAILY_RAIN_FALL')
      this.rainFallOptions = result
    },
    /**
     * 获取隐患类型
     */
    async getDangerTypes() {
      const { result: dangerTypes } = await fetchDictionary('HIDDEN_DANGER_TYPE')
      this.dangerTypes = dangerTypes
    },
    /**
     * 隐患统计信息
     */
    getHiddenDangerCount() {
      getHiddenDangerCount().then((res) => {
        if (res.code != 1) return
        const { result } = res
        let otherSiteCount = result['总监测点数量'] || 0
        for (const key in result) {
          if (key != '总监测点数量' && key != '管网破损' && key != '雨污混接')
            otherSiteCount -= result[key]
        }
        if (otherSiteCount >= 0) this.otherSiteCount = otherSiteCount
      })
    },
    /**
     * 查询监测点
     */
    getHiddenDangerAnalyse() {
      let params = ''
      if(this.checkList.length==0) params = '1,4';
      else params = this.checkList.join(',')
      getHiddenDangerAnalyse({ hiddenDangerType: params }).then((res) => {
        if (res.code == 1) {
          let dataList = res.result
          this.tableData1 = dataList
          let points = dataList.filter((item, index, self) => {
            return self.findIndex(el => el.monitorId == item.monitorId) === index
          })
          const _points = points.map(item => {
            return {
              x: item.longitude,
              y: item.latitude,
              icon: getSiteIcon(item, false)
            }
          })
          setTimeout(() => {
            this.$refs.minimap.addMarkers(_points)
          }, 200);
        }
      })
    },
    /**
     *监测点告警情况分页查询
     */
    getWarningPage() {
      let params = JSON.parse(JSON.stringify(this.pagination))
      if (this.form.siteId) params['id'] = this.form.siteId
      if (this.form.dailyRainfall) params['dailyRainfall'] = this.form.dailyRainfall
      if (this.form.date && this.form.date.length > 0) {
        params['monitorStartDate'] = this.$moment(this.form.date[0]).format('YYYY-MM-DD 00:00:00')
        params['monitorEndDate'] = this.$moment(this.form.date[1]).format('YYYY-MM-DD 23:59:59')
      }
      if (this.form.hiddenDangerType) params['hiddenDangerType'] = this.form.hiddenDangerType
      if (this.form.isNew) params['isNew'] = this.form.isNew
      getWarningPage(params).then((res) => {
        if (res.code == 1) {
          this.tableData3 = res.result.records
          this.pagination.total = res.result.total
        }
      })
    },
    /**
     * 搜索告警情况
     */
    queryWarningPage() {
      this.pagination.current = 1
      this.getWarningPage()
    },
    /**
     * 分页 改变每页条数
     */
    handleSizeChange(size) {
      this.pagination.size = size
      this.getWarningPage()
    },
    /**
     * 分页 改变当前页
     */
    handleCurrentChange(current) {
      this.pagination.current = current
      this.getWarningPage()
    },
    /**
     * 获取评估结果
     */
    getAsessmentConclusion() {
      getAsessmentConclusion().then((res) => {
        if (res.code == 1) {
          const pipeBroken = res.result.find((item) => {
            return item.type == '管网破损'
          })
          this.pipeBroken = pipeBroken && pipeBroken.map ? pipeBroken.map : { length: 0, monitor: 0 }
          const chartsData = pipeBroken && pipeBroken.echartsBar ? pipeBroken.echartsBar : null
          if (chartsData) {
            this.loadChart('chart1', chartsData.xaxisData, chartsData.seriesData)
          }

          const rainHybrid = res.result.find((item) => {
            return item.type == '雨污混接'
          })
          this.rainHybrid = rainHybrid && rainHybrid.map ? rainHybrid.map : { length: 0, monitor: 0 }
          const chartsData2 = rainHybrid && rainHybrid.echartsBar ? rainHybrid.echartsBar : null
          if (chartsData2) {
            this.loadChart('chart2', chartsData2.xaxisData, chartsData2.seriesData)
          }
        }
      })
    },
    /**
     * 获取改造工作量
     */
    getRemouldWorkload() {
      getRemouldWorkload().then((res) => {
        if (res.code == 1) {
          this.tableData2 = res.result
        }
      })
    },
    loadChart(domeName, xAxis, seriesData) {
      let chartDom = this.$refs[domeName]
      let myChart = echarts.init(chartDom)
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        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',
            data: [2.0, 2.3],
            barWidth: 20,
            itemStyle: {
              normal: {
                color: (params) => {
                  var colorList = ['#2d74e7', '#02bdc9', '#cca272', '#74608f', '#d7a02b', '#c8ba23']
                  return colorList[params.dataIndex]
                }
              }
            }
          }
        ]
      }
      myChart.clear()
      option && myChart.setOption(option)
    },
    /**
     * 定位监测点
     */
    locationSite(row) {
      const { latitude, longitude } = row;
      this.$refs.minimap.addMarker([longitude, latitude])
    },
    /**
     * 关联管网定位
     */
    locationPipe(row) {
      const { monitorId } = row;
      if (!monitorId) {
        this.$message.info('未知站点！');
        return
      }
      getAssPipeList(monitorId).then(res => {
        if (res.code != 1) return
        const { result: pipes } = res;
        if (!pipes) {
          this.$message.error('未获取到管网数据！');
          return;
        }
        const pipeFeatures = pipes.map(item => {
          return {
            startCoordinates: [item.longitude, item.latitude],
            endCoordinates: [item.longitude2, item.latitude2]
          }
        })
        this.$refs.minimap.addPipeLines(pipeFeatures)
      })
    },
    /**
     * 曲线查看
     */
    viewCurve(row = null) {
      const siteId = row ? row.id : null;
      const options = row ? {
        beginDate: row.beginDate,
        endDate: row.monitorDate,
        targets: [row.checkCode]
      } : undefined
      // 查看历史曲线
      this.$refs.historyCurve.show(siteId, options)
    },
    moniterClose() {
      this.moniterVisible = false
    }
  }
}
</script>

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