<template>
  <div class="reportinput-container">
    <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.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" 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 min-width="120" 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 min-width="120" 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 show-overflow-tooltip prop="driverAreaText" label="区划" align="center"/>
      <el-table-column show-overflow-tooltip prop="driverName" label="河道名称" align="center"/>
      <el-table-column show-overflow-tooltip prop="formatInspectTime" label="巡检时间" width="160" align="center">
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="originalVideoUrl" label="原视频" align="center">
        <template slot-scope="scoped">
          <el-tooltip v-if="scoped.row.originalVideoUrl&&(isAdmin||btnRule.some(btn=>btn=='video'))" class="item"
                      effect="dark" content="查看原视频" placement="bottom">
            <el-button @click="videoClick(scoped.row.originalVideoUrl,'查看原视频')" type="primary" size="mini"
                       icon="el-icon-video-camera"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="videoUrl" label="压缩视频" align="center">
        <template slot-scope="scoped">
          <el-tooltip v-if="scoped.row.videoUrl&&(isAdmin||btnRule.some(btn=>btn=='video'))" class="item" effect="dark"
                      content="查看压缩视频" placement="bottom">
            <el-button @click="videoClick(scoped.row.videoUrl,'查看压缩视频')" type="primary" size="mini"
                       icon="el-icon-video-camera"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="imageUrl" label="正摄图" align="center">
        <template slot-scope="scoped">
          <el-tooltip v-if="scoped.row.imageUrl&&(isAdmin||btnRule.some(btn=>btn=='image'))" class="item" effect="dark"
                      content="下载正摄图" placement="bottom">
            <el-button @click="uploadDownImg(scoped.row.imageUrl)" type="primary" size="mini" icon="el-icon-download"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="reportUrl" label="电子报告" align="center">
        <template slot-scope="scoped">
          <el-tooltip v-if="scoped.row.reportUrl" class="item" effect="dark"
                      content="查看电子报告" placement="bottom">
            <el-button @click="uploadDownImg(scoped.row.reportUrl)" type="primary" size="mini" icon="el-icon-download"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="statusText" label="状态" align="center">
        <template slot-scope="scoped">
          {{scoped.row.status,statusList | filterName}}
        </template>
      </el-table-column>
      <el-table-column min-width="80" show-overflow-tooltip prop="formatInputUser" label="操作人" align="center"/>
      <el-table-column min-width="160" show-overflow-tooltip prop="formatInputTime" label="操作时间" align="center"/>
      <el-table-column v-if="isAdmin||btnRule.some(btn=>btn=='editUrl')" width="60" label="操作">
        <template slot-scope="scoped">
          <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='editUrl')" class="item" effect="dark" content="编辑"
                      placement="bottom">
            <el-button @click="handleEdit(scoped.row)" type="primary" size="mini" icon="el-icon-edit"/>
          </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="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 @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">
      <cVideo v-if="videoVisible" :videoUrl="videoUrl"></cVideo>
      <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>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible"
               title="编辑">
      <el-form ref="ruleData" :model="ruleData" size="small" label-width="100px"
               class="form">
        <el-form-item label="任务单号" prop="inspectNo">
          <el-input :disabled="true" v-model="ruleData.inspectNo" size="small"/>
        </el-form-item>
        <el-form-item label="行号" prop="num">
          <el-input :disabled="true" v-model="ruleData.num" size="small"/>
        </el-form-item>
        <el-form-item label="报告编号" prop="reportNo">
          <el-input :disabled="true" v-model="ruleData.reportNo" size="small"/>
        </el-form-item>
        <el-form-item label="区属" prop="driverAreaText">
          <el-input :disabled="true" v-model="ruleData.driverAreaText" size="small"/>
        </el-form-item>
        <el-form-item label="河道名称" prop="driverName">
          <el-input :disabled="true" v-model="ruleData.driverName" size="small"/>
        </el-form-item>
        <el-form-item label="巡检时间" prop="formatInspectTime">
          <el-input :disabled="true" v-model="ruleData.formatInspectTime" size="small"/>
        </el-form-item>
        <el-form-item label="原视频地址" prop="originalVideoUrl">
          <el-input clearable v-model="ruleData.originalVideoUrl" size="small" placeholder="请输入原视频地址"/>
        </el-form-item>
        <el-form-item label="压缩视频地址" prop="videoUrl">
          <el-input clearable v-model="ruleData.videoUrl" size="small" placeholder="请输入原视频地址"/>
        </el-form-item>
        <el-form-item label="正摄图地址" prop="imageUrl">
          <el-input clearable v-model="ruleData.imageUrl" size="small" placeholder="请输入原视频地址"/>
        </el-form-item>
        <el-form-item label="电子报告地址" prop="reportUrl">
          <el-input clearable v-model="ruleData.reportUrl" size="small" placeholder="请输入原视频地址"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                      <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium"
                                 @click="submitForm('ruleData')">提交
            </el-button>
            <el-button icon="el-icon-back" size="medium" class="back"
                       @click="resetForm('ruleData') ;addDialogVisible = false">返回</el-button>
        </span>
    </el-dialog>
  </div>
