<template>
  <div>
    <div style="margin-bottom: 10px;float: right;" v-if=" $reportPermission(reportId,[0,1])">
      <el-button type="primary" size="small" v-if="examine" @click="andClick('1')">上传无效请求书</el-button>
      <el-dropdown trigger="click" @command="andClick($event)" :hide-on-click="false" type="primary" size="small">
      <el-button type="primary" size="small">
        上传证据文献<i class="el-icon-arrow-down el-icon--right"></i>
      </el-button>
      <el-dropdown-menu slot="dropdown" class="text-align_center">
        <el-dropdown-item>
            <el-dropdown @command="andClick($event)" placement="right-start">
              <span class="el-dropdown-link"> 上传专利文件 </span>
                <el-dropdown-menu  class="children_item">
                  <el-dropdown-item command="3">专利号导入</el-dropdown-item>
                  <el-dropdown-item command="2">Excel导入</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
          </el-dropdown-item>
          <el-dropdown-item command="5">上传非专利文件</el-dropdown-item>
          <!-- <el-dropdown-item command="1" v-if="examine">上传无效请求书</el-dropdown-item> -->
      </el-dropdown-menu>
    </el-dropdown>



      <!-- 
      <el-button type="primary" size="small"  @click="andClick()">上传专利文件</el-button>
      <el-button type="primary" size="small"  @click="andClick(5)">上传非专利文件</el-button> -->
      <el-button class="margin-left_10" type="primary" size="small" v-if="examine"  @click="isExamine">报告审核</el-button>
    </div>
   <div>
    <el-table :data="tableData"  border style="width: 100%" v-if="show">
      <el-table-column prop="sortStr" align="center" label="排序" min-width="180">
        <template slot-scope="scope">
          <div>
              <el-link type="primary" @click="check(scope.row)">{{ scope.row.sortStr }}</el-link>
              <el-popover
                        placement="bottom"
                        width="200"
                        trigger="click"
                        v-if="$reportPermission(reportId,[0,1])"
                        >
                        <p>将本文件（<span style="color:red">{{ scope.row.sortStr }}</span>）作为：</p>
                        <el-tree
                          ref="tree"
                          :data="tableAll"
                          :props="{label:'sortStr',value:'id'}"
                          :allow-drop="allowDrop"
                          draggable
                          style="height: 300px;overflow: auto;">
                          <span class="custom-tree-node" slot-scope="{ node, data }"><el-radio v-model="val" @input="changeRadio(scope.row,data)" :label="data.id">{{ data.sortStr }}</el-radio></span>
                        </el-tree>
                        <p style="color:red">备注：选择其中一个文件与其交换位置</p>
                        <i class="el-icon-arrow-down el-icon--right" @click="getVal(scope.row)" slot="reference"></i>
                      </el-popover>
          </div>
        </template>
      
      </el-table-column>
      <el-table-column prop="proofName" align="center" label="名称" min-width="180"> 
        <!-- <template slot-scope="scope">
          <div>
            {{ scope.row.proofName }}
          </div>
        </template> -->
      </el-table-column>
      <el-table-column prop="proofType" align="center" label="文件类型" min-width="180"> </el-table-column>
      <el-table-column prop="remark" align="center" label="备注" min-width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.remark?scope.row.remark:'——' }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100" v-if=" $reportPermission(reportId,[0,1])">
        <template slot-scope="scope">
          <div>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color:red"> 删 除 </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;margin-top: 10px;">
      <el-pagination background layout="total, prev, pager, next, jumper" :current-page.sync="queryParams.current"
        :page-size.sync="queryParams.size" @current-change="handleCurrentChange" :total="queryParams.total">
      </el-pagination>
    </div>
   </div>

   <responseDialog ref="responseDialog" :reportId='reportId' @isFinish="handleFinish"></responseDialog>

   <el-dialog title="添加审核任务" :visible.sync="showTask" width="500px"  @close="handleCloseTask" append-to-body :close-on-click-modal="false">
      <el-form :model="task" :rules="TaskRules" ref="TaskForm" label-width="120px">
        <el-form-item label="任务名称 :" prop="taskName">
            <el-input v-model="task.taskName" type="text" placeholder="输入主题" />
          </el-form-item>
          <el-form-item label="审核人 :" prop="personnelId">
          <el-select style="width:100%;" ref="select1" v-model="task.personnelId" clearable filterable >
               <el-option v-for="item in personnelList" :key="item.id" :label="item.personnelName" :value="item.id"></el-option>
            </el-select>
            </el-form-item>
          <el-form-item label="完成日期 :" prop="endTime">
            <el-date-picker style="width:100%" v-model="task.endTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"  placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注 :" prop="remark">
            <el-input v-model="task.remark" type="textarea" placeholder="输入备注" />
          </el-form-item>
      </el-form>
     <span slot="footer" class="dialog-footer">
              <el-button @click="handleCloseTask">取 消</el-button>
              <el-button type="primary" @click="submitTask" >确 定</el-button>
        </span>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="showFile" width="1200px"  @close="handleFile" append-to-body  :close-on-click-modal="false">
      <!-- <importPatent :reportId="this.queryParams.reportId"></importPatent> -->
      <component :is='isComponent' :reportId="this.queryParams.reportId" :downloadId="8"></component>
        <!-- <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFile" >确 定</el-button>
        </span> -->
    </el-dialog>
  </div>
