<template>
  <div class="drive-area">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <el-form-item label="类型" prop="type">
        <el-select style="width: 150px" v-model="searchParam.type" size="small"
                   placeholder="请选择类型">
          <el-option key="1" label="国、省考河道" value="1"/>
          <el-option key="2" label="市、区级河道" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="巡检时间">
        <el-date-picker
          style="width: 220px"
          placeholder="选择的时间"
          clearable
          size="small"
          value-format="yyyy-MM-dd"
          v-model="searchParam.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="区属">
        <el-select style="width: 150px" filterable clearable v-model="searchParam.driverArea" size="small"
                   placeholder="请选择区属">
          <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :loading="tableLoading" icon="el-icon-search" @click="search" size="small" type="primary">搜索
        </el-button>
        <el-button v-if="this.$route.params.id" size="small" icon="el-icon-back"
                   @click="goBack">返回
        </el-button>
      </el-form-item>
    </el-form>
    <div class="chart-box">
      <div>
        <div>巡检问题统计</div>
        <div id="c3"></div>
      </div>
      <div>
        <div>问题河流大数据分析</div>
        <div id="c4"></div>
      </div>
    </div>
    <div style="margin: 15px 0">河道数量：{{totalNum.driverNum}} 巡检次数：{{totalNum.inspectNum}} 问题数量：{{totalNum.questionNum}}
    </div>
    <el-table stripe ref="table" v-loading="tableLoading" :data="dataList"
              border row-key="id">
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="driverName" label="河流名称" align="center"/>
      <el-table-column width="180" show-overflow-tooltip prop="formatInspectTime" label="巡检时间" align="center"/>
      <el-table-column show-overflow-tooltip prop="totalExamineScore" label="评分" align="center"/>
      <el-table-column show-overflow-tooltip prop="totalNum" label="问题总数" align="center"/>
      <el-table-column show-overflow-tooltip prop="surfaceWater" label="水面" align="center">
        <template slot-scope="scoped">
          <a v-if="scoped.row.surfaceWater&&(isAdmin||btnRule.some(btn=>btn=='detail'))" href="javascript:void(0);" @click="getDetail(scoped.row,'surfaceWater')">{{scoped.row.surfaceWater}}</a>
          <span v-else>{{scoped.row.surfaceWater}}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="shoreLine" label="岸线" align="center">
        <template slot-scope="scoped">
          <a v-if="scoped.row.shoreLine&&(isAdmin||btnRule.some(btn=>btn=='detail'))" href="javascript:void(0);" @click="getDetail(scoped.row,'shoreLine')">{{scoped.row.shoreLine}}</a>
          <span v-else>{{scoped.row.shoreLine}}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="outfall" label="排口" align="center">
        <template slot-scope="scoped">
          <a v-if="scoped.row.outfall&&(isAdmin||btnRule.some(btn=>btn=='detail'))" href="javascript:void(0);" @click="getDetail(scoped.row,'outfall')">{{scoped.row.outfall}}</a>
          <span v-else>{{scoped.row.outfall}}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="waterQuality" label="水质" align="center">
        <template slot-scope="scoped">
          <a v-if="scoped.row.waterQuality&&(isAdmin||btnRule.some(btn=>btn=='detail'))" href="javascript:void(0);" @click="getDetail(scoped.row,'waterQuality')">{{scoped.row.waterQuality}}</a>
          <span v-else>{{scoped.row.waterQuality}}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isAdmin||btnRule.some(btn=>btn=='detail')" width="80" label="操作">
        <template slot-scope="scoped">
            <el-button v-if="isAdmin||btnRule.some(btn=>btn=='detail')" :loading="detailLoading" @click="getDetail(scoped.row)" type="primary" size="mini"
                       icon="el-icon-tickets">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page-current">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        prev-text="上一页"
        next-text="下一页"
        layout="total, prev, pager, next, jumper"
        style="display: inline-block;"
        background
        @current-change="handleCurrentChange"
        :total="count"/>
    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" ref="dialogForm" top="5vh" center
               class="detail-dialog" :class="ruleForm.type?'':'query-dialog'" :visible.sync="detailVisible" :title="ruleForm.type?'南京市河道无人机巡检报告':''">
      <report :mapImg="mapImg" :documentList="documentList" v-if="detailVisible" typeName="query" :ruleForm="ruleForm"></report>
      <span slot="footer" class="dialog-footer no-print">
              <el-button v-if="!ruleForm.type" :loading="addLoading" @click="pointMain" type="primary" size="medium"
                         icon="el-icon-printer">打印</el-button>
                  <el-button size="medium" icon="el-icon-back"
                             @click="detailVisible = false">返回
                  </el-button>
              </span>
    </el-dialog>
  </div>
