<template>
  <div class="flex-column">
    <sticky :className="'sub-navbar'">
      <div class="filter-container">
        <el-row type="flex" justify="end" :gutter="24" >

          <el-col :span="4">
                 <el-select v-model="queryConditions.is_intact" placeholder="请选择" size="mini" clearable @change="intactClick">
                      <el-option
                          v-for="item in intactDatas"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                  </el-select>
          </el-col>

           <el-col :span="3">
               <el-input v-model="queryConditions.key" size="mini" placeholder="关键字"></el-input>
          </el-col>

          <el-col :span="2" style="text-align:left;padding-left:36px;">
            <!-- <el-button @click="handleAudit('pl')"  size="mini" plain>批量审核</el-button> -->
            <el-button size="mini" type="primary" @click="loadCompleteQueryList()">查询</el-button>
            <!-- <el-button size="mini" @click="resetQueryConditions()">重置</el-button> -->
            <!-- <el-button size="mini" type=""  v-print="'#printMe'">打印</el-button>
            &nbsp;
            <download-excel
              class="export-excel-wrapper"
              :data = "multipleSelection"
              :fields = "data_fields"
              name="案件导出数据.xls"
            >
               <el-button size="mini" type="" >导出</el-button>
            </download-excel> -->
          </el-col>
          <!-- <el-col :span="3">
            <el-button @click="downLoadExcel" type="success"  size="mini" plain>下载</el-button>
          </el-col> -->
        </el-row>
      </div>
    </sticky>
    <div class="app-container flex-item">
      <el-row class="bg-white fh">
        <el-table
            id="printMe"
            ref="multipleSelection"
            :data="dataList"
            tooltip-effect="dark"
            style="height: calc(100% - 120px);overflow-y:scroll;width:100%;"
            :key="tableKey"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="">
          </el-table-column>
          <el-table-column
              label="案件编号"
              prop="case_no"
              width="">
          </el-table-column>

          <!-- <el-table-column
              prop="case_name"
              label="案件名称"
              width="">
          </el-table-column> -->

          <el-table-column
              prop="case_description"
              label="案件描述"
              :show-overflow-tooltip="true"
              width="">
          </el-table-column>

           <!-- <el-table-column
              prop="start_time"
              label="开始时间"
              show-overflow-tooltip>
          </el-table-column>

           <el-table-column
              prop="end_time"
              label="结束时间"
              show-overflow-tooltip>
          </el-table-column>

          <el-table-column
              prop="case_status_name"
              label="是否逾期"
              width="80"
              show-overflow-tooltip>
          </el-table-column> -->

          <el-table-column
              prop="handle_status_name"
              label="办结状态"
              width="80"
              show-overflow-tooltip>
          </el-table-column>

          
          <el-table-column
              prop="createusername"
              label="上报人"
              show-overflow-tooltip>
          </el-table-column>
          <el-table-column
              prop="createtime"
              label="上报时间"
              show-overflow-tooltip>
          </el-table-column>

          <!-- <el-table-column
              prop="deal_username"
              label="处理人"
              show-overflow-tooltip>
          </el-table-column> -->

           <el-table-column prop="imageList" label="图片"  min-width="120" align="center">
            <template slot-scope="scope">
              <!-- {{scope.row.imageList}} -->
              <div style="100%" >
                <!-- &nbsp;  <el-image style="width:80px" @click="lookImage(scope.row.imageList)" :src="scope.row.imageList" alt="" lazy></el-image> -->
                <el-button  @click="lookImage(scope.row.imageList)" type="primary" size="mini">查看图片</el-button>
              </div>
              
              <!-- <span @click="lookImage(scope.row.imageList)">查看图片</span> -->
            </template>
          </el-table-column>

          <el-table-column label="操作" width="">
            <template slot-scope="scope">
              <!-- <el-button 
                         size="mini"
                         @click="handleEdit(scope.$index, scope.row)">处理
              </el-button> -->
              <el-button
                         size="mini"
                         @click="handleEdit(scope.row, false)">详情
              </el-button>

              <el-button  size="mini" @click="exportWord1(scope.row.id)">报表</el-button>
              <!-- <el-button
                         type="success"
                         size="mini"
                         @click="handleAudit(scope.$index, scope.row)">协办
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div>
            <!-- <span style="font-weight: bold">统计:</span> -->
            <!-- <span style="margin-left: 15px">建筑面积:{{ coveredArea }}</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span> -->
