<template>
  <div>
    <!-- 创建报告-->
    <el-dialog :title="title" :visible.sync="showDialog" width="600px" :close-on-click-modal="false"  @close="handleClose(false)" >
        <el-form :model="form" :rules="rules" ref="reportForm" label-width="120px" v-loading="loading" :element-loading-text="load_text" element-loading-spinner="el-icon-loading"
    element-loading-background-color="rgba(0, 0, 0, 0.8)">
            
            <el-form-item :label="[3].includes(Number(form.type))?'标的产品':'标的专利'" prop="signPatentNo">
              <el-input v-model="form.signPatentNo" autocomplete="off" :placeholder="[3].includes(Number(form.type))?'请输入标的产品':'请输入标的专利'" @change="getPatentNo"></el-input>
              <p v-if="show==1" class="tips">查不到该专利请
                <!-- <el-upload style="display:inline-block;width: 30px !important;" ref="uploads" class="upload-file" action="#" :auto-upload="false" :show-file-list="false" :on-change="onChange1">
                  <span>导入</span>
                </el-upload> -->
                  <span @click="importPatentNo()">导入</span>
                </p>
              <p v-if="show==2" class="tips" style="color:black"><span @click="toPatentDetails(form.signPatentNo)">查看详情</span></p>
            </el-form-item>
            <el-form-item label="报告名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" placeholder="请输入报告名称"></el-input>
            </el-form-item>
            <el-form-item label="是否完成" v-if="!form.id"> 
              <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeStatus"
                :active-value="3"
                :inactive-value="1">
              </el-switch>
            </el-form-item> 
            <el-form-item label="核心结论" v-if="!form.id && form.status == 3">
              <el-checkbox-group v-model="form.conclusionIds">
                <el-checkbox v-for="item in conclusion" :key="item.dictChildValue" :label="item.dictChildValue">{{ item.dictChildLabel }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="结论论述" v-if="!form.id &&form.status == 3">
              <el-input v-model="form.cronConclusion" type="textarea" placeholder="请输入结论论述"></el-input>
            </el-form-item>
            <el-form-item label="后续跟进事项" v-if="!form.id &&form.status == 3 && $permission('/rms/matter')">
             <span v-if="form.followUps"><span v-for="item in form.followUps" :key="item.followUpName" style="margin-right:10px">{{ item.followUpName}}</span></span> 
              <span>
                <el-popover
                ref="popover"
                placement="bottom"
                @hide="hidePopover"
                @show="showPopover"
                trigger="click">
                <div>
                  <addMatter :type="matterType" :sign="matterSign" @value="getMatter"></addMatter>
                </div>
                <el-button slot="reference">添加后续事项</el-button>
              </el-popover>
              </span>
              
            </el-form-item>
            <el-form-item label="承担部门" prop="departmentId">
              <Select-Tree :options="departmentList" @getValue="getDepartmentId" :value="form.departmentId"></Select-Tree>
            </el-form-item>
            <el-form-item label="负责人" prop="personId">
              <el-select v-model="form.personId" placeholder="请选择负责人" filterable  :popper-append-to-body="false">
                <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="clientId" v-if="tenantType == 1">
              <el-select v-model="form.clientId" placeholder="请选择委托方" filterable :popper-append-to-body="false">
                <el-option v-for="item in clientList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="委托方" prop="clientId">
              <el-select v-model="form.clientId" placeholder="请选择委托方">
                <el-option v-for="item in clientList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="产品/技术">
              <el-input v-model="form.proTec" autocomplete="off" placeholder="请输入产品/技术"></el-input>
            </el-form-item>
            <el-form-item label="应用场景">
              <el-select v-model="form.scenarioList" multiple clearable placeholder="请选择应用场景" :popper-append-to-body="false">
                <el-option v-for="item in dictsFromPASList" :key="item.id" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联报告">
              <el-input v-model="form.associateReportName" autocomplete="off" placeholder="请输入关联报告"></el-input>
            </el-form-item>
            <el-form-item label="需要复制的选项" v-show="form.track">
              <el-select v-model="form.copyIds" multiple clearable placeholder="请选择需要复制的选项" :popper-append-to-body="false" @change="changeCopyIds">
                <el-option v-for="item in copyList" :key="item.dictChildValue" :label="item.dictChildLabel" :value="item.dictChildValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="案件编号" v-if="form.type==7">
              <el-input v-model="form.caseNumber" autocomplete="off" placeholder="请输入案件编号"></el-input>
            </el-form-item>
            <el-form-item label="发文序号"  v-if="form.type==7">
              <el-input v-model="form.issueNumber" autocomplete="off" placeholder="请输入发文序号"></el-input>
            </el-form-item>
            <el-form-item label="发明创造名称"  v-if="form.type==7">
              <el-input v-model="form.inventionName" autocomplete="off" placeholder="请输入发明创造名称"></el-input>
            </el-form-item>
            <el-form-item label="专利权人"  v-if="form.type==7">
              <el-input v-model="form.currentApplication" autocomplete="off" placeholder="请输入专利权人"></el-input>
            </el-form-item>
            <el-form-item label="无效宣告请求人"  v-if="form.type==7">
              <el-input v-model="form.invalidApplication" autocomplete="off" placeholder="请输入无效宣告请求人"></el-input>
            </el-form-item>
            <el-form-item label="卷号" prop="volumeNumber" >
              <el-input v-model="form.volumeNumber" autocomplete="off" placeholder="请输入卷号"></el-input>
            </el-form-item>
            <el-form-item :label="(!form.id &&form.status==3)?'上传报告文档':'上传附件'">
              <div v-if="form.reportFiles" class="upload-file">
                <div v-for="item in form.reportFiles" 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"></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-item label="备注" prop="remark" >
              <el-input type='textarea' v-model="form.remark" autocomplete="off" placeholder="请输入备注"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" v-if="$reportPermission(form.id,[0,1])">
              <el-button @click="handleClose(false)">取 消</el-button>
              <el-button type="primary" @click="ifNext " v-if="form.type==7 && !form.id">下一步</el-button>
              <el-button type="primary" @click="ifDialog "  v-else>确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog title="添加审核任务" :visible.sync="showTask" width="500px"  @close="handleCloseTask">
      <el-form :model="task" :rules="TaskRules" ref="TaskForm" label-width="120px" v-loading="loading">
        <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 :visible.sync="showFile">
      <div width="1200px">
        <iframe :src="imageUrl" frameborder="0" width="900px" height="500px"></iframe>
      </div>
      
    </el-dialog>

    <el-dialog :visible.sync="showEvidenceAndRequest" width="1000px" :close-on-click-modal="false">
      <evidenceAndRequest ref="evidence" :examine="true" :reportId="reportId" @show="showEvidenceAndRequest = false"></evidenceAndRequest>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SelectTree from '@/views/workspace/components/common/treeSelect.vue'
import { PatentDetails } from "@/views/workspace/folder/components/mixins";
import PersonnelList from './personnelList.vue'
import Menu from '@/views/workspace/components/menu/index.vue'
import addMatter from "./matter/addMatter.vue";
import evidenceAndRequest from "@/views/report/InvalidResponse/components/evidenceAndRequest.vue";

export default {
  props: ['isTrue'],
  mixins:[PatentDetails],
  components:{
    SelectTree,
    PersonnelList,
    addMatter,
    Menu,
    evidenceAndRequest,
  },
  data() {
    //校验部门是否为空
    const isDepartmentId = (rule,value,callback)=>{
      if(!this.form.departmentId && rule.required){
        callback(new Error('请选择部门'))
      }else{
        callback()
      }
    }
    const isExist = (rule, value, callback) => {
      if(!this.form.signPatentNo){//没有专利号进入报错提示
        this.show = 0
        if([3].includes(Number(this.form.type))){
          var text = '请输入标的产品'
        }else{
          var text = '请输入标的专利号'
        }
        callback(new Error(text))
      }else if(this.form.signPatentNo!=''){//有，且不为空，再判断该专利号是否存在
        if([3].includes(Number(this.form.type)) == false){//避免点击确定时再次调用该接口
          this.$api.PatentByPatentNo({patentNo:this.form.signPatentNo}).then(response=>{
              if(Object.keys(response.data).length!=0){
                this.loading = false
                callback()
                this.show = 2
              }else{
                this.loading = false
                callback(new Error(' '))
                this.show = 1
              }
            }).catch(error => {
              this.loading = false
              callback(new Error(' '))
              this.show = 1
          })
        }else{
          callback()
        }
      
      }
    }
    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('请选择时间'))
      }
    }
    const isClientId = (rule,value,callback)=>{
      if(this.tenantType == 1){
        if(value || !rule.required){
          callback()
        }else{
          callback(new Error('请选择委托方'))
        }
      }else{
        callback()
      }
    }
    return {
      matterType:null,
      matterSign:false,
      tenantType:'',
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      showTask:false,
      task:{},
      showPercentage:false,
      percentage:0,
      loading:false,
      imageUrl:'',
      showFile:false,
      file:[],
      form: {
        signPatentNo: "",
      },
      show:0,
      title:'',
      verify:false,
      showPerson:false,
      person:'',
      departmentList:[],
      clientList:[],
      personnelList:[],
      dictsFromPASList:[],
      reportAsDicItem:{
        "0":"INVALID_ASSESS",
        "1":"THIRD_ASSESS",
        "2":"STABILITY_ASSESS",
        "3":"FTO_ASSESS",
        "4":"TORT_ASSESS",
        "5":"AVOID_ASSESS",
        "7":"REINVALID_ASSESS",
      },
      reportAsDicItemCopy:{
        "0":"INVALID_COPY",
        "1":"THIRD_COPY",
        "2":"STABILITY_COPY",
        "3":"FTO_COPY",
        "4":"TORT_COPY",
        "5":"AVOID_COPY",
      },
      copyList:[],
      copyIndex:{},
      conclusion:[],
      rules: {//校验,
        name: [{ required: true, message: '请输入报告名称', trigger: 'blur' },],
        signPatentNo: [{ required: true, validator:isExist, trigger: 'blur' },],
        personId: [{ required: true, message: '请选择负责人', trigger: 'change' },],
        clientId: [{ required: true, validator:isClientId, trigger: 'change' },],
        // departmentId: [{ required: true, validator:isDepartmentId, trigger: 'change' },],
      },
      TaskRules:{
        taskName:[{ required: true, message: '请输入任务名称', trigger: 'blur' },],
        personnelId: [{ required: true, message: '请选择审核人', trigger: 'change' },],
        endTime: [{  required: true, validator:isTime, trigger: 'change' } ],
      },
      // 控制弹出框显示隐藏
      showDialog: false,
      Already:[],
      load_text: '',
      isEndTime:true,
      isEndTimes: null,
      newReportId: null,
      formCopy: {},
      showEvidenceAndRequest:false,
      reportId:null,
    };
  },
  computed: {
    ...mapGetters(['webSocket',]),
    dictMessage() {
      return this.$store.state.dictMessage.dictMessage
    },
    userinfo() {
      return this.$store.state.admin.userinfo
    },
  },

  mounted() {
    this.getAllPersonnelList()
    this.getAllClientList()
    this.getAllDepartmentList()
    this.getDictsFromPAS()
  },
  methods: {
    //导入专利
    importPatentNo(){
      var params = {
        patentNo:this.form.signPatentNo
      }
      this.$api.importByNos(params).then(res => {
          // console.log(res.code);
          if (res.code == 200) {
            if (res.data && res.data.length > 0) {
            } else {
              this.load_text = '专利导入中'
              this.loading = true
              this.initTask()
            }
          }
        }).catch(error => {
        })
    },
    //隐藏popover
    hidePopover(){
      this.matterSign = true
    },
    //显示popover
    showPopover(){
      this.matterSign = false
    },
    //切换是否完成状态
    changeStatus(val){
      if(val == 3){
        this.rules.personId[0].required = false
        this.rules.clientId[0].required = false
        // this.rules.departmentId[0].required = false
        if (!this.form.id) {
          this.$set(this.form,'conclusionIds',[])
        }
        this.conclusion = this.dictMessage[this.reportAsDicItem[this.form.type]]
        this.matterType = 2
      }else{
        this.rules.personId[0].required = true
        this.rules.clientId[0].required = true
        // this.rules.departmentId[0].required = true
        this.matterType = null
      }
    },
    //关闭审核弹窗
    handleCloseTask(){
      this.matterType = null
      this.$refs.TaskForm.resetFields()
      this.task = {}
      this.showTask = false
      this.isEndTime=true
    },
    //提交审核任务
    submitTask() {
      this.isEndTime=false
      this.$refs.TaskForm.validate((valid) => {
        if (valid) {
          // this.form.status = 0
        let formData = new FormData()
          if(this.file){
            for (var i = 0; i < this.file.length; i++) {
              formData.append("files", this.file[i]);
            }
          }
        var a = {
          report:this.form,
          personIds:[this.task.personnelId],
          // taskName:this.form.name+'审核',
          taskName:this.task.taskName,
          endTime:this.task.endTime,
          remark:this.task.remark,
          type:0
        }
        formData.append('taskVO',JSON.stringify(a))
        this.$api.AddTask(formData).then(response=>{
          if(response.code == 200){
            this.file = []
            // this.$refs.upload.clearFiles()
            this.$message.success('报告创建成功并发送审核')
            this.$emit('getList',true)
            this.handleCloseTask()
            this.handleClose()
          }
        }).catch(error=>{
          this.$message.error('报告创建失败')
          this.handleCloseTask()
        })
        }
      })
    },
    //删除已上传的附件
    delFile(id){
      var index = this.form.reportFiles.findIndex(item=>{
        return item.id == id
      })
      if(index!=-1){
        this.form.reportFiles.splice(index,1)
      }
    },
    //切换上传附件
    onChange(file, fileList) {
      if(this.form.reportFiles){
        var index3 = this.form.reportFiles.findIndex(item=>{
          return item.name+'.'+item.suffix == file.raw.name
        })
        if(index3!=-1){
        
          this.Already.push(this.form.reportFiles[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) 
      }
    },
    //上传专利文件
    onChange1(file, fileList){
      let formData = new FormData()
      formData.append('file', file.raw)
      this.$api.import(formData).then(response => {
        // this.$message.success('任务创建成功')
        this.load_text = '专利导入中'
        this.loading = true
        this.initTask()
        // isExist()
      }).catch(error => {
        this.loading = true
      })
    },
    //websocket 后端发送信息
    initTask() {
      // var webSocket = new WebSocket(`ws://192.168.1.11:8877/api/v2/ws/328`)
      var webSocket =this.webSocket
      if(webSocket){
        webSocket.onmessage = (e) => {
        // console.log(e)
        const { code, data, message } = JSON.parse(e.data)
        if (code === 903 || code === 904) {
          this.loading = false
          this.$message.success('专利导入成功')
          this.$refs['reportForm'].validateField('signPatentNo');
        } else if (code === 803 || code === 804) {
          this.$message.error('专利导入失败')
          isExist(rule, value, callback)
        }
      }
    }
    },
    //删除未提交的附件
    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');
    },
    //导入
    imports(){},
    //获取选择的部门ID
    getDepartmentId(val){
      this.form.departmentId = val
    },
    //获取全部人员
    getAllPersonnelList(){
      this.$api.getTenantPersonnel().then(response=>{
        this.personnelList = response.data
      })
    },
    //获取全部客户
    getAllClientList(){
      this.$api.getAllClientList({}).then(response=>{
        this.clientList = response.data
      })
    },
    //获取全部部门
    getAllDepartmentList(){
      this.$api.getTenantDepartments().then(response=>{
        // console.log(response)
        this.departmentList = response.data
      })
    },
    //获取全部场景信息
    getDictsFromPAS(){
      this.$api.getDictsFromPAS().then(response=>{
        // console.log(response)
        this.dictsFromPASList = response.data
      })
    },
    //修改需要复制的选项
    changeCopyIds(val){
      if(Object.keys(this.copyIndex).length>0){
        var index = this.copyList.findIndex(item=>{
          return item.dictChildLabel == '对比文件'
        })
        if(index!=-1){
          var id = this.copyList[index].dictChildValue
          var index2 = this.copyList.findIndex(item=>{
              return item.dictChildLabel == '标引信息'
            })
          if(val.indexOf(id)!=-1){
            if(index2==-1){
              this.copyList.splice(index+1,0,this.copyIndex)
            }
          }else{
            if(index2!=-1){
              this.copyList.splice(index2,1)
              this.form.copyIds.splice(this.form.copyIds.indexOf(this.copyIndex.dictChildValue),1)
            }
          }
        }else{

        }
      }
    },
    //接收创建报告类型
    open(row, dictMessage) {
      this.tenantType = this.userinfo.tenantType
      this.verify=true
      var a = ''
      this.form = JSON.parse(JSON.stringify(row))
      if(this.form.clientId&&this.form.personId){
        this.form.clientId = Number(row.clientId)
      this.form.personId = Number(row.personId)
      // a = '编辑'
      }else{
        this.form.departmentId = ''
        // a = '创建'
      }
      if (this.form.id) {
        if (this.$reportPermission(this.form.id,[0,1])) {
          a = '编辑'
        } else {
          a = '查看'
        }
      } else {
        a = '创建'
      }
      if(this.form.clientId == 0){
        this.form.clientId = null
      }
      if(dictMessage){
        this.dictMessage.REPORT_TYPE = dictMessage
      }
      // if(row.track && this.form.status == 3){
        this.changeStatus(this.form.status)
      // }
      var reportType = this.dictMessage.REPORT_TYPE.filter(item=>{return item.dictChildValue == this.form.type})[0].dictChildLabel
      this.title = a + reportType + '报告'
      if(row.track){
        this.title = '添加追踪报告'
        this.copyList = this.dictMessage[this.reportAsDicItemCopy[this.form.type]]
        if(this.copyList){
          var index = this.copyList.findIndex(item=>{
            return item.dictChildLabel == '标引信息'
          })
          if(index!=-1){
            this.copyIndex = this.copyList[index]
          }
        }
        
        var arr = this.copyList?this.copyList.map(item=>{return item.dictChildValue}):[]
        this.$set(this.form,'copyIds',arr)
      }
      if(this.form.signPatentNo && !row.track){
        this.$set(this.form,'name',this.form.signPatentNo + reportType)
      }
      this.showDialog = true
      if(this.$refs.reportForm)
      this.$refs.reportForm.resetFields();
    },
    //获取专利号且填入报告名称
    getPatentNo(){
      if(!this.form.name){
        var a = this.dictMessage.REPORT_TYPE.filter(item=>{return item.dictChildValue == this.form.type})[0].dictChildLabel
        this.$set(this.form,'name',this.form.signPatentNo + a)
      }
    },
    //获取后续事项
    getMatter(val){
      this.matterSign = false
      try{
        var keyList={
          followUpName:'',
          remark:'',
          agent:'',
          assistPerson:'',
          timeLimit:''
        }
        var list = []
        val.forEach(item=>{
          var a = false
          for(let key in keyList){
            if(item[key] !='' && item[key] != null){
              a = true
            }
          }
          if(a == true){
            if(item.followUpName!='') {
              list.push(item)              
            }else{
              throw new Error()
            }
          }
        })
        this.form.followUps = list
        this.$refs.popover.showPopper = false
        
      }catch(e){
        this.$message.error('后续事项名称不能为空')
        this.$refs.popover.showPopper = true
      }  
      
    },
    // 点击确定跳转并打开新窗口页面
    ifDialog() {
      if(this.form.status == 3){
        this.matterSign = true
      }
      this.verify=false
      this.load_text = '数据校验中'
      this.loading = true
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          this.loading = false
          if(!this.form.id){
            if (this.form.status == 3) {
                        let formData = new FormData()
                        if(this.file){
                          for (var i = 0; i < this.file.length; i++) {
                            formData.append("files", this.file[i]);
                          }
                        }
                        formData.append('report',JSON.stringify(this.form))
                        this.$api.AddReport(formData).then(response=>{
                          if(response.code == 200){
                            this.file = []
                            // this.$refs.upload.clearFiles()
                            this.$message.success('报告创建成功')
                            this.$emit('getList', true)
                            this.handleClose()
                          }
                        })
                 return false
            }
            this.$confirm('是否需要审核?', '提示', {
                      confirmButtonText: '是',
                      cancelButtonText: '否',
                      closeOnClickModal:false,
                      distinguishCancelAndClose: true,
                    }).then(() => {
                      // this.showPerson = true
                      this.showTask = true
                      this.$set(this.task,'taskName',this.form.name+'审核')
                      // this.$message({
                      //   type: 'success',
                      //   message: '删除成功!'
                      // });
                    }).catch(action => {
                      if(action == 'cancel'){
                       this.submitReport()
                      }else{

                      }
                            
                    });
          }else{
            let formData = new FormData()
            if(this.file){
              for (var i = 0; i < this.file.length; i++) {
                formData.append("files", this.file[i]);
              }
            }
            formData.append('report',JSON.stringify(this.form))
            // for(let key in this.form){
            //   if(key=='reportFiles'){
            //     formData.append(key,JSON.stringify(this.form[key]))
            //   }else{
            //      formData.append(key, this.form[key])
            //   }
             
            // }
            this.$api.UpdateReport(formData).then(response=>{
              if(response.code == 200){
                this.file = []
                // this.$refs.upload.clearFiles()
                this.$message.success('报告更新成功')
                this.$emit('getList',true)
                this.handleClose()
              }
            })
          }
        } else {
          this.loading = false
          this.$alert('校验未通过，请按照要求创建报告', '提示', {
          confirmButtonText: '确定',
          type:'warning',
          callback: action => {
          }
        });
          return false;
        }
      });
    },
    //请求创建报告接口
    submitReport(){
      let formData = new FormData()
      if(this.file){
        for (var i = 0; i < this.file.length; i++) {
          formData.append("files", this.file[i]);
        }
      }
      this.form.status = 1
      formData.append('report',JSON.stringify(this.form))
      this.$api.AddReport(formData).then(response=>{
        if(response.code == 200){
          this.file = []
          if(this.form.type!=7){
            this.$message.success('报告创建成功')
          }
          this.$emit('getList', true)
          this.handleClose(response.data)
          
        }
      })
    },
    // 无效应对报告下一步
    ifNext() {
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          this.submitReport()
        }else {
          this.loading = false
          this.$alert('校验未通过，请按照要求创建报告', '提示', {
            confirmButtonText: '确定',
            type:'warning',
            callback: action => {
            }
          });
          return false;
        }
      })
      
      // this.ifDialog()
    },
    // 弹出框关闭
    handleClose(val) {
      if (!this.form.id) {
        this.getPermissions()
      }
      if(this.form.type == 7 && val){
        this.showEvidenceAndRequest = true
        this.$s.setSession('params', {})
        this.reportId=val
      }
      this.copyIndex = {}
      this.matterType = null
      if (this.$refs.uploads) {
        this.$refs.uploads.clearFiles()
      }
      if(this.$refs.upload){
        this.$refs.upload.clearFiles()
      }
      this.file = []
      if(this.$refs.reportForm){
        this.$refs.reportForm.resetFields();
      }
      
      this.showDialog = false
      this.show = 0
      this.form = {}
    },
    //获取报告由权限的人员
    async getPermissions(){
      const response = await this.$api.getPermission()
      this.$store.commit('SET_PERMISSIONS', response.data)
    },
  },

};
</script>

<style lang="scss" scoped>
.upload-file{
  width: 300px !important;
  // height: 150px;
}
.el-select{
  width: 100% !important;
}
.tips{
  color: #F56C6C;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
  margin:0
}
.tips span:hover{
		cursor :pointer;
		text-decoration:underline;
	}
	.tips span{
		margin: 0 2px;
		color: #42A5F5;
	}
</style>