<template>
  <div>
    <!-- 创建报告-->
    <el-dialog :title="title" :visible.sync="showDialog" width="600px" :close-on-click-modal="false"  @close="handleClose" >
        <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="upload" class="upload-file" action="#" :auto-upload="false" :show-file-list="false" :on-change="onChange1">
                  <span>导入</span>
                </el-upload></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="承担部门" 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" >
              <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="应用场景" prop="easFlag" >
              <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="卷号" prop="volumeNumber" >
              <el-input v-model="form.volumeNumber" autocomplete="off" placeholder="请输入卷号"></el-input>
            </el-form-item>
            <el-form-item label="上传附件">
              <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" @click="showFile1(item.url)">{{item.name?item.name:item.fileName}}</p> <p style="margin:0;" @click="delFile(item.id)"><i class="el-icon-close"></i></p></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">
              <el-button @click="handleClose">取 消</el-button>
              <el-button type="primary" @click="ifDialog" >确 定</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 title="选择审核人" :visible.sync="showPerson" width="1000px"  @close="handleClose2">
      <Personnel-List @checked="getPerson"></Personnel-List>
    
    </el-dialog> -->
    <el-dialog :visible.sync="showFile">
      <div width="1200px">
        <!-- <img width="100%" :src="imageUrl" alt=""> -->
      <iframe :src="imageUrl" frameborder="0" width="900px" height="500px"></iframe>
      </div>
      
      <!-- <div v-html="imageUrl"></div> -->
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SelectTree from '@/views/components/common/treeSelect.vue'
import { PatentDetails } from "@/views/components/common/mixins";
import PersonnelList from './personnelList.vue'

export default {
  props: ['isTrue'],
  mixins:[PatentDetails],
  components:{
    SelectTree,
    PersonnelList
  },
  data() {
    //校验部门是否为空
    const isDepartmentId = (rule,value,callback)=>{
      if(!this.form.departmentId){
        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('请选择时间'))
      }
    }
    return {
      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:[],
      rules: {//校验,
        name: [{ required: true, message: '请输入报告名称', trigger: 'blur' },],
        signPatentNo: [{ required: true, validator:isExist, trigger: 'blur' },],
        personId: [{ required: true, message: '请选择负责人', trigger: 'change' },],
        clientId: [{ required: true, message: '请选择委托方', 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,
    };
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
    dictMessage() {
      return this.$store.state.dictMessage.dictMessage
    },
  },

  mounted() {
    this.getAllPersonnelList()
    this.getAllClientList()
    this.getAllDepartmentList()
    this.getDictsFromPAS()
  },
  methods: {
    handleCloseTask(){
      // this.$refs.TaskForm.clear()
      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) {
      console.log(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){
      console.log(file)
      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 => {

      })
    },
    initTask() {
      if(this.webSocket){
      this.webSocket.onmessage = (e) => {
        // console.log(e)
        const { code, data, message } = JSON.parse(e.data)
        console.log(JSON.parse(e.data))
        if (code === 903 || code === 904) {
          this.loading = false
          this.$message.success('专利导入成功')
          this.$refs['reportForm'].validateField('signPatentNo');
        //   const index = this.taskData.map(item => item.taskId).indexOf(data.taskId)
        //   console.log(index,this.taskData)
        //   if (index === -1) {
        //     // this.taskData.push(data)
        //   } else {
        //     this.$set(this.taskData, index, data)
        //   }
        //   if (data.complete) {
        //     if(this.form==1){
        //       this.$message.success(`导入任务完成`)
        //        for(var i = 0;i<this.taskData.length;i++){
        //       if(this.taskData[i].complete==true){
        //         this.taskData.splice(i,1)
        //       }
        //     }
        //     }else{
        //       this.$message.success(`导出任务完成`)
        //     }
            
        //     // console.log(this.form)
           
        //     this.getList()
          // }
        } else if (code === 803 || code === 804) {
          this.$message.error('专利导入失败')
          isExist(rule, value, callback)
          // this.getList()
        }
      }
    }
    },
    handleRemove(file, fileList) {
      var index = this.file.findIndex(item=>{
        return item.uid == file.raw.uid
      })
      if(index!=-1){
        this.file.splice(index,1)
      }
      console.log(this.file, fileList);
      },
    handlePreview(file) {
      console.log(file);
      // this.$api.seeFile()
      // this.imageUrl ='https://view.xdocin.com/view?src=' + URL.createObjectURL(file.raw)
      // this.showFile = true
    },
   showFile1(url){
    // this.showFile = true
    // this.imageUrl = this.$p + url
    // var b = this.$p + url
    // var a = window.URL.createObjectURL(b)
    // this.imageUrl ='https://view.xdocin.com/view?src=' +encodeURIComponent( b)
    // window.open(this.imageUrl,'_blank')
    // console.log(a)
    // this.$api.seeFile({url:url}).then(response=>{
    //   console.log(response)
    // })
   },
    //获取审核人
    // getPerson(val){
    //   if(val){
    //      this.person = val
    //     console.log(val)
       
    //   }else{
    //     this.handleClose2()
    //   }
    // },
    // //提交审核
    // submitPerson(){},
    //导入
    imports(){},
    //获取选择的部门ID
    getDepartmentId(val){
      this.form.departmentId = val
    },
    //获取全部人员
    getAllPersonnelList(){
      this.$api.getAllPersonnel().then(response=>{
        // console.log(response)
        this.personnelList = response.data
      })
    },
    //获取全部客户
    getAllClientList(){
      this.$api.getAllClient().then(response=>{
        this.clientList = response.data
      })
    },
    //获取全部部门
    getAllDepartmentList(){
      this.$api.getAllDepartment().then(response=>{
        // console.log(response)
        this.departmentList = response.data
      })
    },
    //获取全部场景信息
    getDictsFromPAS(){
      this.$api.getDictsFromPAS().then(response=>{
        // console.log(response)
        this.dictsFromPASList = response.data
      })
    },
    //接收创建报告类型
    open(row,dictMessage) {
      console.log(row)
      this.verify=true
      var a = ''
      this.form = 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(dictMessage){
        this.dictMessage.REPORT_TYPE = dictMessage
      }
      var reportType = this.dictMessage.REPORT_TYPE.filter(item=>{return item.dictChildValue == this.form.type})[0].dictChildLabel
      this.title = a + reportType + '报告'
      if(this.form.signPatentNo ){
        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)
      }
      
      // this.form.name = this.form.signPatentNo + a
    },
    // 点击确定跳转并打开新窗口页面
    ifDialog() {
      this.verify=false
      this.load_text = '数据校验中'
      this.loading = true
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          this.loading = false
          if(!this.form.id){
            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'){
                        let formData = new FormData()
                        if(this.file){
                          for (var i = 0; i < this.file.length; i++) {
                              formData.append("files", this.file[i]);
                          }
                        }
                        
                        for(let key in this.form){
                          formData.append(key, this.form[key])
                        }
                        formData.append('status', 1)
                        // console.log(formData)
                      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()
                        }
                      })  
                      }else{

                      }
                            
                    });
          }else{
            console.log(this.form)
            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;
        }
      });
    },
    // 弹出框关闭
    handleClose() {
      this.$refs.upload.clearFiles()
      this.file = []
      this.showDialog = false
      // this.$refs.reportForm.resetFields();
      this.show = 0
      this.form = {}
    },
    handleClose2(){
      this.showPerson = false
    },
  },

};
</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>