<!--            <span style="margin-left: 15px">拆除涉及面积:1111</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span>-->
<!--            <span style="margin-left: 15px">加固涉及面积:1111</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span>-->
<!--            <span style="margin-left: 15px">没收涉及面积:1111</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span>-->
<!--            <span style="margin-left: 15px">责令停止使用涉及面积:1111</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span>-->
<!--            <span style="margin-left: 15px">责令停工整改涉及面积:1111</span><span style="font-size: 14px">m<sup>2&nbsp;&nbsp;</sup></span>-->
<!--         -->
          </div>

          <div style="margin-top: 10px;text-align: right;margin-right: 100px">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="changePage"
                :current-page="queryConditions.page"
                :page-sizes="[10,20,50,100, 200, 300, 400,countPage]"
                :page-size="queryConditions.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="countPage">
            </el-pagination>
          </div>
        </div>
      </el-row>
    </div>
    <el-dialog
        width="60%"
        top="60px"
        :visible.sync="dialogFormVisible"
        style="overflow-y:scroll;height:1000px;"
        >
      <CaseDetail :only-show="onlyShow" :caseDetail="caseDetail" v-if="dialogFormVisible" :id="id"
            :dialog-form-visible="dialogFormVisible"></CaseDetail>
    </el-dialog>
     <el-image-viewer v-if="lookimageviewer" :on-close="closeViewer" :url-list="lookimgsrc" ></el-image-viewer>
  </div>

 
</template>

<script>
import Sticky from '@/components/Sticky'
import {getInformationCollectionList, getInformationExportExcel, postInformationVerify,getCompleteQueryList,getCaseInfo,ExportCaseWord} from "../../api/forms";

import CaseDetail from './widget/CaseDetail'
import {generateId} from "element-ui/src/utils/util";
import valTipVue from '../../components/cron/config/ext/valTip.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
// 导出Word相关插件
import Docxtemplater from 'docxtemplater';
import {saveAs} from 'file-saver';
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils';
import PizZip from 'pizzip'

let BASE_IMAGE_URL = process.env.VUE_APP_BASE_IMG_URL;
let BASE_URL = process.env.VUE_APP_BASE;


