<template>
  <div class="query-container">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <!-- <el-form-item label="河道类型">
        <el-select style="width: 150px" clearable v-model="searchParam.driverExam" size="small"
                   placeholder="请选择河道类型">
          <el-option v-for="item in driverExamList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item> -->
      <el-form-item label="任务单号">
        <el-input clearable v-model="searchParam.inspectNo" size="small" placeholder="请输入任务单号" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="报告编号">
        <el-input clearable v-model="searchParam.reportNo" size="small" placeholder="请输入报告编号" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="河道名称">
        <el-input clearable v-model="searchParam.driverName" size="small" placeholder="请输入河道名称" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="区属">
        <driver-area-select v-model="searchParam.driverArea"></driver-area-select>
      </el-form-item>
      <el-form-item label="巡检时间">
        <el-date-picker
          style="width: 150px"
          placeholder="巡检时间"
          clearable
          size="small"
          value-format="yyyy-MM-dd"
          v-model="searchParam.inspectTime">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 150px" filterable clearable v-model="searchParam.status" size="small"
                   placeholder="请选择状态">
          <el-option v-for="(value,key,index) in statusList" :key="index" :label="value" :value="key"/>
        </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 icon="el-icon-refresh-right" @click="initSearchParam();search()"
                   type="primary" size="small"
                   style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
        </el-button>
      </el-form-item>
    </el-form>
    <el-table stripe ref="table"
              :height="tableHeight" v-loading="tableLoading" :data="dataList" border size="medium"
              row-key="id">
      <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center"/>
      <el-table-column min-width="100" show-overflow-tooltip prop="reportNo" label="报告单号" align="center">
        <template slot-scope="scoped">
          <a @click="getDetail(scoped.row)" v-if="isAdmin||btnRule.some(btn=>btn=='view')" href="javascript:void(0);">{{scoped.row.reportNo}}</a>
          <span v-else>{{scoped.row.reportNo}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100" show-overflow-tooltip prop="inspectNo" label="任务单号" align="center"/>
      <el-table-column min-width="70" show-overflow-tooltip prop="num" label="行号" align="center"/>
      <el-table-column show-overflow-tooltip prop="driverName" label="河道名称" align="center"/>
      <el-table-column show-overflow-tooltip prop="driverAreaText" label="区划" align="center"/>
      <el-table-column show-overflow-tooltip prop="formatInspectTime" label="巡检时间" width="110" align="center">
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="driverStart" label="起点" align="center"/>
      <el-table-column show-overflow-tooltip prop="driverEnd" label="终点" align="center"/>
      <el-table-column min-width="70" show-overflow-tooltip prop="inspectLength" label="长度" align="center"/>
      <el-table-column min-width="80" show-overflow-tooltip prop="statusText" label="状态" align="center"/>
      <el-table-column v-if="isAdmin||btnRule.some(btn=>btn=='video'||btn=='image'||btn=='drop'||btn=='reProcess')"
                       label="操作" align="left"
                       width="270">
        <template slot-scope="{row}">
          <el-button v-if="row.videoUrl&&(isAdmin||btnRule.some(btn=>btn=='video'))" @click="videoClick(row)"
                     type="primary" size="mini"
                     icon="el-icon-video-camera">视频
          </el-button>
          <el-button v-if="row.imageUrl&&(isAdmin||btnRule.some(btn=>btn=='image'))"
                     @click="uploadDownImg(row.imageUrl)" type="primary" size="mini"
                     icon="el-icon-picture">正摄图
          </el-button>
          <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='drop')" class="item" effect="dark" content="删除"
                      placement="bottom">
            <el-button :loading="delBtnLoading" type="danger" size="mini" icon="el-icon-delete"
                       @click="handleDelete(row)"/>
          </el-tooltip>
          <el-button v-if="row.status==3&&(isAdmin||btnRule.some(btn=>btn=='reProcess'))" :loading="reProcessBtnLoading"
                     @click="refreshReport(row)" type="primary" size="mini"
                     icon=" el-icon-refresh-right">重处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-current">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        prev-text="上一页"
        next-text="下一页"
        background
        layout="total, prev, pager, next, jumper"
        style="display: inline-block;"
        :total="count"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-drawer
      title="报告"
      :visible.sync="detailVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleDetailClose">
      <report :mapImg="mapImg" v-if="detailVisible" typeName="query" :ruleForm="ruleForm"></report>
      <div style="width: 100%;text-align: center;margin-top: 20px;margin-bottom: 20px">
        <el-button :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>
      </div>
    </el-drawer>
    <el-drawer
      title="视频"
      :visible.sync="videoVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleVideoClose">
      <div class="video-top">
        <div>
          <img src="../../assets/img/video-top.png">
          <div>
            <div>区属</div>
            <div>{{videoItem.driverAreaText}}</div>
          </div>
        </div>
        <div>
          <img src="../../assets/img/video-top.png">
          <div>
            <div>河道名称</div>
            <div>{{videoItem.driverName}}</div>
          </div>
        </div>
        <div>
          <img src="../../assets/img/video-top.png">
          <div>
            <div>起点</div>
            <div>{{videoItem.driverStart}}</div>
          </div>
        </div>
        <div>
          <img src="../../assets/img/video-top.png">
          <div>
            <div>终点</div>
            <div>{{videoItem.driverEnd}}</div>
          </div>
        </div>
        <div>
          <img src="../../assets/img/video-top.png">
          <div>
            <div>巡检时间</div>
            <div>{{videoItem.formatInspectTime}}</div>
          </div>
        </div>
      </div>
      <cVideo v-if="videoVisible" :videoUrl="videoItem.videoUrl"></cVideo>
      <!--      <iframe width="100%" :height="vedioHeight" v-if="videoVisible" frameborder="0" :src="videoUrl"></iframe>-->
      <div style="width: 100%;text-align: center;margin-top: 20px;margin-bottom: 20px">
        <el-button size="medium" icon="el-icon-back"
                   @click="videoVisible = false">返回
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import reportApi from '@/api/report/report'
  import cVideo from '@/components/cVideo'
  import driverAreaSelect from '@/components/driverAreaSelect'
  import {mapGetters} from "vuex";
  import report from './report'
  import $ from 'jquery'
  import html2canvas from 'html2canvas'

  export default {
    name: "query-container",
    data() {
      return {
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        mapImg: '',
        reProcessBtnLoading: false,
        vedioHeight: '',
        videoVisible: false,
        addLoading: false,
        detailVisible: false,
        statusList: [],
        dataList: [],
        // driverExamList: [
        //   {id: 1, name: '国、省考河道'},
        //   {id: 2, name: '市、区级河道'}
        // ],
        currentPage: 1,
        count: 0,
        pageSize: parseInt((document.body.clientHeight - 300 - 43) / 44.5),
        tableHeight: document.body.clientHeight - 300,
        tableLoading: false,
        posterImg: require('../../assets/img/vedio-bak.jpg'),
        searchParam: {
          reportNo: '',
          inspectNo: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
          status: '',
          // driverExam: ''
        },
        videoItem: {},
        ruleForm: {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: []
        },
        delBtnLoading: false
      }
    },
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    components: {report, cVideo, driverAreaSelect},
    created() {
      this.vedioHeight = (document.body.clientWidth - 190)/16*9
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
    },
    methods: {
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      handleDetailClose(hide) {
        if (hide) {
          hide()
        }
        this.detailVisible = false
      },
      handleVideoClose(hide) {
        if (hide) {
          hide()
        }
        this.videoVisible = false
      },
      refreshReport(data) {
        this.$confirm('确认重处理此报告？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.reProcessBtnLoading = true
          reportApi.reProcess({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '重处理成功！'
            })
            this.reProcessBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.reProcessBtnLoading = false
          })
        }).catch(() => {
        })
      },
      handleDelete(data) {
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          type: 'warning',
          message: h('div', null, [
            h('div', {style: 'color: #333333;padding-top: 43px;'}, '确认删除此报告?'),
            h('div', {style: 'color: #999999;margin-top: 10px;'}, '数据删除后无法恢复，删除后如需恢复，需重新生成报告')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          this.delBtnLoading = true
          reportApi.dropReport({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        });
      },
      videoClick(row) {
        this.videoVisible = true
        this.videoItem = row
      },
      uploadDownImg(url) {
        window.location.href = url
      },
      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) {
        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
          this.ruleForm = Object.assign({}, ruleForm)
          this.detailVisible = true
        }).catch(e => {
          this.tableLoading = false
        })
      },
      initSearchParam() {
        this.searchParam = {
          reportNo: '',
          inspectNo: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
          status: '',
          // driverExam: ''
        }
      },
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      handleCurrentChange(val) {
        this.tableLoading = true
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      getAllList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        if (searchParam.inspectTime) {
          searchParam.inspectTime = new Date(searchParam.inspectTime).getTime() / 1000
        }
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        reportApi.getSearchList(searchParam).then(res => {
          this.dataList = res.data.data.records ? res.data.data.records : []
          this.statusList = res.data.statusList ? res.data.statusList : []
          this.count = res.data.data.total
          this.tableLoading = false
        }).catch(e => {
          this.dataList = []
          this.statusList = []
          this.tableLoading = false
        })
      }
    }
  }
</script>

<style lang="less">
  .query-container {
    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;

    .video-top {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      margin-bottom: 15px;

      > div {
        display: flex;

        > img {
          width: 40px;
          height: 40px;
        }

        > div:last-child {
          margin-left: 10px;
          color: #999999;

          > div:last-child {
            color: #666666;
          }
        }
      }
    }

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

        .el-dialog__header {
          padding: 0 !important;

          .el-dialog__headerbtn .el-dialog__close {
            color: #333333 !important;
          }
        }
      }
    }

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

      .el-dialog__body {
        background-position: center center;
        background-size: cover;
        background-image: url(../../assets/img/video-2.png);
      }
    }
  }
</style>
