<template>
  <div class="inspect-driver-list">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <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.driverName" size="small" placeholder="请输入河道名称" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="区划">
        <driverAreaSelect v-model="searchParam.driverArea"></driverAreaSelect>
      </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" 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="isAdmin||btnRule.some(btn=>btn=='view')" 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="isAdmin||btnRule.some(btn=>btn=='point')" show-overflow-tooltip
                       prop="driverLength" label="巡检轨迹" align="center">
        <template slot-scope="{row}">
          <el-button 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="isAdmin||btnRule.some(btn=>btn=='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="isAdmin||btnRule.some(btn=>btn=='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-column
        v-if="isAdmin||(btnRule.filter(value=>value=='print'||value=='execute'||value=='drop'||value=='reProcess').length>0)"
        label="操作"
        align="left" width="255">
        <template slot-scope="{row}">
          <!--          <el-button v-if="isAdmin||btnRule.some(btn=>btn=='print')" @click="point(row)" :loading="pointLoading"-->
          <!--                     type="primary" size="mini" icon="el-icon-printer">打印-->
          <!--          </el-button>-->
          <el-button v-if="row.status==2&&(isAdmin||btnRule.some(btn=>btn=='execute'))" type="success" size="mini"
                     icon="el-icon-finished"
                     @click="execute(row)">执行
          </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="reportVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleReportClose">
      <report @goBack="reportVisible=false" v-if="reportVisible" :reportData="reportData"></report>
    </el-drawer>
    <el-dialog top="10vh" class="execute-dialog" :close-on-press-escape="false" :close-on-click-modal="false" center
               :visible.sync="executeVisible" title="执行">
      <el-form ref="executeForm" :model="executeForm" size="small" label-width="120px">
        <el-form-item label="执行时间" prop="executionTime" :rules="[{
                    required: true, message: '执行时间不能为空', trigger: 'change'
                  }]">
          <el-date-picker
            placeholder="执行时间"
            size="small"
            style="width: 100%"
            clearable
            value-format="yyyy-MM-dd"
            v-model="executeForm.executionTime"
            type="date">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="天气" prop="weather">
          <el-input maxlength="20" clearable v-model="executeForm.weather" size="small" placeholder="请输入天气"/>
        </el-form-item>
        <el-form-item label="风向" prop="wind">
          <el-input maxlength="20" clearable v-model="executeForm.wind" size="small" placeholder="请输入风向"/>
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-input maxlength="20" clearable v-model="executeForm.temperature" size="small" placeholder="请输入温度"/>
        </el-form-item>
        <el-form-item label="飞行速度 (M/S)" prop="flightSpeed" :rules="[{
                    validator: validateNum, trigger: 'blur'
                  }]">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" maxlength="9" clearable
                    v-model="executeForm.flightSpeed" size="small" placeholder="请输入飞行速度 (M/S)"/>
        </el-form-item>
        <el-form-item label="飞行时间 (Min)" prop="flightTime" :rules="[{
                    validator: validateNum, trigger: 'blur'
                  }]">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" maxlength="9" clearable v-model="executeForm.flightTime"
                    size="small" placeholder="请输入飞行时间 (Min)"/>
        </el-form-item>
        <el-form-item label="飞行高度 (M)" prop="flightHeight" :rules="[{
                    validator: validateNum, trigger: 'blur'
                  }]">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" maxlength="9" clearable
                    v-model="executeForm.flightHeight" size="small" placeholder="请输入飞行高度 (M)"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input show-word-limit maxlength="200" clearable v-model="executeForm.remark" type="textarea" rows="5"
                    size="small"
                    placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="executeLoading" @click="executeMain('executeForm')" type="primary" size="medium"
                   icon="el-icon-finished">执行</el-button>
            <el-button size="medium" icon="el-icon-back"
                       @click="executeVisible = false">返回
            </el-button>
        </span>
    </el-dialog>
    <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>
    <el-drawer
      title="巡航轨迹"
      :visible.sync="trajectoryVisible"
      :direction="direction"
      :size="drawerWidth"
      :before-close="handleRrajectoryClose">
      <trajectory-dialog :driverId="driverId" v-if="trajectoryVisible"></trajectory-dialog>
    </el-drawer>
  </div>
