<template>
  <div>
    <el-dialog title="请求协同" :visible.sync="visibleCollaboration" :before-close="close" class="sendCollaboration">
      <div>
        <el-form :model="clientForm" :rules="clientRules" ref="clientForm">

          <el-form-item label="协同人 :" prop="handlePersonIds">
            <el-select style="width:100%;" ref="select1" v-model="clientForm.handlePersonIds" clearable
               filterable remote placeholder="请输入协同人" :remote-method="remoteMethod" @change="change" @clear="clear(0)"
              @visible-change="visibleChange" :loading="ploading">
              <el-option v-for="item in personnelList" :key="item.value" :label="item.label" :value="item.value" :disabled="!item.value">
                <span style="float: left" >{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px" v-if="!item.value"><el-button size="small" @click="create(0)" >创建</el-button></span>
              </el-option>

              <!-- <el-option v-for="item in personnelList" :key="item.value" :label="item.label" :value="item.value">
              </el-option> -->
            </el-select>
            <el-tooltip class="item" effect="dark" content="只能选择一人（默认为选择第一个人）" placement="top">
              <p style="position: absolute; right: 10px;top: 28px;width:20px"><i class="el-icon-circle-plus-outline"
                  style="font-size:20px" @click="showPersonnel(0)"></i></p>
            </el-tooltip>
          </el-form-item>

          <el-form-item label="抄送人 :" prop="syneryCCLists">
            <el-select style="width:100%;" v-model="clientForm.syneryCCLists" clearable multiple filterable
              remote placeholder="请输入抄送人" :remote-method="remoteMethod" @change="change1" @remove-tag="removeTag" @clear="clear(1)"
              @visible-change="visibleChange" :loading="ploading">
                <el-option v-for="item in personnelList" :key="item.value" :label="item.label" :value="item.value"
                  :disabled="!item.value">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px" v-if="!item.value"><el-button size="small" @click="create(1)">创建</el-button></span>
                </el-option>

              <!-- <el-option v-for="item in personnelList" :key="item.value" :label="item.label" :value="item.value">
              </el-option> -->
            </el-select>
            <p style="position: absolute; right: 10px;top: 28px;width:20px"><i class="el-icon-circle-plus-outline"
                style="font-size:20px" @click="showPersonnel(1)"></i></p>
          </el-form-item>

          <el-form-item label="主题 :" prop="taskName">
            <el-input v-model="clientForm.taskName" type="text" placeholder="输入主题" />
          </el-form-item>

          <el-form-item label="完成日期 :" prop="endTime">
            <el-date-picker style="width:100%" v-model="clientForm.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="clientForm.remark" type="textarea" placeholder="输入备注" />
          </el-form-item>
        </el-form>
      </div>

      <el-dialog title="人员列表" :visible.sync="userInformation" width="1000px" append-to-body>
        <!-- 组件 -->
        <Personnel-List @checked="getCheck"></Personnel-List>

        <!-- <div slot="footer" class="dialog-footer">
              <el-button @click="userInformation = false">取 消</el-button>
              <el-button type="primary" @click="submit">确定</el-button>
            </div> -->

      </el-dialog>
      <el-dialog title="创建人员" :visible.sync="createdPersonnel" width="500px" append-to-body>
        <el-form :model="CreatedPerson" :rules="CreatedPersonRule" ref="CreatedPerson">
          <el-form-item label="姓名 :" prop="name">
            <el-input v-model="CreatedPerson.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="邮箱 :" prop="email">
            <el-input v-model="CreatedPerson.email" placeholder=" 请输入邮箱" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeCreatedPersonnel">取 消</el-button>
          <el-button type="primary" @click="submitCreatedPersonnel">确定</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="sendMessage" :loading="btnLoading">发送</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import PersonnelList from './personnelList'
export default {
  props: ["visibleCollaborations", "reportId", "onChangesIn", "formS","compareResultA","patentNo1"],
  components: {
    PersonnelList
  },
  data() {
    //校验协同人是否为空
    const isCollaborator = (rule, value, callback) => {
      if (!this.clientForm.handlePersonIds) {
        console.log("进来");
        callback(new Error('请选择协同人'))
      } else {
        callback()
      }
    }
    const isEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!this.CreatedPersonRule.email) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    const isTime = (rule, value, callback) => {
      if (this.isEndTime) {
        this.isEndTimes = Date.parse(new Date)
      }
      let b = Date.parse(value)
      console.log(this.isEndTimes,b);
      if (value) {
        if (b<this.isEndTimes) {
          callback(new Error('禁止选择现在及以前时间，请重新选择'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      witchOne:'',
      createdPersonnel: false,
      CreatedPerson:{},
      visibleCollaboration: false,
      clientInformation: false,
      btnLoading: false,
      queryParams: {
        // signPatentNo:this.signPatentNo,
        // taskId: this.taskId,
        // reportId: this.reportId,
        // applicationName: "",//申请人
        // obligeeName: "",//权利人
        patentNo: this.patentNo1,
        // applicationNo: "",
        // numberIpc: "",
        // numberCpc: "",
        // numberUpc: "",
        // patentName: "",
        // abstractStr: "",
        // filedOptions: [],//数组，用来存放自定义字段勾选项进行筛选
        // taskStatus:"3",
        reportId:this.reportId,
        current: 1,
        size: 10,
        total: 0,
        // handlePersonId: this.clientForm.collaborator,
        syneryCCList:[],
        // taskName: this.clientForm.content,
        // endTime: this.clientForm.date,
        // remark: this.clientForm.remark,
        // clientForm: {},
        patentVO: {},
        compareResult: this.compareResultA,
        isAll:0,
      },
      ploading: false,
      userInformation: false,
      AllpersonnelList: [],
      personnelList: [],
      list: [],
      checked: [],
      sign: '',
      clientForm: {
        // collaborator: [],
        syneryCCLists: [],
      },
      isEndTime:true,
      isEndTimes:null,
      clientRules: {
        handlePersonIds: [{ required: true, validator: isCollaborator, trigger: 'change' },],
        taskName: [{ required: true, message: "请输入主题", trigger: "blur" },],
        endTime: [
            {  required: false, validator:isTime, trigger: 'change' }
          ],
      },
      CreatedPersonRule: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" },],
        email: [{ required: true, validator: isEmail, trigger: "change" },],
      }
    }
  },
  computed: {
    ...mapGetters(['userinfo'])
  },
  mounted() {
    this.getPersonnelList()
    
  },
  watch: {
   
    visibleCollaborations(val) {
      this.visibleCollaboration = val
    },
    compareResultA(val) {
      this.queryParams.compareResult = val
      console.log(this.queryParams.compareResult);
    }
  },
  // 点击子组件personnelList中确定按钮，像父级发送数据，父级通过getCheck接收存入到checked数组中（数据是对象）
  methods: {
    sendMessage() {
      this.isEndTime=false
      // this.queryParams.clientForm=this.clientForm
      this.$refs.clientForm.validate((valid) => {
        if (valid) {
          // if (this.queryParams.reportType != 4) {
          if (this.onChangesIn) {
              this.queryParams.patentVO.filedOptions = this.onChangesIn
              this.queryParams.isAll = 1;
              if (Object.keys(this.formS).length > 0) {
                for (let k in this.formS) {
                  this.queryParams.patentVO[k] = this.formS[k]
                }
              }
          }
          if (this.queryParams.patentNo) {
            this.queryParams.isAll=null
          }
            
          // }
          if (Object.keys(this.clientForm).length > 0) {
              for (let kForm in this.clientForm) {
                this.queryParams[kForm] = this.clientForm[kForm]
              }
          }
          console.log(this.personnelList,this.queryParams);
          this.$api.addSyneryTask(this.queryParams).then(res => {
            if (res.code==200) {
              this.visibleCollaboration = false
              this.$emit("collaboration", this.visibleCollaboration)
              this.clientForm = {}
              this.$message.success("任务创建成功，邮件已成功发送")
            }
          })
          console.log(this.queryParams);
        }
      })
     
    },
    getCheck(val) {
      console.log("getCheck", val)//每行数据对象
      this.checked = val
      this.submit()
    },
    submit() {
      // 遍历checked数组，拼接名字邮箱
      if(this.checked.length>0){
        if (this.sign == 0) {//判断是协同人
          this.queryParams.personEmail = ''
          this.queryParams.handlePersonId = this.checked[0].id
          this.clientForm.handlePersonIds = this.checked[0].name + "<" + this.checked[0].email + ">"
        } else {
          for (var i = 0; i < this.checked.length; i++) {
            var a = this.checked[i].name + "<" + this.checked[i].email + ">"
            console.log(a);
            if (this.clientForm.syneryCCLists.indexOf(a) == -1) {
              this.clientForm.syneryCCLists.push(a)
              this.queryParams.syneryCCList.push({
                ccId: this.checked[i].id,
                ccEmail: this.checked[i].email,
                ccName: this.checked[i].name
              })
            }
          }

        }
      }
      
      this.userInformation = false
    },
    //点击icon打开人员信息弹出框
    showPersonnel(val) {
      this.sign = val
      this.userInformation = true
    },
    getPersonnelList() {
      this.$api.getAllPersonnel()
        .then((response) => {
          this.AllpersonnelList = response.data;
          this.list = this.AllpersonnelList.map(item => {
            return { value: `${item.id}`, label: `${item.personnelName}<${item.personnelEmail}>` };
          });
        })

    },
    remoteMethod(query) {
      if (query !== '') {
        this.ploading = true;
        setTimeout(() => {
          this.ploading = false;
          this.personnelList = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
          if (this.personnelList.length == 0) {
            this.personnelList.push({
              label: query,
              value:''
            })
          }
        }, 200);
      } else {
        this.personnelList = [];
      }
    },
    visibleChange() {
      this.personnelList = []
    },
    create(key) {
      this.witchOne = key
      this.CreatedPerson = {
        name:this.personnelList[0].label
      }
      this.createdPersonnel = true
      
    },
    change(item) {
      console.log(item);
      this.queryParams.personEmail = ''
      this.queryParams.handlePersonId=item
      this.personnelList = []
    },
    change1(item) {
      console.log(item);
      var a = item.length - 1
      var arr = this.AllpersonnelList.filter(item1 => {
        return item1.id == item[a]
      })
      console.log(arr);
      if (arr.length>0) {
        if (this.queryParams.syneryCCList.findIndex(it=>{ return it.ccId==arr[0].id })==-1) {
          this.queryParams.syneryCCList.push({
            ccId:arr[0].id,
            ccEmail: arr[0].personnelName,
            ccName: arr[0].personnelEmail
          })  
        }
       
      }
      this.personnelList = []
    },
    removeTag(item) {
      this.queryParams.syneryCCList.forEach((items, index) => {
        if (items.ccId==item) {
          this.queryParams.syneryCCList.splice(index,1)
        } else {
          if (items.sign==item) {
            this.queryParams.syneryCCList.splice(index,1)
          }
        }
      })
      console.log(item, this.queryParams.syneryCCList);
    },
    clear(val) {
      if (val==0) {
        this.queryParams.personEmail = ''
        this.queryParams.handlePersonId=''
      } else {
        this.queryParams.syneryCCList=[]
      }
    },
    submitCreatedPersonnel() {
      this.$refs.CreatedPerson.validate((valid) => {
        if (valid) {
          switch (this.witchOne) {
            case 0:
              this.queryParams.handlePersonId = null
              this.queryParams.personEmail = this.CreatedPerson.name+"<" + this.CreatedPerson.email + ">"
              this.clientForm.handlePersonIds = this.CreatedPerson.name + "<" + this.CreatedPerson.email + ">"
              this.closeCreatedPersonnel()
              break;
            case 1:
              var a = this.CreatedPerson.name + "<" + this.CreatedPerson.email + ">"
              if (this.clientForm.syneryCCLists.includes(a) == false) {
                this.clientForm.syneryCCLists.push(a)
                this.queryParams.syneryCCList.push({
                  ccEmail: this.CreatedPerson.email,
                  ccName: this.CreatedPerson.name,
                  sign:a,
                })
              }
              this.closeCreatedPersonnel()
              break;
            }
        }
   
      })
     },
    closeCreatedPersonnel() {
      this.CreatedPerson = {}
      this.createdPersonnel = false
    },
    close() {
      this.isEndTime=true
      // this.$emit('getClientInformation', this.clientInformation)
      this.visibleCollaboration = false
      this.clientForm = {}
      this.$emit("collaboration", this.visibleCollaboration)
    }
  },
}
</script>
<style >
.sendCollaboration .el-input__suffix {
  right: 50px;
  transition: all .3s;
}

.sendCollaboration .el-input__prefix,
.el-input__suffix {
  position: absolute;
  top: 0;
  /* -webkit-transition: all .3s; */
  height: 100%;
  color: #C0C4CC;
  text-align: center;
}
</style>