<template>
  <!-- 分配任务3（可做公共组件） -->
	<div style="padding:20px;height:100%;background:white">
		<div class="header1">
			<div>
				<span>总件数：{{totalNumber}}</span>  
				<span> 剩余件数：{{ leaveNumber}}</span>
			</div>
      <div>
        <label for="">任务类型：</label>
        <el-select v-model="taskType">
          <el-option label="对比任务" value="2"></el-option>
          <el-option label="初筛任务" value="3"></el-option>
        </el-select>
      </div> 
      <!-- 平均分配 -->
      <div>
        <el-button  type="primary" size="small" style="height:40px" @click="handleConfirm">平均分配</el-button>
			  <el-button @click="getPerson">添加人员</el-button>
        <el-button @click="finish" v-if="params">完成</el-button >
      </div>
		</div>
		<div style="margin-top:20px">
			<el-table
				:data="checkList"
				v-loading="loading"
				style="width: 100%"
				border
			>
				<el-table-column prop="name" label="人员名称" align="center" show-overflow-tooltip></el-table-column>
				<!-- <el-table-column prop="personnelEmail" label="Email" align="center" show-overflow-tooltip></el-table-column> -->
				<el-table-column prop="tenantName" label="所属租户" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="email" label="邮箱" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="assignCount" label="件数" align="center" show-overflow-tooltip>
					<template slot-scope="scope">
						<span v-if="scope.row.vVisible">{{scope.row.assignCount}}</span>
						<span v-if="!scope.row.vVisible">
							<el-input v-model="scope.row.assignCount" size="small" placeholder="请输入件数"></el-input>
						</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" width="300px">
					<template slot-scope="scope">
						<div class="special">
                <el-button v-if="scope.row.vVisible" class="items" @click.native="edit(scope.row)" :disabled="scope.row.isChoose">编辑</el-button>
                <el-button v-if="!scope.row.vVisible" class="items" @click.native="save(scope.row)">保存</el-button>
                <!-- <span>&nbsp;|&nbsp;</span> -->
                <el-button @click="chosePatentFile(scope.row)" v-if="scope.row.isChoose!=true">选择</el-button>
                <el-button @click="cancelChoose(scope.row)" v-else>取消选择</el-button>

                <el-button @click="removePerson(scope.row)"  type="danger">移除</el-button>
            </div>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog title="人员列表" :visible.sync="personInformation" width="1000px">
			<Personnel-List @checked="getCheck" :checkS="checkListA" ></Personnel-List>
		</el-dialog>

    <el-dialog title="选择专利" :visible.sync="patentInformation" width="1000px">
      
      <Patent-Table ref="getPatent" :tableData="tableData"  @PersonPatent="getPersonPatent" @onForm="onFormTable" :isSubmit="isSubmit" :queryParams="queryParams"></Patent-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>
      <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submitPatent">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog title="任务名称" :visible.sync="taskInformation" width="1000px" :before-close="close2">
      <el-form ref="form" :model="form" :rules="taskRules">
          <el-form-item label="任务名称">
            <el-input v-model="form.name" placeholder="请输入任务名称"></el-input>
          </el-form-item>
          <el-form-item label="截止日期 :" prop="date">
                <el-date-picker style="width:100%"
                    v-model="form.date"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="备注 :" >
                <el-input v-model="form.remark" type="textarea" placeholder="输入备注" />
              </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close2">取 消</el-button>
          <el-button type="primary" @click="submitTask">确 定</el-button>
        </div>
    </el-dialog>
    <el-dialog title="温馨提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
			<div class="spanDiv">
				<div>
					<span class="spanCountdown">{{ countdown }}</span>
					<span class="spanCenter">秒后跳转到<span class="spanJump" @click="dialogVisibleSure">报告管理</span>页面</span>
				</div>
			</div> 
		</el-dialog>
	</div>
</template>

