<template>
  <div class="inspect-driver-table">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <el-form-item label="任务类型">
        <el-select style="width: 150px" filterable clearable 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="区划">
        <driverAreaSelect v-model="searchParam.driverArea"></driverAreaSelect>
      </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="日期">
        <el-date-picker
          style="width: 220px"
          placeholder="日期"
          clearable
          size="small"
          value-format="yyyy-MM-dd"
          v-model="searchParam.inspectTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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" size="medium"
              :height="tableHeight" v-loading="tableLoading" :data="dataList" border
              row-key="id">
      <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center"/>
      <el-table-column width="120" show-overflow-tooltip prop="inspectNo" label="任务单号" align="center">
        <template slot-scope="scoped">
          <a v-if="btnRule.inspectDriver_detail" href="javascript:void(0);" @click="detailNo(scoped.row)">{{scoped.row.inspectNo}}</a>
          <span v-else>{{scoped.row.inspectNo}}</span>
        </template>
      </el-table-column>
      <el-table-column width="60" 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="inspectTime" label="巡检时间" min-width="120" align="center">
      </el-table-column>
      <el-table-column width="80" v-if="btnRule.inspectDriver_point" show-overflow-tooltip
                       prop="driverLength" label="巡检轨迹" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status==2||row.status==3"></span>
          <el-button v-else type="primary" size="mini"
                     @click="pointClick(row)">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column width="80" show-overflow-tooltip prop="formatCreateUser" label="申请人" align="center"/>
      <el-table-column width="160" show-overflow-tooltip prop="formatCreateTime" label="申请时间" align="center"/>
      <el-table-column width="80" show-overflow-tooltip prop="statusText" label="状态" align="center"/>
      <el-table-column v-if="btnRule.inspectDriver_view" width="60" show-overflow-tooltip prop=""
                       label="报告" align="center">
        <template slot-scope="{row}">
          <el-tooltip v-if="row.reportId" class="item" effect="dark" content="查看报告" placement="bottom">
            <el-button @click="getDetail(row.reportId)" type="primary" size="mini" icon="el-icon-document"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column v-if="btnRule.inspectfile_view" width="80" show-overflow-tooltip prop=""
                       label="图像资料" align="center">
        <template slot-scope="{row}">
          <el-tooltip v-if="row.status==4" class="item" effect="dark" content="查看图像" placement="bottom">
            <el-button @click="setMark(row)" type="primary" size="mini" icon="el-icon-picture"/>
          </el-tooltip>
        </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="trajectoryVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleRrajectoryClose">
      <trajectory-dialog :driverId="driverId" v-if="trajectoryVisible"></trajectory-dialog>
    </el-drawer>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" ref="dialogForm" top="5vh" center
               class="detail-dialog" :visible.sync="detailVisible">
      <pReport :mapImg="mapImg" v-if="detailVisible" typeName="query" :ruleForm="ruleForm"></pReport>
      <span slot="footer" class="dialog-footer no-print">
              <el-button @click="pointMain('reportPoint')" 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>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" class="image-dialog" top="2vh" center
               :visible.sync="imageVisible" title="图片">
      <image-list selectType="1" ref="imageList" type="show" :imageDetail="imageDetail"
                  :documentList="documentList"
                  v-if="imageVisible"></image-list>
      <span slot="footer" class="dialog-footer">
            <el-button size="medium" icon="el-icon-back"
                       @click="imageVisible = false">返回
            </el-button>
        </span>
    </el-dialog>
    <report :inspectId="inspectId" :visible="reportVisible" :status="status" @goBack="reportVisible=false" v-if="reportVisible"></report>
  </div>
</template>

<script>
  import inspectApi from '@/api/business/inspect'
  import reportApi from '@/api/report/report'
  import inspectfileApi from '@/api/file/inspectfile'
  import driverAreaSelect from '@/components/driverAreaSelect'
  import trajectoryDialog from '@/components/trajectoryDialog'
  import imageList from '@/components/imageList'
  import pReport from '@/components/report'
  import report from './inspectReport'
  import html2canvas from 'html2canvas'
  import $ from 'jquery'
  import {mapGetters} from "vuex";

  export default {
    name: "inspect-driver-table",
    data() {
      return {
        reportVisible:false,
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        dataList: [],
        currentPage: 1,
        count: 0,
        pageSize: parseInt((document.body.clientHeight - 320 - 43) / 45),
        tableHeight: document.body.clientHeight - 320,
        tableLoading: false,
        driverId:'',
        documentList: {},
        trajectoryVisible:false,
        searchParam: {
          type: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
        },
        detailVisible:false,
        mapImg: '',
        ruleForm: {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: []
        },
        imageDetail:{},
        imageVisible:false,
        inspectId:''
      }
    },
    props: {
      status: {
        type: String,
        default() {
          return '0'
        }
      }
    },
    mounted() {
      this.getDocument()
      this.getAllList()
    },
    components: {driverAreaSelect,trajectoryDialog,pReport,imageList,report},
    computed: {
      ...mapGetters(["btnRule"])
    },
    methods: {
      getDocument() {
        inspectfileApi.getDocument().then(res => {
          this.documentList = res.data ? res.data : {}
        }).catch(e => {
          this.documentList = {}
        })
      },
      setMark(row) {
        this.tableLoading = true
        let method = 'getDetail'
        inspectfileApi[method]({id: row.id}).then(res => {
          this.tableLoading = false
          let imageDetail = {
            taskId: row.id,
            driverName: row.driverName,
            formatExecutionStartTime: row.formatInspectTime,
            imgList: res.data ? res.data : []
          }
          this.imageDetail = Object.assign({}, imageDetail)
          this.imageVisible = true
          this.tableLoading = false
        }).catch(e => {
          this.tableLoading = false
        })
      },
      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(name) {
        let me = this
        if (name == 'reportPoint') {
          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);
          }
        } else {
          me.print(document.getElementById(name).innerHTML);
        }
      },
      initRuleForm() {
        this.ruleForm = {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: [],
        }
      },
      getDetail(id) {
        this.tableLoading = true
        reportApi.getDetail({id: 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
        })
      },
      pointClick(row) {
        this.driverId = row.driverId
        this.trajectoryVisible = true
      },
      handleRrajectoryClose(){
        this.trajectoryVisible=false
      },
      detailNo(row) {
        this.inspectId=row.id
        this.reportVisible=true
      },
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      initSearchParam() {
        this.searchParam = {
          type: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
        }
      },
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      getAllList() {
        this.tableLoading = true
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        if (searchParam.inspectTime && searchParam.inspectTime.length > 0) {
          searchParam.inspectTime = searchParam.inspectTime[0] + '~' + searchParam.inspectTime[1]
        } else {
          searchParam.inspectTime = ''
        }
        searchParam.status = this.status === '0' ? '' : this.status
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        inspectApi.getInspectDriverList(searchParam).then(res => {
          console.log(res.data)
          this.dataList = res.data.records ? res.data.records : []
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.dataList = []
          this.tableLoading = false
        })
      },
    }
  }
</script>

<style lang="less">
  .inspect-driver-table {
    .detail-dialog {
      .el-dialog {
        width: 80% !important;

        .el-dialog__header {
          padding: 0 !important;

          .el-dialog__headerbtn .el-dialog__close {
            color: #333333 !important;
          }
        }
      }
    }
    .image-dialog {
      .el-dialog {
        width: 600px !important;
      }
    }
  }
</style>
