<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">评估结果</div>
      <div class="chart-panel">
        <div class="chart-box" style="padding:0 20px 0 10px;">
          <div style="width:100%;height:100%;background-color:#f9f9f9;overflow:hidden;padding:10px">
            <p style="margin:10px 0;color:#2d74e7;margin-top:50px">地下水入侵：</p>
            <p style="margin:10px 0;color:#3f3f3f;line-height:20px">雨水管网共布设{{allCount||'0'}}个监测点位，其中{{yhCount||'0'}}个监测点位发现地下水入侵隐患</p>
          </div>
        </div>
        <div class="chart-box" style="padding-left:20px" ref="chart1"></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="2">发现地下水入侵监测点（{{yhCount}}）</el-checkbox>
              <el-checkbox label="1,3,4">其他相关监测点（{{allCount - yhCount}}）</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="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="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" show-overflow-tooltip></el-table-column>
          <el-table-column prop="hiddenDangerTime" label="发现隐患时间" align="center" show-overflow-tooltip></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">
        <div class="head-title line">监测点告警情况</div>
        <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 0 10px 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 0 10px 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 0 10px 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 0 10px 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% - 51px)">
          <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="monitorDate" label="监测日期" align="center"></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"></el-table-column> -->
          <!-- <el-table-column prop="hiddenDangerType" label="隐患类型" align="center"></el-table-column> -->
          <el-table-column prop="warningCause" label="告警原因" align="center" width="300" 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>
      </div>
    </div>
    <historyCurve ref="historyCurve"></historyCurve>
  </div>
</template>

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

import {
  getReportCondision,
  getHiddenDangerCount,
  getWarningPage,
  getHiddenDangerAnalyse,
  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,
    historyCurve,
    thematicMap
  },
  data() {
    return {
      form: { isNew: '1' },
      tableData: [],
      tableData1: [],
      tableData2: [],
      tableData3: [],
      checkList: ['2'],
      dangerTypes: [],
      activeName: 'first',
      moniterVisible: false,
      allCount: 0,
      yhCount: 0,
      siteOption: [],
      rainFallOptions: [],
      pagination: { current: 1, size: 100, total: 0 }
    }
  },
  async mounted() {
    this.getSites()
    await this.getRainFall()
    await this.getDangerTypes()
    this.getHiddenDangerCount()
    this.getHiddenDangerAnalyse()
    this.getWarningPage()
    this.loadChart()
  },
  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
      if (this.dangerTypes.length > 0) this.$set(this.form, 'hiddenDangerType', '2')
    },
    /**
     * 按管网评估情况统计
     */
    loadChart() {
      let chartDom = this.$refs.chart1
      let myChart = echarts.init(chartDom)
      getReportCondision().then((res) => {
        if (res.code == 1) {
          let result = res.result
          let option = {
            tooltip: {
              trigger: 'item'
            },
            color: ['#15d0ea', '#f6b638'],
            series: [
              {
                name: '监测点',
                type: 'pie',
                radius: '70%',
                data: result,
                label: {
                  formatter: '{b} {c}个',
                  fontSize: 14,
                  fontWeight: 500
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          myChart.clear()
          option && myChart.setOption(option)
        }
      })
    },

    /**
     * 隐患统计信息
     */
    getHiddenDangerCount() {
      getHiddenDangerCount({ hiddenDangerType: '2' }).then((res) => {
        this.allCount = res.result['总监测点数量'] || 0
        this.yhCount = res.result['地下水入侵'] || 0
      })
    },
    /**
     *监测点告警情况分页查询
     */
    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()
    },
    /**
     * 查询监测点
     */
    getHiddenDangerAnalyse() {
      getHiddenDangerAnalyse({ hiddenDangerType: this.checkList.join(',') }).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);
        }
      })
    },
    /**
     * 定位监测点
     */
    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() { }
  }
}
</script>

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