<script>
import PersonnelList from '../../components/personnelList.vue';//导入相对特征页面
import PatentTable from '../../components/patentTable.vue'
export default {
  components: {
    PersonnelList,
    PatentTable
  },
  props:['reportId','isFinish','patentNo',"personId",'reportName'],
  data() {
    const isTime = (rule, value, callback) => {
      let a = Date.parse(new Date)
      let b = Date.parse(value)
      if (value) {
        if (b<a) {
          callback(new Error('禁止选择现在及以前时间，请重新选择'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择时间'))
      }
    }
    return {
      isFirst:true,
      dialogVisible:false,
      countdown:3,
      taskType:"2",
      taskInformation:false,
      form:{
        
      },
      patentInformation:false,
      personInformation: false,
      // totalNumber: this.tableDataA.length!=0?tableDataA.length:"",//总件数
      // leaveNumber: this.tableDataA.length!=0?tableDataA.length:null,//剩余件数
      totalNumber: '',//总件数
      leaveNumber: null,//剩余件数
      loading: false,
      checkList: [],
      patentCheck:[],
      pj: false,
      num: 0,
      isEqually:true,//是否点击平均分配
      personIdS:this.personId?this.personId:this.$route.query.personId,
      tableData:[],
      data:[],
      isSubmit:false,
      total:0,
      queryParams:{
        size:10,
        current:1,
        reportId: this.reportId?this.reportId:this.$route.query.reportId,
        patentName: "",
        // patentNo: "",
        patentNo: '',
        abstractStr:"",
        applicationNo:"",
      },
      taskRules:{
        date: [
            // {  required: true, message: '请选择日期', trigger: 'change' }
            {  required: true, validator:isTime, trigger: 'change' }
          ],
      },
      checkListA: [],
      reportNameA: {},
      params:{},
      FilterList:''
    }
  },
  computed:{
    userInfo(){
      return this.$store.state.admin.userinfo
    },
  },
  watch:{
    dialogVisible(val){
      if(val){
        this.out()
      }
    },
   
    // 'checkList'(val){
    //   console.log(this.userInfo)
    //   if (val.length == 0) {
    //     console.log("进");
    //     this.fu()
    //   }
    // },
    isFinish(val) {
      console.log(val);
      if(val){
        this.showTask()
      }
    },
  },
  created() {
    // this.personIdS=this.$route.params.personId
    // this.queryParams.reportId=this.$route.params.reportId
    // this.queryParams.patentNo=this.$route.params.patentNo
    this.reportNameA=this.$route.query.reportName
    this.params =this.$route.query.params?JSON.parse(this.$route.query.params):null
    // console.log(this.tableDataA);
  },
  mounted() {
    console.log(this.reportName,this.params)
    if (this.params) {
      console.log(2)
      this.getList2()
    } else {
      console.log(1)
      this.getList()
    }
   
  },
  methods: {
    // 接收子组件值，筛选
    onFormTable(val) {
      this.FilterList = val
      // let value=JSON.parse(val)
      if (Object.keys(val).length != 0) {
        if (this.params) {
          for (let key in val) {
            this.params[key]=val[key]
          } 
          this.getList2()
        } else {

          for (let key in val) {
          this.queryParams[key]=val[key]
        } 
          this.getList()
        }
      } else {
       
        // this.getList()
        if (this.params) {
          for (let key in val) {
            this.params[key]=val[key]
          } 
          this.getList2()
        } else {
          for (let key in val) {
            this.queryParams[key]=val[key]
          } 
          // this.queryParams.patentName = "";
          // this.queryParams.patentNo = "";
          // this.queryParams.abstractStr = "";
          // this.queryParams.applicationNo = "";
          // this.queryParams.applicationName = "";
          // this.queryParams.obligeeName = "";
          this.getList()
        }
      }
    },
     //完成
    finish() {
      this.showTask()
    },
    // 负责人
    fu() {
      let par = {
        size: 10,
        current: 1,
        ID: this.personIdS,
      }
      this.$api.getPartPersonnelID(par).then(res => {
        if (res.code==200) {
          console.log(res);
          // res.data.name = res.data[0].personnelName
          // res.data[0].tenantName = res.data.personnelName
           res.data[0].patentNos=[]
           res.data[0].isChoose = false
           res.data[0].isEdit = false 
           res.data[0].assignCount = this.totalNumber
           this.leaveNumber=0
           res.data[0].vVisible = true
          res.data[0].personId = res.data[0].id
           
          this.checkList.push(res.data[0])
        }
      })
    },
    //保存任务
    submitTask(){
      this.$refs.form.validate((valid) => {
          if (valid) {
            var a = {
                taskType:this.taskType,
                taskName:this.form.name,
                reportId:this.queryParams.reportId,
                endTime:this.form.date,
                remark:this.form.remark,
                assigns:this.checkList,
              }
              if(this.params){
                a.patentVO = this.params
              }
       
            this.$api.addAssTask(a).then(response=>{
              if(response.code == 200){
                this.taskInformation = false
                this.dialogVisible = true
                // this.$emit('addTask',true)
              }
            })
          }
        })
        
    },
    out(){
      this.timer = setInterval(() => {
        if (this.countdown == 0) {
          this.$router.replace("/admin/rManage");
          clearInterval(this.timer);
          this.dialogVisible = false
        } else {
          this.countdown--;
        }
      }, 1000);
    },
    dialogVisibleSure() {
      this.$router.replace("/admin/rManage");
    },
    handleClose() {
      clearInterval(this.timer);
      this.dialogVisible = false;
    },
    showTask(){
      if(this.checkList.length>0){
        console.log(this.reportName)
        this.taskInformation = true
        this.form = {
          name:this.reportName?this.reportName + (this.taskType=="2"?'对比':'初筛')+'任务':this.reportNameA + (this.taskType=="2"?'对比':'初筛')+'任务'
        }
      }else{
        this.$alert('您未添加分配人员', '提示', {
          confirmButtonText: '确定',
          type:'warning',
          callback: action => {
            this.$emit('addTask',false)
          }
        });
      }
    },

    getCheck(val) {//人员信息
      console.log("getCheck",val)
      this.checkList = val
      this.personInformation=false
    },
    edit(row) {//编辑
        this.num = row.assignCount
        row.vVisible = !row.vVisible
        this.checkList = JSON.parse(JSON.stringify(this.checkList))
    },
    save(row){//保存
      row.vVisible = !row.vVisible
      var a= row.assignCount
      row.isEdit = false
      for(var i=0;i<this.checkList.length;i++){
        if(this.checkList[i].isChoose==true||this.checkList[i].isEdit==true){
          a = Number(a) + Number(this.checkList[i].assignCount)
        }
      }
      if(a>this.totalNumber){
        row.assignCount = this.num
      }else{
        if(row.assignCount!=0){
          row.isEdit = true
        }
        
        this.leaveNumber =  Number(this.totalNumber) - Number(a)
      }
       

        if(this.isEqually){
            this.beforeHandleConfirm()
          }  
        
        
    },
    getPerson() {
      this.personInformation = true
      this.checkListA = JSON.parse(JSON.stringify(this.checkList))
      console.log(this.checkListA);
    },
    //移除人员
    removePerson(row){
      var index = this.checkList.findIndex(item=>{
        return item.id == row.id
      })
      if(index !=-1){
        this.checkList.splice(index,1)
        this.leaveNumber = Number(this.leaveNumber) + row.assignCount
      }
    },
    submit() {
      this.personInformation = false
    },
    beforeHandleConfirm(){
      if(this.checkList.length>0){
        var data = JSON.parse(JSON.stringify(this.checkList))
        for(var i = 0;i<data.length;i++){
            if(data[i].isChoose==false&&data[i].isEdit==false){
              // this.leaveNumber = Number(this.leaveNumber) + Number(data[i].assignCount)
              data[i].assignCount=0
            }
        }
        this.checkList = data
        this.handleConfirm()
      }
    },
    // 平均分配
    handleConfirm() {
      this.isEqually = true
      if (this.checkList.length > 0) {
        // var num = parseInt(Number(this.totalNumber) / Number(this.checkList.length))
          var a = 0
        for(var i=0;i<this.checkList.length;i++){
          if(this.checkList[i].isChoose==true||this.checkList[i].isEdit==true){
            a = Number(a) + Number(this.checkList[i].assignCount)
          } else {
            this.checkList[i].assignCount=0
          }
        }
        this.leaveNumber = Number(this.totalNumber) - Number(a)
        console.log(this.leaveNumber);
        var data = JSON.parse(JSON.stringify(this.checkList))

        if(this.leaveNumber>0){
          this.getRowNumber(data)
        }
       
        // data.forEach(item => {
        //   item.assignCount = num
        // });
        // this.leaveNumber = Number(this.totalNumber) % Number(this.checkList.length)
        // // this.getList()
        this.checkList = data
      }
      
    },
    getRowNumber(data){
      for(var i = 0;i<data.length;i++){
        if(this.leaveNumber>0){
          if(data[i].isChoose==false&&data[i].isEdit==false){
            data[i].assignCount+=1
            this.leaveNumber-=1
          }
        }else{
          i=data.length
        }
        }
        if(this.leaveNumber>0){
          this.getRowNumber(data)
        }
        
    },
    chosePatentFile(row) {
      console.log(this.FilterList)
      this.isSubmit = true
      this.patentInformation=true
      // this.$refs.getPatent.opens(this.tableData)
      this.personIdS = row.id
      this.queryParams.current = 1
      if (this.params) {
        this.params.current = 1
        for (let key in this.FilterList) {
            this.params[key]=''
          } 
        this.getList2()
      } else {
        for (let key in this.FilterList) {
            this.queryParams[key]=''
          } 
        this.getList()
      }
    },
    cancelChoose(row){
      row.isChoose = false
      row.isEdit = false
      row.assignCount = 0
      // this.leaveNumber = this.leaveNumber+row.patentNos.length
      row.patentNos = []
      var a = 0
      for(var i=0;i<this.checkList.length;i++){
        if(this.checkList[i].isChoose==true||this.checkList[i].isEdit==true){
          a = Number(a) + Number(this.checkList[i].assignCount)
        }
      }
      this.leaveNumber =  Number(this.totalNumber) - Number(a)
      if(this.isEqually){
        this.beforeHandleConfirm()
      }
    },
    close(){
      this.isSubmit = false
      this.patentInformation = false
    },
    close2(){
      this.taskInformation = false
      this.$emit('addTask',false)
    },
    getPersonPatent(val){
      this.patentCheck = val
    },
    submitPatent(){
      if(this.patentCheck.length>0){
        var index = this.checkList.findIndex(item=>{
          return item.id == this.personIdS
        })
        if(index!=-1){
          var data = JSON.parse(JSON.stringify(this.checkList))
          data[index].patentNos = this.patentCheck
          data[index].isChoose  = true
          data[index].assignCount = this.patentCheck.length
          this.checkList = data
          var a = 0
          for(var i=0;i<this.checkList.length;i++){
            if(this.checkList[i].isChoose==true||this.checkList[i].isEdit==true){
              a = Number(a) + Number(this.checkList[i].assignCount)
            }
          }
          if(a>this.totalNumber){
            data[index].patentNos = []
            data[index].isChoose  = false
            data[index].assignCount = 0
          }else{
            this.leaveNumber =  Number(this.totalNumber) - Number(a)
          }
          // this.leaveNumber = this.leaveNumber - this.patentCheck.length
          
          if(this.isEqually){
            this.beforeHandleConfirm()
          }
        }
      }
      
      console.log(this.patentCheck)
      this.close()
    },
    handleCurrentChange(val) {//分页
      
      if (this.params) {
        this.params.current = val;
        this.getList2()
      } else {
        this.queryParams.current = val;
        this.getList()
      }
    },
    //获取专利
   async getList() {
    await this.$api.getSureCompareFile(this.queryParams).then(response=>{
        if(response.code==200){
          this.tableData = response.data.records
          this.total = response.data.total
          if(this.isFirst==true){
            this.totalNumber = this.total
            this.leaveNumber = this.leaveNumber===null?this.total:this.leaveNumber
          }
          this.isFirst = false
          
          // var a = []
          // var b=this.tableData
          for(var i=0;i<this.checkList.length;i++){
            if(this.checkList[i].patentNos.length>0){
              for(var j=0;j<this.checkList[i].patentNos.length;j++){
                // console.log(b)
                var index = this.tableData.findIndex(item=>{
                  return item.patentNo == this.checkList[i].patentNos[j]
                })
                if(index!=-1){
                   this.tableData[index].disabled =  true
                }
              }
             
            }
          }
          if (this.checkList.length==0) {
            this.fu()
          }
          
        }
      })
    },
    async getList2() {
      // 需要根据报告id查询所有对比文件
      await this.$api.getSureCompareFile(this.params).then(response => {
        // console.log(res);
        if(response.code==200){
          this.tableData = response.data.records
          console.log(this.tableData,response.data.records);
          this.total = response.data.total
          this.totalNumber = this.total
          this.leaveNumber = this.leaveNumber===null?this.total:this.leaveNumber
          // var a = []
          // var b=this.tableData
          for(var i=0;i<this.checkList.length;i++){
            if(this.checkList[i].patentNos.length>0){
              for(var j=0;j<this.checkList[i].patentNos.length;j++){
                // console.log(b)
                var index = this.tableData.findIndex(item=>{
                  return item.patentNo == this.checkList[i].patentNos[j]
                })
                if(index!=-1){
                   this.tableData[index].disabled =  true
                }
              }
             
            }
          }
          if (this.checkList.length==0) {
            this.fu()
          }
          
        }
      })
    },
  },
  getData(){

  }
}
</script>

<style lang="scss" scoped>
 .header1{
    display: flex;
    justify-content: space-between;
    align-items:center;
 }
 .spanDiv{
		display: flex;
		justify-content: center;
		height: 100px ;
	}
	.spanCountdown{
		color: red;
		font-size: 24px;
		margin: 10px;
	}
	.spanCenter{
		margin: 0;
		font-size: 16px;
	}
	.spanJump:hover{
		cursor :pointer;
		color: red;
		text-decoration:underline;
	}
	.spanJump{
		font-size: 16px;
		margin: 10px 0;
		color: #42A5F5;
	}
</style>