<template>
  <div>
    <div style="display:flex;justify-content: flex-end;margin-bottom:20px">
        <el-button @click="add">添加</el-button>
    </div>
    <el-table :data="tableData" v-loading="loading" :maxHeight="tableHeight" border style="width: 100%">
        <el-table-column label="无效案号" prop="invalidCaseNum" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.invalidCaseNum}}</span>
            </template>
        </el-table-column>
        <el-table-column label="被无效专利" prop="invalidedPatent" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.invalidedPatent}}</span>
            </template>
        </el-table-column>
        <el-table-column label="无效时间" prop="invalidTime" align="center">
            <template slot-scope="scope">
                <span v-if="scope.row.invalidTime">{{scope.row.invalidTime.substring(0,10)}}</span>
                <span v-else></span>
            </template>
        </el-table-column>
        <el-table-column label="无效理由" prop="invalidReason" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.invalidReason}}</span>
            </template>
        </el-table-column>
        <el-table-column label="是否被审查员认可" prop="ifApproved" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.ifApproved?'是':'否'}}</span>
            </template>
        </el-table-column>
        <el-table-column label="附件" prop="files" align="center">
            <template slot-scope="scope">
                <span>
                    <span v-if="scope.row.files && scope.row.files.length>0">
                        <div v-for="item in scope.row.files" style="margin:0;display:flex;justify-content:space-around;align-items:center;">
                            <p style="margin:0;width:calc(100% - 40px);overflow: hidden;white-space: nowrap;text-overflow:ellipsis;cursor: pointer">{{item.name?item.name+'.'+item.suffix:item.fileName}}</p> 
                            <Menu :data="item" @delFile="delFile(scope.row,item.id,1)"></Menu>
                        </div>
                    </span>
                    <span v-else><i class="el-icon-minus"></i></span>
                </span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-link @click="edit(scope.row)">编辑</el-link>
              <el-link type="danger" class="margin-left_10" @click="delData(scope.row)">删除</el-link>
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="visible" width="1000px" :before-close="close">
        <div>
            <el-form ref="form" :model="form" :rules="rules" label-width="140px">
                <el-form-item label="无效案号" prop="invalidCaseNum">
                    <el-input v-model="form.invalidCaseNum" placeholder="请输入无效案号"></el-input>
                </el-form-item>
                <el-form-item label="被无效专利" prop="invalidedPatent">
                    <el-input v-model="form.invalidedPatent" placeholder="请输入被无效专利"></el-input>
                </el-form-item>
                <el-form-item label="无效时间" prop="invalidTime">
                    <el-date-picker
                        style="width: 100%"
                        v-model="form.invalidTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期时间"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="无效理由" prop="invalidReason">
                    <el-input v-model="form.invalidReason" placeholder="请输入无效理由"></el-input>
                </el-form-item>
                <el-form-item label="是否被审查员认可" prop="approve">
                    <el-switch
                      v-model="form.ifApproved"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      :active-value="1"
                      :inactive-value="0">
                    </el-switch>
                </el-form-item>
                <el-form-item label="上传附件">
                    <div v-if="form.files" class="upload-file">
                        <div v-for="item in form.files" style="margin:0;display:flex;justify-content:space-around;">
                        <p style="margin:0;width:calc(100% - 40px);overflow: hidden;white-space: nowrap;text-overflow:ellipsis;cursor: pointer">{{item.name?item.name+'.'+item.suffix:item.fileName}}</p> 
                            <Menu :data="item" @delFile="delFile(form,item.id)"></Menu>
                        </div>
                    </div>
                    <el-upload  ref="upload" class="upload-file" drag action="#" :auto-upload="false" :show-file-list="true" :on-change="onChange" multiple  :on-preview="handlePreview" :on-remove="handleRemove">
                        <i :class="!file ? 'el-icon-upload' : 'el-icon-refresh'"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip"></div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div> 
        <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit" :loading="btnLoading">确定</el-button>
        </div> 
    </el-dialog>
  </div>
</template>