</template>

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

  export default {
    name: "inspectDriverList",
    data() {
      var validateNum = (rule, value, callback) => {
        if (value) {
          let lengthP = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
          if (lengthP.test(value)) {
            if (value >= 1000000) {
              callback(new Error('不能大于999999.99'));
            } else {
              callback();
            }
          } else {
            callback(new Error('正整数最多两位小数点'));
          }
        } else {
          callback();
        }
      }
      return {
        trajectoryVisible:false,
        driverId:'',
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        validateNum: validateNum,
        reProcessBtnLoading: false,
        delBtnLoading: false,
        imageDetail: {},
        documentList: {},
        imageVisible: false,
        detailVisible: false,
        executeLoading: false,
        typeList: [
          {value: 1, label: '可见光巡检'},
          {value: 2, label: '多光谱巡检'}
        ],
        executeVisible: false,
        adminList: [],
        statusList: [],
        dataList: [],
        currentPage: 1,
        count: 0,
        pageSize: parseInt((document.body.clientHeight - 300 - 43) / 45),
        tableHeight: document.body.clientHeight - 300,
        tableLoading: false,
        searchParam: {
          type: '',
          inspectNo: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
          status: ''
        },
        ruleForm: {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: []
        },
        executeForm: {
          executionTime: '',
          weather: '',
          wind: '',
          temperature: '',
          flightSpeed: '',
          flightHeight: '',
          flightTime: '',
          remark: ''
        },
        pointLoading: false,
        reportData: {},
        reportVisible: false,
        pointData: {},
        pointVisible: false,
        mapImg: '',

      }
    },
    components: {report, point, pReport, imageList, driverAreaSelect,trajectoryDialog},
    created() {
    },
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    mounted() {
      this.tableLoading = true
      this.getDocument()
      this.getBaseData()
      this.getAllList()
    },
    methods: {
      handleRrajectoryClose(){
        this.trajectoryVisible=false
      },
      pointClick(row) {
        this.driverId=row.driverId
        this.trajectoryVisible=true
      },
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      handlePointClose(hide) {
        if (hide) {
          hide()
        }
        this.pointVisible = false
      },
      handleReportClose(hide) {
        if (hide) {
          hide()
        }
        this.reportVisible = false
      },
      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
          inspectApi.dropTask({id: data.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.delBtnLoading = false
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delBtnLoading = false
          })
        });
      },
      refreshReport(data) {
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          type: 'warning',
          message: h('div', null, [
            h('div', {style: 'color: #333333;padding-top: 25px;'}, '确认重处理此任务?'),
            h('div', {style: 'color: #999999;margin-top: 10px;'}, '重处理后任务，需要删除旧报告，重新生成新报告')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          this.reProcessBtnLoading = true
          inspectApi.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(() => {
        })
      },
      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
        })
      },
      getDocument() {
        inspectfileApi.getDocument().then(res => {
          this.documentList = res.data ? res.data : {}
        }).catch(e => {
          this.documentList = {}
        })
      },
      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
        })
      },
      executeMain(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            let executeForm = JSON.parse(JSON.stringify(this.executeForm))
            this.addBtnLoading = true
            inspectApi.executeTask(executeForm).then(res => {
              this.executeLoading = false
              this.$refs[formName].resetFields()
              this.$message({
                type: 'success',
                message: '任务执行成功'
              })
              this.executeVisible = false
              this.tableLoading = true
              this.getAllList()
            }).catch(e => {
              this.executeLoading = false
            })
          }
        })
      },
      initExecuteForm() {
        this.executeForm = {
          executionTime: '',
          weather: '',
          wind: '',
          temperature: '',
          flightSpeed: '',
          flightHeight: '',
          flightTime: '',
          remark: ''
        }
      },
      execute(data) {
        this.initExecuteForm()
        this.executeForm.id = data.id
        this.executeVisible = true
        this.$nextTick(function () {
          try {
            this.$refs['executeForm'].resetFields()
          } catch (e) {
          }
        })
      },
      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);
        }
      },
      toPrint: function (frameWindow) {
        try {
          setTimeout(function () {
            frameWindow.focus();
            try {
              if (!frameWindow.document.execCommand('print', false, null)) {
                frameWindow.print();
              }
            } catch (e) {
              frameWindow.print();
            }
            frameWindow.close();
          }, 10);
        } catch (err) {
          console.log('err', err);
        }
      },
      detailNo(item) {
        this.tableLoading = true
        inspectApi.getDetail({id: item.id}).then(res => {
          this.reportData = res.data
          this.reportVisible = true
          this.tableLoading = false
        }).catch(e => {
          this.reportData = {}
          this.tableLoading = false
        })
      },
      initSearchParam() {
        this.searchParam = {
          type: '',
          inspectNo: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
          status: '',
        }
      },
      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
        inspectApi.getInspectDriverList(searchParam).then(res => {
          this.dataList = res.data.records ? res.data.records : []
          this.count = res.data.total
          this.tableLoading = false
        }).catch(e => {
          this.dataList = []
          this.tableLoading = false
        })
      },
      getBaseData() {
        inspectApi.basicData().then(res => {
          const {statusList, adminList} = res.data
          this.statusList = statusList ? statusList : {}
          this.adminList = adminList ? adminList : []
        }).catch(e => {
          this.statusList = []
          this.adminList = []
        })
      }
    }
  }
</script>

<style lang="less">
  .inspect-driver-list {
    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;

    .upload-dialog, .image-dialog {
      .el-dialog {
        width: 600px !important;
      }
    }

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

        .el-dialog__header {
          padding: 0 !important;

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

    .execute-dialog {
      .el-dialog {
        width: 550px !important;
      }

      .el-range-editor--small.el-input__inner {
        width: 100% !important;
      }
    }


    .rw-dialog, .report-dialog {
      .el-dialog {
        width: 80% !important;
      }
    }

    .report-dialog {
      .el-dialog__header {
        padding: 0 !important;

        .el-dialog__headerbtn .el-dialog__close {
          color: #333333 !important;
        }
      }
    }
  }
</style>