</template>

<script>
  import statisticsApi from '@/api/statistics/index'
  import inspectApi from '@/api/business/inspect'
  import report from '../report/report'
  import reportApi from '@/api/report/report'
  import inspectfileApi from '@/api/file/inspectfile'
  import G2 from '@antv/g2';
  import $ from 'jquery'
  import html2canvas from 'html2canvas'

  export default {
    name: "drive-area",
    data() {
      return {
        mapImg:'',
        currentPage: 1,
        count: 0,
        // 每页条数
        pageSize: 50,
        cityList: [],
        preTotal: 0,
        tableLoading: false,
        searchParam: {
          type: '1',
          time: '',
          driverArea: ''
        },
        filterDataList: [],
        detailLoading: false,
        addLoading: false,
        detailVisible: false,
        ruleForm: {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: []
        },
        filterBarList: [],
        dataList: [],
        chart: {},
        barChart: {},
        chartWidth: 500,
        totalNum: {},
        btnRule: [],
        documentList:{},
        isAdmin: false
      }
    },
    components: {report},
    created() {
      this.chartWidth = (document.body.clientWidth - 300) / 2
      const {btnRule, isAdmin} = this.$store.state.user
      this.btnRule = btnRule
      this.isAdmin = isAdmin
      const {id,searchParam}=this.$route.params
      if(id){
        this.searchParam={
          type: searchParam.type,
          time: searchParam.time,
          driverArea: parseInt(id)
        }
      }
    },
    mounted() {
      this.tableLoading = true
      this.initChar()
      this.initBar()
      this.getBaseData()
      this.getDocument()
      this.getAllList()
    },
    methods: {
      getDocument() {
        inspectfileApi.getDocument().then(res => {
          this.documentList = res.data ? res.data : {}
        }).catch(e => {
          this.documentList = {}
        })
      },
      goBack(){
        history.go(-1)
      },
      print(content, w = null, h = null) {
        const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
        const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

        const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
        w = +w === 0 ? width : w;
        h = +h === 0 ? height : h;
        const left = ((width / 2) - (w / 2)) + dualScreenLeft;
        const top = ((height / 2) - (h / 2)) + dualScreenTop;
        var myWindow = window.open("", "打印", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left);
        var style = "<style type='text/css'>table.gridtable {font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;}table.gridtable th {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666;background-color: #dedede;}table.gridtable td {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666;background-color: #ffffff;}</style>";
        myWindow.document.write(content + style);
        myWindow.focus();
        myWindow.document.close();     //关闭document的输出流, 显示选定的数据
        $(myWindow).ready(function () {
          myWindow.print();
          myWindow.close()
        });
        return myWindow;
      },
      pointMain() {
        let me = this
        let reportMap = document.getElementById('reportMap')
        if(reportMap){
          html2canvas(reportMap, {
            backgroundColor: 'white',
            scale: 2,
            dpi: 300
          }).then((canvas) => {
            let dataURL = canvas.toDataURL("image/png");
            me.mapImg = dataURL
            me.$nextTick(function () {
              me.print(document.getElementById('reportPoint').innerHTML);
              me.mapImg = ''
            })
          });
        }else{
          me.print(document.getElementById('reportPoint').innerHTML);
        }
      },
      initRuleForm() {
        this.ruleForm = {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: [],
        }
      },
      getDetail(data,type) {
        this.tableLoading = true
        reportApi.getDetail({id: data.id}).then(res => {
          this.tableLoading = false
          this.initRuleForm()
          let ruleForm = JSON.parse(JSON.stringify(res.data))
          let questionList = ruleForm.questionList
          let filterQuestionList = []
          let categoryList = []
          questionList.map(item => {
            if (!categoryList.some(category => category == item.category)) {
              categoryList.push(item.category)
            }
          })
          categoryList.sort(function (a, b) {
            return a - b
          })
          categoryList.map(category => {
            let list = questionList.filter(item => item.category == category)
            let typeList = []
            list.map(item => {
              if (!typeList.some(type => type == item.type)) {
                typeList.push(item.type)
              }
            })
            typeList.sort(function (a, b) {
              return a - b
            })
            let filter = []
            typeList.map(type => {
              let filterType = list.filter(item => item.type == type)
              filterType[0].typeRow = filterType.length
              filter = filter.concat(filterType)
            })
            filter[0].categoryRow = list.length
            filterQuestionList = filterQuestionList.concat(filter)
          })
          ruleForm.filterQuestionList = filterQuestionList
          ruleForm.type = type
          this.ruleForm = Object.assign({}, ruleForm)
          this.detailVisible = true
        }).catch(e => {
          this.tableLoading = false
        })
      },
      handleCurrentChange(val) {
        this.tableLoading = true
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      getBaseData() {
        inspectApi.basicData().then(res => {
          const {areaList} = res.data
          this.cityList = areaList ? areaList : []
        }).catch(e => {
          this.cityList = []
        })
      },
      initSearchParam() {
        this.searchParam = {
          type: '1',
          time: '',
          driverArea: ''
        }
      },
      search() {
        this.tableLoading = true
        this.currentPage = 1
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      initChar() {
        let chart = new G2.Chart({
          container: 'c3',
          height: 400,
          width: this.chartWidth,
          padding: [40, 0, 0, 0]
        });
        chart.source(this.filterDataList, {
          percent: {
            formatter: val => {
              val = (val * 100) + '%';
              return val;
            }
          }
        });
        chart.tooltip({
          showTitle: false,
          'g2-tooltip': {
            width:'150px',
            position: 'absolute',
            visibility: 'hidden',
            border: '1px solid #efefef',
            backgroundColor: '#666666',
            color: '#ffffff',
            fontSize: '16px',
            opacity: '0.8',
            padding: '5px 15px',
            transition: 'top 200ms,left 200ms',
          }, // 设置 tooltip 的 css 样式
          'g2-tooltip-list': {
            margin: '10px',
          },
        });
        chart.legend('item', {
          position: 'top-center'
        });
        chart.coord('theta', {
          radius: 0.75
        });
        chart.intervalStack()
          .position('pre')
          .color('item')
          .label('pre', {
            formatter: (val, item) => {
              return item.point.item;
            },
            textStyle: {
              fill: '#333333',
              fontSize: 14
            }
          })
          .tooltip('item*pre', (item, pre,value) => {
            pre = (this.preTotal?(pre*this.preTotal):0) + '(' + parseInt(pre * 100) + '%' + ')';
            return {
              name: item,
              value: pre
            };
          })
          .style({
            lineWidth: 1,
            stroke: '#fff',
            fontSize: 16
          });
        chart.render();
        this.chart = chart
      },
      initBar() {
        let chart = new G2.Chart({
          container: 'c4',
          height: 400,
          width: this.chartWidth,
          padding: [60, 40, 40, 25]
        });
        chart.source(this.filterBarList);
        chart.scale('value', {
          min: 0,
        });
        chart.axis('type', {
          label: {
            textStyle: {
              fill: '#333333',
              fontSize: 14
            }
          },
          tickLine: {
            alignWithLabel: false,
            length: 0
          },
          line: {
            stroke: '#999999',
          }
        });

        chart.axis('value', {
          label: {
            textStyle: {
              fill: '#333333',
              fontSize: 14
            }
          },
          line: {
            stroke: '#999999',
          },
          title: {
            offset: 50
          }
        });
        chart.legend('company', {
          position: 'top-center'
        });
        chart.tooltip({
          'g2-tooltip': {
            width:'220px',
            position: 'absolute',
            visibility: 'hidden',
            border: '1px solid #efefef',
            backgroundColor: '#666666',
            color: '#ffffff',
            fontSize: '16px',
            opacity: '0.8',
            padding: '5px 15px',
            transition: 'top 200ms,left 200ms',
          }, // 设置 tooltip 的 css 样式
          'g2-tooltip-list': {
            margin: '10px',
          },
        });
        chart.interval().position('type*value').color('company')
          .opacity(8)
          .adjust([{
            type: 'dodge',
            marginRatio: 10 / 32
          }])
        ;
        chart.render();
        this.barChart = chart
      },
      initDataList() {
        let surfaceWater = 0
        let shoreLine = 0
        let outfall = 0
        let waterQuality = 0
        let filterDataList = []
        let list = JSON.parse(JSON.stringify(this.dataList))
        list.map(item => {
          surfaceWater += item.surfaceWater
          shoreLine += item.shoreLine
          outfall += item.outfall
          waterQuality += item.waterQuality
        })
        this.preTotal = surfaceWater + shoreLine + outfall + waterQuality
        filterDataList.push({item: '水面',pre:this.preTotal?(surfaceWater/this.preTotal):0.25, count: surfaceWater})
        filterDataList.push({item: '岸线',pre:this.preTotal?(shoreLine/this.preTotal):0.25 ,count: shoreLine})
        filterDataList.push({item: '排口',pre:this.preTotal?(outfall/this.preTotal):0.25, count: outfall})
        filterDataList.push({item: '水质',pre:this.preTotal?(waterQuality/this.preTotal):0.25, count: waterQuality})
        this.filterDataList = Object.assign([], filterDataList)
      },
      initBarList() {
        let filterBarList = []
        let list = JSON.parse(JSON.stringify(this.dataList))
		list = list.slice(0,8)
        list.map(item => {
          let ccList = filterBarList.filter(child => child.company == item.driverName)
          if (ccList.length > 0) {
            for (let i = 0; i < filterBarList.length; i++) {
              if (filterBarList[i].company == item.driverName && filterBarList[i].type == '水面') {
                filterBarList[i].value = filterBarList[i].value + item.surfaceWater
              }
              if (filterBarList[i].company == item.driverName && filterBarList[i].type == '岸线') {
                filterBarList[i].value = filterBarList[i].value + item.shoreLine
              }
              if (filterBarList[i].company == item.driverName && filterBarList[i].type == '排口') {
                filterBarList[i].value = filterBarList[i].value + item.outfall
              }
              if (filterBarList[i].company == item.driverName && filterBarList[i].type == '水质') {
                filterBarList[i].value = filterBarList[i].value + item.waterQuality
              }
            }
          } else {
            filterBarList.push({company: item.driverName, type: '水面', value: item.surfaceWater})
            filterBarList.push({company: item.driverName, type: '岸线', value: item.shoreLine})
            filterBarList.push({company: item.driverName, type: '排口', value: item.outfall})
            filterBarList.push({company: item.driverName, type: '水质', value: item.waterQuality})
          }
        })
        this.filterBarList = Object.assign([], filterBarList)
      },
      getAllList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        if (searchParam.time && searchParam.time.length > 0) {
          searchParam.inspectTime = searchParam.time[0] + '~' + searchParam.time[1]
        }
        delete searchParam.time
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        statisticsApi.getArea(searchParam).then(res => {
          this.dataList = res.data.data
          this.count = res.data.total
          this.pageSize = res.data.size
          this.totalNum = {
            driverNum: res.data.driverNum,
            inspectNum: res.data.inspectNum,
            questionNum: res.data.questionNum
          }
          this.initDataList()
          this.initBarList()
          this.chart.changeData(this.filterDataList);
          this.barChart.changeData(this.filterBarList)
          this.tableLoading = false
        }).catch(e => {
          this.dataList = []
          this.tableLoading = false
        })
      }
    }
  }
</script>

<style lang="less">
  .drive-area {
    height: fit-content;
    background-color: #fff;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);
    padding: 15px;

    .chart-box {
      margin-top: 20px;
      display: flex;

      > div {
        width: 50%;
      }
    }

    .detail-dialog{
      .el-dialog {
        width: 80% !important;
      }
    }

    .video-dialog {
      .el-dialog {
        width: 80% !important;
      }
    }

    .query-dialog{
      .el-dialog__header{
        padding: 0!important;
        .el-dialog__headerbtn .el-dialog__close{
          color: #333333!important;
        }
      }
    }
  }
</style>