<script>
import Menu from '@/views/workspace/components/menu/index2.vue'
export default {
  components:{
      Menu
    },
  props:["patent"],
  data() {
    return {
        title:'新增无效证据使用历史',
        tableData:[],
        visible:false,
        btnLoading:false,
        loading:false,
        form:{},
        Already:[],
        file:[],
        queryParams:{
          current:1,
          size:10,
          patentNo:this.patent.patentNo
        },
        total:0,
        tableHeight:document.documentElement.clientHeight- 410,
        rules:{

        }
    };
  },
  watch: {
    patent(val){
      this.queryParams.patentNo = val.patentNo
      this.getList()
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    //查询数据
    getList(){
      this.loading = true
      this.$api.queryInvalidReasonHistory(this.queryParams).then(response=>{
        if(response.code == 200 ){
          this.tableData = response.data.records
          this.total = response.data.total
          this.loading = false
        }
      }).catch(error=>{
        this.tableData = []
        this.total = 0
        this.loading = false
      })
    },
    //打开弹窗
    add(){
      this.title = '新增无效证据使用历史'
      this.form = {}
      this.visible = true
    },
    //编辑数据
    edit(row){
      this.form = JSON.parse(JSON.stringify(row))
      this.title = '编辑无效证据使用历史'
      this.visible = true
    },
    //关闭弹窗
    close(){
       this.form = {}
       this.file = []
       this.$refs.upload.clearFiles()
       this.visible = false
    },
    //删除数据
    delData(row){
      this.deletes([row.id])
    },
    //批量删除
    deletes(ids){
      this.$confirm("确认删除本条数据吗？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}).then(() => {
          this.$api.deleteInvalidReasonHistory(ids).then(response=>{
            if(response.code == 200){
              this.$message.success('删除成功')
              this.getList()
            }
          }).catch(error=>{
            this.$message.error('删除失败')
          })
        })
      
    },
    //添加数据
    submit(){
        this.btnLoading = true
        let formData = new FormData()
          if(this.file && this.file.length>0){
            for (var i = 0; i < this.file.length; i++) {
              formData.append("files", this.file[i]);
            }
          }
          this.form.patentNo = this.patent.patentNo
          formData.append("history", JSON.stringify(this.form));
          this.$api.addOrUpdateInvalidReasonHistory(formData).then(response=>{
            if(response.code == 200){
              if(this.form.id){
                this.$message.success('更新成功')
              }else{
                this.$message.success('添加成功')
              }
              this.close()
              this.getList()
              this.btnLoading = false
            }
          }).catch(error=>{
            // if(this.form.id){
            //     this.$message.error('更新失败')
            //   }else{
            //     this.$message.error('添加失败')
            //   }
            this.btnLoading = false
          })
        
    },
    //分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    //删除文件
    delFile(row,id,index){
      console.log(row,id)
        var index1 = row.files.findIndex(item=>{
          return item.id == id
        })
        if(index1!=-1){
          row.files.splice(index1,1)
          console.log(row.files)
        }
        if(index){
          this.form = row
          this.submit()
          this.$nextTick(()=>{
            this.from = {}
          })
        }
        
    },
    //切换上传附件
    onChange(file, fileList) {
      if(this.form.files){
        var index3 = this.form.files.findIndex(item=>{
          return item.name+'.'+item.suffix == file.raw.name
        })
        if(index3!=-1){
          this.Already.push(this.form.files[index3].name)
          var index2 = fileList.reverse().findIndex(item=>{
            return item.raw.name == file.raw.name
          })
          fileList.splice(index2,1)
        }else{
          this.inFile(file, fileList)
        }
      }else{
        this.inFile(file, fileList)
      }
    this.$nextTick(()=>{
      var b = ''
      if(this.Already.length>0){
        this.Already.forEach(item=>{
          b = b+item+','
        })
        this.$alert('文件'+b+'已存在', '提示', {
          confirmButtonText: '确定',
          type:'warning',
          callback: action => {
            this.Already = []
          }
        });
        
      }
    })
    },
    //整理重复上传的文件
    inFile(file, fileList){
      var index = this.file.findIndex(item=>{
        return item.name == file.raw.name
      })
      if(index!=-1){
        this.Already.push(this.file[index].name)
        var index2 = fileList.reverse().findIndex(item=>{
          return item.raw.name == file.raw.name
        })
        fileList.splice(index2,1)
      }else{
        this.file.push(file.raw) 
      }
    },
    //删除未提交的附件
    handleRemove(file, fileList) {
      var index = this.file.findIndex(item=>{
        return item.uid == file.raw.uid
      })
      if(index!=-1){
        this.file.splice(index,1)
      }
      },
      //上传附件时查看附件内容
    handlePreview(file) {
          var item={
              name:file.name,
              suffix:'',
              downLoad:true
            }
            var index = file.raw.type.lastIndexOf('/')
            var type = file.raw.type.substring(index+1,file.raw.type.length)
            var arr = ['png','jpeg','bmp','jpg']
            if(arr.includes(type)){
              var FileUrl =  URL.createObjectURL(file.raw)
              var isPicture = 1
            }else if(type == 'pdf'){
              var FileUrl = URL.createObjectURL(file.raw)
              var isPicture = 0
            }else{
              return false
            }
            const router = this.$router.resolve({
                path: '/checkFile',
                query: {
                    row: JSON.stringify(item),
                    FileUrl: FileUrl,
                    isPicture:isPicture
                }
            })
            window.open(router.href, '_blank');
    },
  },
};
</script>
<style lang="scss" scoped>
</style>