<template>
  <div class="fileinspect-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: 150px"/>
      </el-form-item>
      <el-form-item label="河道名称">
        <el-input clearable v-model="searchParam.driverName" size="small" placeholder="请输入河道名称" style="width: 150px"/>
      </el-form-item>
      <el-form-item label="区划">
        <driverAreaSelect v-model="searchParam.driverArea"></driverAreaSelect>
      </el-form-item>
      <el-form-item label="查看范围">
        <el-select style="width: 150px" filterable v-model="searchParam.driverAreaType" size="small"
                   placeholder="请选择查看范围">
          <el-option v-for="(value,key,index) in driverAreaTypeList" :key="index" :label="value" :value="key+''"/>
        </el-select>
      </el-form-item>
      <el-form-item label="巡检开始时间">
        <el-date-picker
          style="width: 200px"
          placeholder="巡检开始时间"
          clearable
          size="small"
          value-format="yyyy-MM-dd"
          v-model="searchParam.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </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 label="河道类型" prop="driverExam">
        <el-select clearable style="width: 150px" v-model="searchParam.driverExam" 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>
        <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 width="50" show-overflow-tooltip prop="id" label="编号" align="center"/>
      <el-table-column width="130" show-overflow-tooltip prop="inspectNo" label="任务单号" align="center">
        <template slot-scope="scoped">
          <el-tooltip
            v-if="isAdmin||btnRule.some(btn=>btn=='view')"
            class="item"
            effect="dark" content="查看图片"
            placement="bottom">
            <a href="javascript:void(0);" @click="setMark(scoped.row,1)">{{scoped.row.inspectNo}}</a>
          </el-tooltip>
          <span v-else>{{scoped.row.inspectNo}}</span>
        </template>
      </el-table-column>
      <el-table-column 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 width="80" show-overflow-tooltip prop="totalNum" label="图片数量" align="center"/>
      <el-table-column width="120" show-overflow-tooltip label="未标记/已标记" align="center">
        <template slot-scope="scoped">
          {{scoped.row.unsignNum}}/{{scoped.row.signNum}}
        </template>
      </el-table-column>
      <el-table-column width="80" show-overflow-tooltip prop="statusText" label="任务状态" align="center"/>
      <el-table-column width="120" show-overflow-tooltip prop="lastUploadTime" label="最近上传时间" align="center"/>
      <el-table-column width="120" show-overflow-tooltip prop="formatExecutionTime" label="巡检时间" align="center"/>
      <el-table-column label="操作" align="left" width="250">
        <template slot-scope="{row}">
          <el-tooltip v-if="row.canOption==1&&row.status==3&&(isAdmin||btnRule.some(btn=>btn=='upload'))" class="item"
                      effect="dark" content="上传"
                      placement="bottom">
            <el-button @click="uploadItem(row)" type="primary" size="mini" icon="el-icon-upload2"/>
          </el-tooltip>
          <el-button
            v-if="row.canOption==1&&row.status==3&&row.lastUploadTime&&(isAdmin||btnRule.some(btn=>btn=='setMark'))"
            type="success" size="mini" icon="el-icon-rank" :loading="signLoading"
            @click="setMark(row,2)">标记
          </el-button>
          <el-button
            v-if="row.canOption==1&&row.status==3&&row.lastUploadTime&&(isAdmin||btnRule.some(btn=>btn=='markFinish'))"
            :loading="finishedLoading" size="mini" icon="el-icon-finished" @click="finished(row)">标记完成
          </el-button>
          <el-tooltip
            v-if="row.canOption==1&&row.status!=3&&row.lastUploadTime&&(isAdmin||btnRule.some(btn=>btn=='download'))"
            class="item" effect="dark" content="下载"
            placement="bottom">
            <el-button :loading="downLoading" @click="downMain(row)" type="primary" size="mini"
                       icon="el-icon-download"/>
          </el-tooltip>
          <el-tooltip
            v-if="row.canOption==1&&row.status==3&&row.lastUploadTime&&(isAdmin||btnRule.some(btn=>btn=='drop'))"
            class="item" effect="dark" content="删除"
            placement="bottom">
            <el-button type="danger" size="mini" class="el-icon-delete" :loading="delLoading"
                       @click="handleDelete(row)"></el-button>
          </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-dialog :close-on-press-escape="false" :close-on-click-modal="false" class="upload-dialog" top="5vh" center
               :visible.sync="uploadVisible" title="上传图片">
      <el-form ref="uploadForm" :model="uploadForm" size="small" label-width="110px">
        <el-form-item label="图片分类" prop="fileDocument" :rules="{
                    required: true, message: '图片分类不能为空', trigger: 'change'
                  }">
          <el-select style="width: 150px" filterable clearable v-model="uploadForm.fileDocument" size="small"
                     placeholder="请选择图片分类">
            <el-option v-for="(value,key,index) in documentList" :key="index" :label="value" :value="key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="file" :rules="{
                    required: true, message: '图片分类不能为空', trigger: 'blur'
                  }">
          <uploadImage v-if="uploadVisible" :isCompress="true" ref="uploadImage" v-model="uploadForm.file"
                       :baseList="baseList"
                       v-on:addImage="addImage" v-on:removeImage="removeImage"></uploadImage>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="uploadLoading" @click="uploadSubmit('uploadForm')" type="primary" size="medium"
                   icon="el-icon-upload2">上传</el-button>
            <el-button size="medium" icon="el-icon-back"
                       @click="initUploadForm();uploadVisible = false">返回
            </el-button>
        </span>
    </el-dialog>
    <el-dialog @close="imageVisible = false;getAllList()" :close-on-press-escape="false" :close-on-click-modal="false" class="image-dialog" top="2vh" center
               :visible.sync="imageVisible" title="图片">
      <image-list :selectType="selectType" ref="imageList" @sign="clickSign" :type="signType==1?'show':'sign'" :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-dialog :fullscreen="true" :close-on-press-escape="false" :close-on-click-modal="false" class="sign-dialog"
               center :visible.sync="signVisible" title="标注">
      <signBox :btnRule="btnRule" :isAdmin="isAdmin" @cancelBak="signBack" @uploadImg="uploadImg" ref="signBox"
               :questionList="questionList" :documentList="documentList" :signImageDetail="signImageDetail"
               v-if="signVisible"></signBox>
    </el-dialog>
  </div>