</template>

<script>
import responseDialog from "./responseDialog.vue"
import ExcelImport from "@/views/components/import/excelImport/importPatent.vue"
import PatentNoImport from "@/views/components/import/PatentNoImport/download.vue"

export default {
  props:['reportId','signPatentNo','examine'],
  components: {
    responseDialog,
    ExcelImport,
    PatentNoImport
  },
  data() {
    const isTime = (rule, value, callback) => {
      if (this.isEndTime) {
        this.isEndTimes = Date.parse(new Date)
      }
      
      let b = Date.parse(value)
      if (value) {
        if (b<this.isEndTimes) {
          callback(new Error('禁止选择现在及以前时间，请重新选择'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择时间'))
      }
    }
    return {
      tableData: [],
      tableAll: [],//排序所用，全部的证据文献
      queryParams: {
        reportId:this.reportId,
        signPatentNo:this.signPatentNo,
        size: 10,
        current: 1,
        orderType: '',//asc，desc
        total: 0,
      },
      form: {},
      showTask: false,
      showFile: false,
      title:'',
      isComponent:'',
      task: {},
      TaskRules:{
        taskName:[{ required: true, message: '请输入任务名称', trigger: 'blur' },],
        personnelId: [{ required: true, message: '请选择审核人', trigger: 'change' },],
        endTime: [{  required: true, validator:isTime, trigger: 'change' } ],
      },
      personnelList: [],//全部人员
      val: null,
      show: true,
    }
  },
  computed: {
  },
  watch: {
  },
  mounted() {
    this.getList()
    this.getListTable()
    //创建报告时打开
    if(this.examine){
      this.getAllPersonnelList()
    }
  },
  methods: {
    // 删除证据文献
    handleDelete(row) {
      this.$confirm('此操作将删除该证据文献, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [row.id]
        var index = this.tableAll.findIndex(item =>{
          return item.id == row.id
        })
        this.tableAll.splice(index,1)
        this.$api.deleteCompareFile(ids).then(response => {
          if (response.code == 200) {
            // this.getList()
            this.$message.success('删除证据文献成功')
            this.addOrder()
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
     //查看证据文献
     check(val) {
      // var router = this.$router.resolve({
      //   path: '/ContrastIndex/' + val.id,
      // })
      var router = this.$router.resolve({
        path: '/checkFileDetails/' + val.id,
      })
      let params = this.$s.getSession('params')
      params.type=7
      params.reportType=7
      params.aid=val.id
      params.signPatentNo=this.signPatentNo || val.proofConditions
      params.reportId=this.queryParams.reportId
      this.$s.setSession('params', params)
      window.open(router.href, '_blank');
    },
    //获取当前文献id
    getVal(val){
      this.val = val.id
    },
    //上下拖动
    allowDrop(draggingNode, dropNode, type){
      if(draggingNode.level == dropNode.level){
        return type === 'next' || type === 'prev'
      }else{
        return type === 'prev'
      }
    },
    //交换文献
    changeRadio(val1, node) {
      var index1 = this.tableAll.findIndex(item=>{//获取当前专利位置
        return item.id == val1.id
      })
      var index2 = this.tableAll.findIndex(item=>{//获取选中专利位置
        return item.id == node.id
      })
      this.tableAll[index1] = this.tableAll.splice(index2,1,this.tableAll[index1])[0]
      this.addOrder()
    },
    //证据文献排序
    addOrder() {
      var params ={
        "report": this.queryParams.reportId,
        "orders": this.tableAll.map((item,index) => {
          return {
            id: item.id,
            order:index+1
          }
        })
      }
      this.$api.addProodOrder(params).then(response => {
        if (response.code == 200) {
          this.show = false
          this.getList()
          this.getListTable()
          this.$nextTick(() => {
            this.show = true
          })
        }
      }).catch(error => {
        
      })
    },

    // 报告审核按钮,打开审核弹窗
    isExamine() {
      this.showTask=true
    },
    // 审核确认
    submitTask() { 
      this.$refs.TaskForm.validate((valid) => {
        if (valid) { 
          let formData = new FormData()
          let a = this.task
          a.reportId = this.queryParams.reportId
          a.personIds = [this.task.personnelId]
          a.type = 0
          formData.append('taskVO',JSON.stringify(a))
          this.$api.AddTask(formData).then(response=>{
              if (response.code == 200) {
              this.$message.success('报告创建成功并发送审核')
              this.handleCloseTask()
              this.$emit('show',false)
            }
          }).catch(error => {
            this.$message.error('报告创建失败')
          })
        }
      })
    },
    // 审核取消，关闭审核弹窗
    handleCloseTask() { 
      this.$refs.TaskForm.resetFields()
      this.task = {}
      this.showTask = false
    },
    //获取全部人员
    getAllPersonnelList(){
      this.$api.getTenantPersonnel().then(response=>{
        this.personnelList = response.data
      })
    },
    // 上传证据文献成功弹窗关闭
    handleFinish(val) {
      this.getList();
      this.getListTable()
    },
    //分页查询证据文献
    getList() {
      this.$api.queryProof(this.queryParams).then((res) => {
        if (res.code==200) {
          this.tableData=res.data
          this.queryParams.size=res.pageColumn.size
          this.queryParams.current=res.pageColumn.current
          this.queryParams.total=res.pageColumn.total
        }
      }).catch((error) => {
        
      })
    },
    //查询所有证据文献
    getListTable() {
      var params = {
        size: 999,
        current: 1,
        reportId:this.queryParams.reportId
      }
      this.$api.queryProof(params).then((res) => {
        if (res.code==200) {
          this.tableAll = res.data
        }
      }).catch((error) => {
        
      })
    },
    //打开上传文件弹窗
    andClick(val) {
      switch(val){
        case '1':
        case '5':
          this.form.reportId=this.queryParams.reportId
          this.form.processType=val
          this.$refs.responseDialog.open(this.form)
          break;
        case '2':
          this.title='Excel导入'
          this.isComponent = 'ExcelImport'
          this.showFile=true
          break;
        case '3':
          this.title='专利号导入'
          this.isComponent = 'PatentNoImport'
          this.showFile=true
          break;
      }
    },
    // 上传文件弹窗关闭
    handleFile() {
      this.getList()
      this.getListTable()
      this.showFile=false
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
  },
}
</script>

<style lang="scss" scoped>

</style>