<template>
  <div class="page-panel">
    <div class="left-panel">
      <mini-map layerControl projectList partsCheck>
        <template slot="topBar">
          <div @click="viewCurve()">监测查看</div>
          <thematic-map></thematic-map>
        </template>
      </mini-map>
      <!-- <transition name="el-zoom-in-bottom">
        <moniter-see ref="moniterSee" v-show="moniterVisible" @close="moniterClose()"></moniter-see>
      </transition> -->
    </div>
    <div class="right-panel">
      <div class="top-box">
        <div class="head-title">分析设置</div>
        <el-form ref="form" :model="form" size="small" label-width="100px">
          <el-row>
            <el-form-item label="工程名称">
              <el-select v-model="currentProject" filterable placeholder="选择方案" clearable style="width: 350px" @change="getProjectSchemeById" @clear="clearPlan()">
                <el-option v-for="(item, index) in projectScheme" :key="index" :label="item.projectName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row style="padding: 15px 10px 0 10px; background-color: #f1f2f6">
            <el-row>
              <el-col :span="12">
                <el-form-item label="工程名称">
                  <el-input v-model="form.projectName" placeholder="工程名称" style="width: 100%"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工程改造目标">
                  <el-input v-model="form.projectRemouldTarget" placeholder="改造目标" style="width: 100%"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 监测点选择 -->
            <el-row style="position: relative" v-for="(item, index) in siteGroups" :key="index">
              <el-button v-if="index == siteGroups.length - 1" type="text" class="row-btn" icon="el-icon-circle-plus-outline" @click="addSiteItem()"></el-button>
              <el-button v-else type="text" class="row-btn" style="color: #f40" icon="el-icon-remove-outline" @click="romoveSiteItem(index)"></el-button>
              <el-col :span="12">
                <el-form-item label="监测点">
                  <el-select v-model="item.site" filterable placeholder="选择站点" value-key="id" clearable style="width: 100%" @change="selectSite(item.site, index)">
                    <el-option v-for="(site, index) in siteOption" :key="index" :label="site.siteName" :value="site">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="监测目标">
                  <el-select v-model="item.target" filterable placeholder="选择指标" value-key="targetCode" clearable style="width: calc(100% - 217px)" @change="
                      (val) => {
                        targetChange(val, index)
                      }
                    ">
                    <el-option v-for="(target, index) in item.targets" :key="index" :label="target.targetName" :value="target">
                    </el-option>
                  </el-select>
                  <el-select v-model="item.symbol" filterable clearable style="width: 100px">
                    <el-option label="大于" value="大于"></el-option>
                    <el-option label="小于" value="小于"></el-option>
                  </el-select>
                  <el-input v-model="item.value" placeholder="目标值" style="width: 110px">
                    <span slot="suffix" style="color: #000">{{ item.targetUnit }}</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="改造前计算">
                  <el-date-picker v-model="form.beforeRemouldDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="改造后计算">
                  <el-date-picker v-model="form.afterRemouldDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
          <el-row style="margin-top: 15px">
            <el-button type="primary" @click="saveProject()" size="small" style="float: right; margin-left: 10px">方案保存</el-button>
            <el-button type="primary" @click="getRemouldConclusion()" size="small" style="float: right; margin-left: 10px">开始评估</el-button>
            <el-button type="warning" @click="clearPlan()" size="small" style="float: left; margin-left: 10px">清 空</el-button>
            <el-button type="danger" @click="removePlan()" size="small" style="float: left; margin-left: 10px">删 除</el-button>
          </el-row>
        </el-form>
      </div>
      <div class="middle-box">
        <div class="head-title">评估结果</div>
        <el-table :data="tableData" style="width: 100%" stripe :header-cell-style="{
            background: 'rgba(45, 116, 231,0.2)',
            color: '#333333',
            height: '40px',
            textAlign: 'center'
          }" max-height="400px">
          <template slot="empty">
            <img src="@/assets/icon/null.png" alt="暂无数据" style="width: 100px" />
          </template>
          <el-table-column prop="monitorName" label="站点名称" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="waterQualityIndex" label="水质指标" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="remouldAfter" label="改造后" align="center"></el-table-column>
          <el-table-column prop="remouldBefore" label="改造前" align="center"></el-table-column>
          <el-table-column prop="compareRemouldBefore" label="较改造前" align="center">
            <template slot-scope="{ row }">
              <span style="color: #36c46e">{{ row.compareRemouldBefore }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remouldAfterTarget" label="改造后目标值" align="center"></el-table-column>
          <el-table-column prop="compareTarget" label="较目标值" align="center">
            <template slot-scope="{ row }">
              <span :style="{ color: row.result == '达标' ? '#36c46e' : '#f33d48' }">
                {{ row.result == '达标' ? `+${row.compareTarget}` : row.compareTarget }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="结论" align="center">
            <template slot-scope="{ row }">
              <span :style="{ color: row.result == '达标' ? '#36c46e' : '#f33d48' }">{{ row.result }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 统计图 -->
      <div class="bottom-box" v-for="(val, key, i) in chartsData" :key="i">
        <div class="head-title" style="margin-top: 20px; font-weight: 600">{{ key }}</div>
        <zb-item v-for="(item, index) in val" :key="index" :data="item"></zb-item>
      </div>
      <!-- 曲线 -->
      <div v-for="(item,index) in curveData" :key="index">
        <div class="head-title">{{`${item.type==0?'改造前':'改造后'}：${item.name}`}}</div>
        <div class="chart-box" :ref="`chart${item.code}`"></div>
      </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 zbItem from './zbItem/index'
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'

import { getRemouldConclusion } from '@/views/spectrum/reform/api/api'
import { getSites } from '@/views/spectrum/dynamicMonitor/api/api'
import {
  getSiteTargets,
  getProjectScheme,
  saveProjectScheme,
  getProjectSchemeById,
  deleteProjectSchemeById,
  remouldHourCurve
} from '@/views/spectrum/reform/api/api'
import { getRainfallHour } from '@/views/spectrum/dynamicMonitor/api/api'
export default {
  components: {
    miniMap,
    moniterSee,
    thematicMap,
    historyCurve,
    zbItem
  },
  data() {
    return {
      siteGroups: [
        {
          site: null,
          targets: [],
          target: null,
          symbol: null,
          value: '',
          targetUnit: ''
        }
      ],
      currentProject: null,
      projectScheme: [],
      form: {},
      tableData: [],
      siteOption: [],
      moniterVisible: false,
      // 图表数据
      chartsData: [],
      curveData: [], // 曲线数据
    }
  },
  mounted() {
    this.getProjectScheme()
    this.getSites()
    // this.getRemouldConclusion()
  },
  methods: {
    /**
     * 获取工程项目列表
     */
    getProjectScheme() {
      getProjectScheme().then((res) => {
        if (res.code != 1) return
        this.projectScheme = res.result
      })
    },
    /**
     * 获取站点
     */
    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)
        }
      })
    },
    /**
     * 改造后评估结果
     */
    async getRemouldConclusion() {
      const data = this.readyParams(0)
      if (!data) return
      getRemouldConclusion(data).then((res) => {
        if (res.code == 1) {
          this.tableData = res.result.assessmentConclusions
          this.chartsData = res.result.maps
        }
      })
      this.remouldHourCurve()
    },
    /**
     * 添加条件
     */
    addSiteItem() {
      this.siteGroups.push({
        site: null,
        targets: [],
        target: null,
        symbol: null,
        value: '',
        targetUnit: ''
      })
    },
    /**
     * 移除条件
     */
    romoveSiteItem(index) {
      this.siteGroups.splice(index, 1)
    },
    /**
     * 站点选择
     */
    selectSite(site, index) {
      if (!site) {
        this.$set(this.siteGroups[index], 'target', null)
        this.$set(this.siteGroups[index], 'targetUnit', null)
        return
      }
      getSiteTargets({ siteIds: `${site.id}` }).then((res) => {
        if (res.code != 1 || res.result.length == 0) return
        this.siteGroups[index].targets = res.result
        this.siteGroups[index].target
        this.$set(this.siteGroups[index], 'target', res.result[0])
        this.$set(this.siteGroups[index], 'targetUnit', res.result[0].targetUnit)
      })
    },
    /**
     * 选择指标
     */
    targetChange(val, index) {
      if (!val) this.$set(this.siteGroups[index], 'targetUnit', null)
      this.$set(this.siteGroups[index], 'targetUnit', val.targetUnit)
    },
    /**
     * 确定方案参数
     * type => 0:评估参数 1:保存方案参数
     */
    readyParams(type) {
      const { projectName, projectRemouldTarget, beforeRemouldDate, afterRemouldDate, id } = this.form
      const monitorScheme = this.siteGroups.map((item) => {
        return {
          monitorId: (item.site && item.site.id) || '',
          monitorType: (item.target && item.target.targetCode) || '',
          projectSchemeId: item.projectSchemeId || undefined,
          id: item.id || undefined,
          symbol: item.symbol || '',
          targetValue: item.value || '',
          unit: item.targetUnit || ''
        }
      })
      if (!projectName) {
        this.$message.warning('请输入方案名称！')
        return false
      }
      if (!projectRemouldTarget) {
        this.$message.warning('请输入方案目标！')
        return false
      }
      if (type == 0 && (!beforeRemouldDate || beforeRemouldDate.length == 0)) {
        this.$message.warning('请输入改造前计算时间！')
        return false
      }
      if (type == 0 && (!afterRemouldDate || afterRemouldDate.length == 0)) {
        this.$message.warning('请输入改造后计算时间！')
        return false
      }
      const data = {
        monitorScheme: monitorScheme,
        projectScheme: {
          afterRemouldEndDate:
            afterRemouldDate && afterRemouldDate.length == 2
              ? this.$moment(afterRemouldDate[1]).format('YYYY-MM-DD 23:59:59')
              : '',
          afterRemouldStartDate:
            afterRemouldDate && afterRemouldDate.length == 2
              ? this.$moment(afterRemouldDate[0]).format('YYYY-MM-DD 00:00:00')
              : '',
          beforeRemouldEndDate:
            beforeRemouldDate && beforeRemouldDate.length == 2
              ? this.$moment(beforeRemouldDate[1]).format('YYYY-MM-DD 23:59:59')
              : '',
          beforeRemouldStartDate:
            beforeRemouldDate && beforeRemouldDate.length == 2
              ? this.$moment(beforeRemouldDate[0]).format('YYYY-MM-DD 00:00:00')
              : '',
          projectName: projectName || '',
          projectRemouldTarget: projectRemouldTarget || '',
          id: id || undefined
        }
      }
      return data
    },
    /**
     * 保存方案
     */
    saveProject() {
      const data = this.readyParams(1)
      if (!data) return
      saveProjectScheme(data).then((res) => {
        if (res.code != 1) return
        this.$message.success('保存方案成功')
        this.getProjectScheme()
      })
    },
    /**
     * 通过id获取方案
     */
    getProjectSchemeById(id) {
      this.tableData = this.$options.data().tableData
      this.chartsData = this.$options.data().chartsData
      if (!id) return
      getProjectSchemeById(id).then(async (res) => {
        if (res.code != 1) return
        const { monitorScheme, projectScheme } = res.result
        // 方案
        this.$set(this.form, 'projectName', projectScheme.projectName)
        this.$set(this.form, 'projectRemouldTarget', projectScheme.projectRemouldTarget)
        this.$set(this.form, 'id', projectScheme.id)
        // 方案站点指标
        let siteGroups = []
        if (monitorScheme) {
          for (let index = 0; index < monitorScheme.length; index++) {
            const item = monitorScheme[index]
            const { result: targets } = await getSiteTargets({ siteIds: `${item.monitorId}` })
            const site = this.siteOption.find((siteItem) => {
              return siteItem.id == item.monitorId
            })
            const target = targets.find((targetItem) => {
              return targetItem.targetCode == item.monitorType
            })
            const siteGroup = JSON.parse(
              JSON.stringify({
                site: site,
                targets: targets,
                target: target,
                symbol: item.symbol,
                value: item.targetValue,
                targetUnit: item.unit,
                projectSchemeId: item.projectSchemeId,
                id: item.id
              })
            )
            this.$set(siteGroups, index, siteGroup)
          }
        }

        this.siteGroups = siteGroups.length > 0 ? siteGroups : [{
          site: null,
          targets: [],
          target: null,
          symbol: null,
          value: '',
          targetUnit: ''
        }]
        this.$set(this.form, 'beforeRemouldDate', [
          projectScheme.beforeRemouldStartDate,
          projectScheme.beforeRemouldEndDate
        ])
        this.$set(this.form, 'afterRemouldDate', [
          projectScheme.beforeRemouldEndDate,
          projectScheme.afterRemouldEndDate
        ])
        this.$forceUpdate()
      })
    },
    /**
     * 曲线请求参数
     */
    readyRemouldHourCurveParams() {
      let scm = {}
      this.siteGroups.forEach((siteGroup) => {
        const targetCode = siteGroup.target.targetCode
        if (scm.hasOwnProperty(targetCode)) scm[targetCode].push(siteGroup.site.id)
        else scm[targetCode] = [siteGroup.site.id]
      })
      let params = []
      for (const key in scm) {
        params.push({
          code: key,
          siteId: scm[key]
        })
      }
      const data = {
        params: params,
        beginTime: this.$moment(this.form.beforeRemouldDate[0]).format('YYYY-MM-DD 00:00:00'),
        endTime: this.$moment(this.form.beforeRemouldDate[1]).format('YYYY-MM-DD 23:59:59'),
        afterBeginTime: this.$moment(this.form.afterRemouldDate[0]).format('YYYY-MM-DD 00:00:00'),
        afterEndTime: this.$moment(this.form.afterRemouldDate[1]).format('YYYY-MM-DD 23:59:59')
      }
      return data
    },
    /**
     * 统计曲线
     */
    remouldHourCurve() {
      const data = this.readyRemouldHourCurveParams();
      remouldHourCurve(data).then(async res => {
        const result = res.result;
        let curveData = []
        const beforeRemould = result.beforeRemould;
        const afterRemould = result.afterRemould;
        for (const target in beforeRemould) {
          const beforeItem = beforeRemould[target];
          beforeItem['type'] = 0;
          beforeItem['code'] = `b${target}`
          beforeItem['targetCode'] = target
          const afterItem = afterRemould[target];
          afterItem['type'] = 1;
          afterItem['code'] = `a${target}`
          afterItem['targetCode'] = target
          curveData = [...curveData, ...[beforeItem, afterItem]]
        }
        this.curveData = curveData;
        // 改造前雨量数据
        let { result: beforeRainFall } = await getRainfallHour({
          beginDate: this.$moment(this.form.beforeRemouldDate[0]).format("YYYY-MM-DD"),
          endDate: this.$moment(this.$moment(this.form.beforeRemouldDate[1]).add(1, 'd')).format("YYYY-MM-DD")
        });
        // 改造后雨量数据
        let { result: afterRainFall } = await getRainfallHour({
          beginDate: this.$moment(this.form.afterRemouldDate[0]).format("YYYY-MM-DD"),
          endDate: this.$moment(this.$moment(this.form.afterRemouldDate[1]).add(1, 'd')).format("YYYY-MM-DD")
        });

        const beforeRainDataObj = this.getRainDataObj(beforeRainFall) // 改造前计算雨量数据对象
        const afterRainDataObj = this.getRainDataObj(afterRainFall) // 改造后计算雨量数据对象

        for (let index = 0; index < curveData.length; index++) {
          const item = curveData[index];
          const domeId = `chart${item.code}`
          const xData = item.dateDate
          const series = item.siteData.map(site_data => {
            return {
              name: site_data.siteName,
              type: 'line',
              smooth: true,
              lineStyle: {
                width: 2
              },
              showSymbol: false,
              data: site_data.data
            }
          })

          // 雨量数据
          series.unshift({
            name: '雨量',
            xAxisIndex: 0,
            sampling: 'average', //降采样策略
            type: 'bar',
            yAxisIndex: 1,
            emphasis: {
              focus: 'series'
            },
            data: this.groupRainfallData(xData, item.type == 0 ? beforeRainDataObj : afterRainDataObj)
          })
          this.$nextTick(() => {
            this.loadChart(domeId, xData, series, item.name)
          })
        }
      })
    },
    /**
     * 将雨量列表转对象
     */
    getRainDataObj(rainFallData) {
      let rainObj = {}
      for (let index = 0; index < rainFallData.length; index++) {
        const item = rainFallData[index];
        rainObj[this.$moment(item.xposition).format("_YYYY_MM_DD_HH")] = item.maxFall
      }
      return rainObj
    },
    /**
     * 获取图表雨量数据
     */
    groupRainfallData(x1Data, rainFallDataObj) {
      let myRainFallData = []
      for (let index = 0; index < x1Data.length; index++) {
        const x1Item = this.$moment(x1Data[index]).format("_YYYY_MM_DD_HH");
        myRainFallData.push(rainFallDataObj[x1Item] ? rainFallDataObj[x1Item] : null)
      }
      return myRainFallData
    },
    /**
     * 图表
     */
    loadChart(domId, xData, series, y0Name) {
      const chartDom = this.$refs[domId][0];
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: series.map(item => { return item.name })
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData
        },
        yAxis: [
          {
            type: 'value',
            name: y0Name,
            nameLocation: "end"
          },
          {
            nameLocation: 'end',
            alignTicks: true,
            type: 'value',
            name: '雨量'
          }
        ],
        series: series
      };
      myChart.clear()
      option && myChart.setOption(option);
      elementResizeDetectorMaker().listenTo(chartDom, () => {
        this.$nextTick(() => {
          myChart.resize()
        })
      })
    },
    /**
     * 清除方案
     */
    clearPlan() {
      this.siteGroups = this.$options.data().siteGroups
      this.currentProject = this.$options.data().currentProject
      this.form = this.$options.data().form
      this.tableData = this.$options.data().tableData
      this.chartsData = this.$options.data().chartsData
      this.curveData = this.$options.data().curveData
    },
    /**
     * 删除当前方案
     */
    removePlan() {
      const { id } = this.form;
      if (!id) return
      this.$confirm('确认删除该方案?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProjectSchemeById(id).then(res => {
          if (res.code == 1) {
            this.clearPlan()
            this.getProjectScheme()
            this.$message.success('删除方案成功');
          }
        })
      })
    },
    /**
     * 监测查看
     */
    viewCurve(row = null) {
      this.$refs.historyCurve.show(row)
    },
    moniterClose() {
      this.moniterVisible = false
    }
  }
}
</script>

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