export default {
  name: "Forms",
  components: {
    Sticky,
    CaseDetail,
    ElImageViewer
  },
  data() {
    return {
      intactDatas:[
        { id: 0 , name: '未判读'},
        { id: 1 , name: '已提交'},
        { id: 99 , name: '已关闭'},
        { id: null , name: '全部'},
      ],
      tablewidth:1200,
      tableKey:Math.random(),
      obj:{
        nickName:"helloworld",
      },
      lookimageviewer:false,
      lookimgsrc:null,
      caseDetail:null,
      dataList:null,
      data_fields:{
        "案件编号":{
          field:"case_no",
          callback:value=>{
            return "&nbsp;"+value;
          }
        },
        "案件名称":"case_name",
        "案件地址":"address",
        "经纬度":"lng.lat",
        "处理人":"deal_username",
        "案件状态":"handle_status_name",
        "无人机编码":"drone_no",
        "上报人":"createusername",
        "上报时间":"createtime",
        "开始时间":"start_time",
        "结束时间":"end_time",
        "是否逾期":"case_status_name",
        "案件描述":"case_description",
      },
      queryConditions:{
        is_intact:null,
        handle_status_id:null,
        case_status_id:null,
        report_start_time:null,
        report_end_time:null,
        report_name:null,
        deal_username:null,
        key:null,
        page:1,
        limit:20,
        
      },
      multipleSelection: [],
      informationCollectionList: [],
      page: 1,
      dialogFormVisible: false,
      id: "",
      onlyShow: false,
      selectIdList: [],
      searchKeys: "",
      countPage: 1,
      limit: 10,
      datetime: "",
      starttime: "",
      endtime: "",
      coveredArea:0,
      currentCase:{},
    }
  },
  watch: {
    searchKeys: function () {
      this.page = 1;
      this.informationCollectionList = []
      this.loadInformationCollectionList()
    },
    page: function () {
      this.informationCollectionList = []
      this.loadInformationCollectionList()
    },
    limit: function () {
      this.page = 1;
      this.loadInformationCollectionList()
    },
    datetime: function (e) {

      if (e && e.length === 2) {
        this.starttime = e[0].Format('yyyy-MM-dd HH:mm:ss')
        this.endtime = e[1].Format('yyyy-MM-dd HH:mm:ss')
        this.page = 1;
        this.loadInformationCollectionList()
      } else {
        this.starttime = ""
        this.endtime = ""
        this.page = 1;
        this.loadInformationCollectionList()
      }
    }
  },
  beforeCreate(){
   
  },
  created(){

  },
  mounted() {
    this.loadCompleteQueryList();
  },
  methods: {
    intactClick(){
      this.queryConditions.page = 1
      this.loadCompleteQueryList();
    },
    exportWord1(id){
      ExportCaseWord({id:id}).then(res=>{
        if(res.code == 200){
          console.log(res);
          //  window.open("http://175.27.168.120:6016"+"/"+res.result);
           window.location.href = BASE_URL+"/"+res.result
          // console.log("http://175.27.168.120:6016"+"/"+res.result)
        }
      })
    },
    exportWord(row){
      this.currentCase = row;
      let _this = this;
      let printingCase = row;
      for(let key in printingCase){
        if(printingCase[key] == null){
          printingCase[key] = "未填写";
        }
      }
      JSZipUtils.getBinaryContent("reportpritingtemplate.docx",function(error, content){
        if (error) {
          throw error;
        }
        let zip = new JSZip(content);
        let doc = new Docxtemplater().loadZip(zip);
        doc.setData({
          ...printingCase,
        });
        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties
          };
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
        let out = doc.getZip().generate({
          type: "blob",
          mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        });

        // 将目标文件对象保存为目标类型的文件，并命名
        saveAs(out, "无人机执法违法监测报告"+_this.currentCase.case_no+".docx");
      })
    },
    base64DataURLToArrayBuffer(dataURL) {     //图片转base64
        const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
        if (!base64Regex.test(dataURL)) {
            return false;
        }
        const stringBase64 = dataURL.replace(base64Regex, "");
        let binaryString;
        if (typeof window !== "undefined") {
            binaryString = window.atob(stringBase64);
        } else {
            binaryString = new Buffer(stringBase64, "base64").toString("binary");
        }
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            const ascii = binaryString.charCodeAt(i);
            bytes[i] = ascii;
        }
        return bytes.buffer;
    },
    testBase64(){

    },
    printExcel(){
        console.log(this.multipleSelection);
    },
    handleSelectionChange(e) {
      this.multipleSelection = e;
      console.log(this.multipleSelection);

      this.selectIdList = []
      e.forEach(item => {
        this.selectIdList.push(item.id)
      })
    },
    handleEdit(e, i) {
      console.log(e,i);
      this.caseDetail = e;
      // this.id = this.informationCollectionList[e].id;
       this.dialogFormVisible = true
      // if (!i) {
      //   this.onlyShow = true
      // }
    },
    handleAudit(e) {
      let _this = this;
      let list = []
      if (e === 'pl') {
        //批量审核
        list = this.selectIdList
        if (!list.length) {
          _this.$message({
            type: 'error',
            message: '请选择!'
          });
          return false
        }
      } else {
        let id = this.informationCollectionList[e].id;
        list.push(id)
      }
      this.$confirm('通过审核, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        postInformationVerify(list).then(res => {
          if (res.code === 200) {
            if (e === 'pl') {
              _this.informationCollectionList.forEach((item, index) => {
                if (_this.selectIdList.includes(item.id)) {
                  _this.informationCollectionList[index].reviewStatus = '1'
                }
              })
            } else {
              _this.informationCollectionList[e].reviewStatus = '1'
            }
            _this.$message({
              type: 'success',
              message: '审核成功!'
            });
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    handleFilter(e) {
      console.log(e)
    },
    loadInformationCollectionList() {
      
  
      let _this = this;
      getInformationCollectionList(
          {
            page: this.page,
            key: this.searchKeys,
            limit: this.limit,
            starttime: this.starttime,
            endtime: this.endtime
          }
      ).then(response => {
        let res = response.result;
        _this.countPage = res.totalNumber
        _this.coveredArea = res._CoveredArea
        _this.informationCollectionList = res.informationCollectionList;
      })
    },
    closedOP() {
      this.dialogFormVisible = false
    },
    changePage(e) {
      this.queryConditions.page = e;
      this.loadCompleteQueryList();
      
    },
    handleSizeChange(e) {
      this.queryConditions.limit = e;
      this.loadCompleteQueryList();
    },
    downLoadExcel() {
      getInformationExportExcel(this.page, this.searchKeys, this.limit).then(res => {
        const aLink = document.createElement('a')
        let mimeType = "application/vnd.ms-excel"
        let blob = new Blob([res.data], {type: mimeType});
        //从response的headers中获取filename,
        //后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置文件名;
        let pattern = new RegExp('filename=([^;]+\\.[^.;]+);*')
        let contentDisposition = decodeURI(res.headers['content-disposition'])
        let result = pattern.exec(contentDisposition)
        let fileName = generateId() + ".xlsx"
        fileName = fileName.replace(/"/g, '')
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName // 设置下载文件名称
        document.body.appendChild(aLink)
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    loadCompleteQueryList(){
      // new Promise((success,error)=>{
      //   getCompleteQueryList(this.queryConditions).then(res=>{
      //     if(res.code == 200){
      //       success(res.data);
      //     }
      //   });
      // }).then(res=>{
      //   for(let i=0;i<res.length;i++){
      //     let info = new Promise((resolve,reject)=>{
      //         getCaseInfo({id:res[i].id}).then(obj=>{
      //           if(obj.code == 200){
      //             resolve(obj.result);
      //           }
      //         })
      //     });
      //     info.then(value=>{
      //       console.log("value",value);
      //       this.dataList[i] = value.info;
      //       console.log(this.dataList[i])
      //       // this.dataList[i].imageList = "http://175.27.168.120:6001/"+value[0];
      //     })
      //   }
      // });
 
      console.log(this.queryConditions.report_start_time);
      getCompleteQueryList(this.queryConditions).then(res=>{
        if(res.code == 200){
          // this.dataList = res.data;
          this.countPage = res.count;
          let _this = this;
          _this.dataList = res.data;
          for(let i=0;i<res.data.length;i++){
            //  _this.dataList[i] = res.data[i];
             let info = new Promise((resolve,reject)=>{
              // _this.getDetailCaseInfo(this.dataList[i].id);
                getCaseInfo({id:res.data[i].id}).then(obj=>{
                  if(obj.code == 200){
                    resolve(obj.result.pic_list);
                  }
                })
            });
            info.then(value=>{
              _this.dataList[i].imageList = [];
              for(let j = 0;j<value.length;j++){
                _this.dataList[i].imageList[j] = BASE_IMAGE_URL+"/"+value[j];
              }
              // _this.dataList[i].imageList = BASE_IMAGE_URL+"/"+value[0];
            })
          }
        }
        console.log("datalist",this.dataList);
        this.queryConditions.key = null;
      })
    },
    lookImage(images){
      this.lookimageviewer = true;
      this.lookimgsrc =images;
    },
    closeViewer(){
       this.lookimageviewer = false;
    },
    getDetailCaseInfo(id){
      getCaseInfo({id:id}).then(res=>{
        if(res.code == 200){
          return res.result;
        }
      })
    },
    resetQueryConditions(){
      for(let i in this.queryConditions){
        if(i == 'limit' || i == 'page'){
          continue;
        }else{
          this.queryConditions[i] = null;
        }
      }
      this.loadCompleteQueryList();
    }
  }
}
</script>

<style>
.custom-theme .el-table .cell {
  text-align: center !important;
}

.filter-container {
  padding: 5px;
}

.custom-theme .el-dialog__body {
  padding: 0 30px;
}

.custom-theme .el-dialog {
  height: calc(100% - 240px);
  overflow-y: hidden;
  position: relative;
}

.van-cell {
  padding: 10px 10px;
}

.el-table__body-wrapper is-scrolling-none {

}
</style>
>