</template>

<script>
  import inspectfileApi from '@/api/file/inspectfile'
  import inspectApi from '@/api/business/inspect'
  import driverAreaSelect from '@/components/driverAreaSelect'
  import uploadImage from '@/components/fileUploadImage'
  import imageList from '../imageList'
  import signBox from '../sign'
  import {mapGetters} from "vuex";

  export default {
    name: "fileinspect-list",
    data() {
      return {
        downLoading: false,
        delLoading: false,
        finishedLoading: false,
        signVisible: false,
        imageDetail: {},
        signImageDetail: {},
        signLoading: false,
        imageVisible: false,
        uploadLoading: false,
        documentList: {},
        uploadVisible: false,
        dataList: [],
        currentPage: 1,
        count: 0,
        pageSize: parseInt((document.body.clientHeight - 300- 43) / 44.5),
        signType: 1,
        tableHeight: document.body.clientHeight - 300,
        tableLoading: false,
        searchParam: {
          inspectNo: '',
          driverName: '',
          driverArea: '',
          time: '',
          status:'',
          driverAreaType:'1'
          // driverExam:''
        },
        driverAreaTypeList:{
          1:'区划所有',
          2:'本级河湖'
        },
        selectType:{},
        baseList: [],
        questionList: [],
        statusList:[],
        uploadForm: {
          file: [],
          inspectDriverId: '',
          fileDocument: ''
        },
      }
    },
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    components: {uploadImage, imageList, signBox,driverAreaSelect},
    created() {
    },
    mounted() {
      this.tableLoading = true
      this.getBaseData()
      this.getDocument()
      this.getQuestionList()
      this.getAllList()
    },
    methods: {
      handleDelete(row) {
        this.$confirm('确定要删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delLoading = true
          inspectfileApi.drop({id: row.id}).then(res => {
            this.delLoading = false
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.delLoading = false
          })
        })
      },
      finished(row) {
        this.$confirm('确定标记完成吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.finishedLoading = true
          inspectfileApi.setMarkFinish({id: row.id}).then(res => {
            this.finishedLoading = false
            this.$message({
              type: 'success',
              message: '标记完成成功！'
            })
            this.tableLoading = true
            this.getAllList()
          }).catch(e => {
            this.finishedLoading = false
          })
        })
      },
      downMain(row) {
        this.delLoading = true
        inspectfileApi.down({id: row.id}).then(res => {
          console.log(res)
          window.open(res.data)
          this.delLoading = false
        }).catch(e => {
          this.delLoading = false
        })
      },
      uploadImg(...data) {
        inspectfileApi.downPic({id: data[0]}).then(res => {
          let url = window.URL.createObjectURL(res)
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', data[1].split('/')[data[1].split('/').length - 1])
          document.body.appendChild(link)
          link.click()
          this.$refs.signBox.uploadLoading = false
        }).catch(e => {
          this.$refs.signBox.uploadLoading = false
        })
      },
      removeImage(...data) {
        this.uploadForm.file.splice(data[0], 1)
        this.baseList.splice(data[0], 1)
      },
      addImage(...data) {
        this.uploadForm.file.push(data[0])
        this.baseList.push(data[1])
        if(this.baseList.length==data[2]){
          this.$refs.uploadImage.uploadLoading=false
        }
      },
      initUploadForm() {
        this.baseList = []
        this.uploadForm = {
          file: [],
          inspectDriverId: '',
          fileDocument: ''
        }
      },
      uploadItem(data) {
        this.initUploadForm()
        this.uploadVisible = true
        this.$nextTick(function () {
          try {
            this.uploadForm.inspectDriverId = data.id
            this.$refs['uploadForm'].resetFields()
          } catch (e) {
          }
        })
      },
      uploadSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.uploadLoading = true
            let param = {
              fileList:this.uploadForm.file,
              inspectDriverId:this.uploadForm.inspectDriverId,
              fileDocument: this.uploadForm.fileDocument
            }
            inspectfileApi.uploadPic(param).then(res => {
              this.uploadLoading = false
              this.$refs[formName].resetFields()
              this.$message({
                type: 'success',
                message: '上传图片成功'
              })
              this.uploadVisible = false
              this.tableLoading = true
              this.getAllList()
            }).catch(e => {
              this.uploadLoading = false
            })
          }
        })
      },
      initSearchParam() {
        this.searchParam = {
          inspectNo: '',
          driverName: '',
          driverArea: '',
          time: '',
          status:'',
          driverAreaType:'1'
          // 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.time && searchParam.time.length > 0) {
          searchParam.inspectTime = searchParam.time[0] + '~' + searchParam.time[1]
        }
        delete searchParam.time
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        inspectfileApi.getPicList(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 {areaList,statusList} = res.data
          this.statusList = statusList?statusList:[]
        }).catch(e => {
          this.statusList =[]
        })
      },
      getDocument() {
        inspectfileApi.getDocument().then(res => {
          this.documentList = res.data ? res.data : {}
        }).catch(e => {
          this.documentList = {}
        })
      },
      getQuestionList() {
        inspectfileApi.getQuestionList().then(res => {
          this.questionList = res.data ? res.data : []
        }).catch(e => {
          this.questionList = []
        })
      },
      setMark(row, type) {
        let method = 'setMark'
        if(type==1){
          method= 'getDetail'
        }
        this.signType = type
        this.signLoading = true
        inspectfileApi[method]({id: row.id}).then(res => {
          this.signLoading = false
          let imageDetail = {
            taskId: row.id,
            driverName: row.driverName,
            formatExecutionStartTime: row.formatExecutionTime,
            imgList: res.data ? res.data : []
          }
          this.imageDetail = Object.assign({}, imageDetail)
          this.imageVisible = true
        }).catch(e => {
          this.signLoading = false
        })
      },
      signBack() {
        this.selectType={}
        this.signVisible = false
        inspectfileApi.setMark({id: this.imageDetail.taskId}).then(res => {
          let imageDetail = JSON.parse(JSON.stringify(this.imageDetail))
          imageDetail.imgList = res.data ? res.data : []
          this.imageDetail = Object.assign({}, imageDetail)
        }).catch(e => {
        })
      },
      clickSign(...data) {
        this.signVisible = true
        this.signImageDetail = data[0]
      }
    }
  }
</script>

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

    .sign-dialog {
      .el-dialog {
        width: 100% !important;

        .el-dialog__body {
          padding-bottom: 0px;
        }
      }
    }
  }
</style>