</template>

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

  export default {
    name: "reportinput-container",
    data() {
      return {
        drawerWidth: (document.body.clientWidth - 190) + 'px',
        direction: 'rtl',
        ruleData: {
          originalVideoUrl: '',
          videoUrl: '',
          imageUrl: '',
          reportUrl: ''
        },
        addBtnLoading: false,
        addDialogVisible: false,
        videoUrl: '',
        videoVisible: false,
        generateLoading: false,
        addLoading: false,
        detailVisible: false,
        statusList: [],
        dataList: [],
        currentPage: 1,
        count: 0,
        pageSize: parseInt((document.body.clientHeight - 300 - 43) / 44.5),
        tableHeight: document.body.clientHeight - 300,
        tableLoading: false,
        searchParam: {
          reportNo: '',
          inspectNo: '',
          driverName: '',
          driverArea: '',
          inspectTime: '',
          status: ''
        },
        videoTitle: '',
        ruleForm: {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: []
        },
        mapImg: ''
      }
    },
    components: {report, cVideo, driverAreaSelect},
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    created() {
    },
    mounted() {
      this.tableLoading = true
      this.getBaseData()
      this.getAllList()
    },
    methods: {
      handleDetailClose(hide) {
        if (hide) {
          hide()
        }
        this.detailVisible = false
      },
      handleVideoClose(hide) {
        if (hide) {
          hide()
        }
        this.videoVisible = false
      },
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addBtnLoading = true
            reportApi.editUrl(this.ruleData).then(res => {
              this.addBtnLoading = false
              this.addDialogVisible = false
              this.initRuleData()
              this.$refs[formName].resetFields()
              this.tableLoading = true
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
              this.getAllList()
            }).catch(e => {
              this.addBtnLoading = false
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.initRuleData()
        this.$refs[formName].resetFields()
      },
      initRuleData() {
        this.ruleData = {
          originalVideoUrl: '',
          videoUrl: '',
          imageUrl: '',
          reportUrl: ''
        }
      },
      handleEdit(row) {
        this.initRuleData()
        this.addDialogVisible = true
        let me = this
        this.$nextTick(function () {
          try {
            let ruleData = JSON.parse(JSON.stringify(row))
            me.ruleData = Object.assign({}, ruleData)
            me.$refs['ruleData'].resetFields()
          } catch (e) {

          }
        })
      },
      uploadDownImg(url) {
        window.location.href = url
      },
      videoClick(videoUrl, title) {
        this.videoVisible = true
        this.videoUrl = videoUrl
        this.videoTitle = title
      },
      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'>.BMap_Marker img{width: 32px;height: 35px;z-index: 999}.anchorBL {display: none !important;};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);
        }
      },
      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
        })
      },
      generateMain() {
        this.addLoading = true
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm))
        let descriptionList = []
        if (ruleForm.questionFileList && ruleForm.questionFileList.length > 0) {
          ruleForm.questionFileList.map(item => {
            let child = {
              id: item.id + '',
              description: item.questionContent ? item.questionContent : ''
            }
            descriptionList.push(child)
          })
        }
        let examineScore = []
        if (ruleForm.filterQuestionList && ruleForm.filterQuestionList.length > 0) {
          ruleForm.filterQuestionList.map(item => {
            let child = {
              questionId: item.id + '',
              examineScore: item.examineScore,
              checkScore: item.checkScore,
              remark: item.note
            }
            examineScore.push(child)
          })
        }
        let param = {
          id: ruleForm.id,
          imageUrl: ruleForm.imageUrl,
          videoUrl: ruleForm.videoUrl,
          examineScore: examineScore,
          manyiExamineScore: ruleForm.manyiExamineScore,
          manyiCheckScore: ruleForm.manyiCheckScore,
          awareExamineScore: ruleForm.awareExamineScore,
          awareCheckScore: ruleForm.awareCheckScore,
          totalExamineScore: ruleForm.totalExamineScore,
          totalCheckScore: ruleForm.totalCheckScore,
          desc: ruleForm.desc,
          descriptionList: descriptionList
        }
        reportApi.generateSub(param).then(res => {
          this.$message({
            type: 'success',
            message: '报告生成成功！'
          })
          this.detailVisible = false
          this.addLoading = false
          this.tableLoading = true
          this.getAllList()
        }).catch(e => {
          this.addLoading = false
        })

      },
      initRuleForm() {
        this.ruleForm = {
          videoUrl: '',
          imageUrl: '',
          examineScore: [],
          manyiExamineScore: '',
          manyiCheckScore: '',
          totalExamineScore: '',
          totalCheckScore: '',
          desc: '',
          descriptionList: [],
          filterQuestionList: [],
        }
      },
      initSearchParam() {
        this.searchParam = {
          reportNo: '',
          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
        reportApi.getInputList(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() {
        reportApi.getBaseData().then(res => {
          const {areaList, statusList} = res.data
          this.statusList = statusList ? statusList : {}
        }).catch(e => {
          this.statusList = []
        })
      },
    }
  }
</script>

<style lang="less">
  .reportinput-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;

    .el-input.is-disabled .el-input__inner {
      background-color: #fff !important;
      color: #333333 !important;
    }

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


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

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

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

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