<template>
<section>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single"
  >
    <el-form
      label-width="90px"
      :model="formList"
      :rules="rules"
      ref="ruleForm"
    > 

      <el-row>
        <el-col :span="24">
          <el-form-item :label=label prop="employeeIds">
            <!-- <el-select v-model="formList.employeeIds" filterable :filter-method="filterMethod" collapse-tags multiple @change="selectUser" @remove-tag="removetag" placeholder="请选择">
              <el-option
                v-for="item in tableDataEmployee"
                :key="item.id"
                :label="item.name+' ('+item.telephone+')'+' ('+item.departName+')'"
                :value="item.id">
              </el-option>
            </el-select>             -->
            <div style="display:flex">
              <el-button @click="SelectpopUp">请选择</el-button>  
              <div class="Selected" v-if="employeeList.length>0">已选择{{employeeList.length}}{{$SuperviseStr.employee}}</div>
            </div>
            <div v-if="isshow" style="color:#F56C6C;font-size:12px">请选择{{$SuperviseStr.employee}}</div>
          </el-form-item>
        </el-col>
      </el-row>

   

      <el-row>
        <el-col :span="24">
          <el-form-item :label="`${$SuperviseStr.operation}日期`" prop="expectedDate">
            <el-date-picker
             v-model="formList.expectedDate"
             type="date"
             format="yyyy-MM-dd"
             value-format="yyyy-MM-dd"
             style="width:100%"
             clearable
             :disabled="disabledexpectedDate"
             placeholder="选择日期">
           </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

     

      <el-row>
        <el-col :span="24">
          <el-form-item :label="`${$SuperviseStr.operation}原因：`" prop="note">
            <el-input
              type="textarea"
              auto-complete="off"
              v-model="formList.note"
              :placeholder="`请输入${$SuperviseStr.operation}原因`"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>   

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm()" :loading="loading">确 定</el-button>
      <el-button @click="cancelForm()">取 消</el-button>
    </div>
  </el-dialog>

  

  <MoveSuperDialog :showdialogMoveSuper.sync="showdialogMoveSuper" :getTreeDepartlist="getTreeDepartlist" @refurlist="refurlist" ref="popChildrenMoveSuper"></MoveSuperDialog>
  <PersonnelDialog
      :showdialogpersonnel.sync="showdialogpersonnel"
      :tableData="tableData"
      ref="popChildren"
      @SelectedList="getList"
    ></PersonnelDialog>
</section>  
</template>
<script>
import selectTree from "@/components/SelectTree";
import PersonnelDialog from "@/components/personnelDialog/index.vue";
import MoveSuperDialog from './MoveSuperDialog.vue'
import { employeeTableListApi,AddUserEmplyeeLeaveApi,StaffDepartmentListApi } from "@/api/staffApi.js"

export function validatePhone(rule,value,callback){//校验手机号
  setTimeout(() => {
     if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }, 500);
}
export default {
  inject:['permissions'],
  computed:{
    permissionsStr(){
        return this.permissions()
    }
  },
  props: ["showdialog", "getTreeDepartlist"],
  watch: {
    showdialog() {
      this.dialogFormVisible = this.showdialog;
      this.defaulDataParent=[]
    },
    // employeeList(newv,val){
    //   console.log("Selected",newv)
    //   console.log("Selected",val)
    // }
  },
  components: {
    selectTree, //注册组件
    MoveSuperDialog,
    PersonnelDialog
  },
  data() {
    return {     
      title: $SuperviseStr.operation==='移除' ? '用户移除' : '办理离职',
      dialogFormVisible: this.showdialog,
      OperType: 0, //0 新增  1修改
      formList: {},
      label:'选择' + $SuperviseStr.employee,
      params:{//搜索条件
        pageIndex:1,
        pageSize:10,
        keyword:'',             
        total:0
      },
      rules: {
        employeeIds: [{required: true, message: `请选择${$SuperviseStr.employee}`, trigger: "blur" }],
        expectedDate:[{required: true, message: `请选择${$SuperviseStr.operation}日期`, trigger: "blur"}],
        note:[{required: true, message: `请输入${$SuperviseStr.operation}原因`, trigger: "blur"}],       
      },
      defaulDataParent:'',//上级部门默认回选数据
      defaulData:[],
      tableData:[],
      tableDataEmployee:[],
      resultArr:[],//选择用户下拉得到对应名称数组
      employeeList:[],
      tagChange:'',
      showdialogMoveSuper:false,
      disabledexpectedDate:false,
      showdialogpersonnel:false,
      isshow:false,
      loading: false,
    };
  },
  methods: {  
    getList(SelectedList){
      console.log("SelectedList",SelectedList)
      if(SelectedList.length>0){
        this.isshow = false
      }
      this.employeeList = SelectedList
    },
    SelectpopUp(){
      // this.$refs.popChildren.test()
      this.tableDatalist()
      let employeeList = this.employeeList.length>0 ? JSON.parse(JSON.stringify(this.employeeList)) : []
      this.$refs.popChildren.SelectpopUp(employeeList)
    } , 
    // 通知子组件删除标签
    handle(tag){
      console.log(tag)
      this.employeeList.splice(this.employeeList.indexOf(tag), 1);
      this.$refs.popChildren.tagChanges(tag.id)
    },
    tableDatalist(){//表格列表
        StaffDepartmentListApi().then(response=>{
            if(response.data){
              console.log(response)
              this.tableData=response.data
              // this.sortTableData(this.tableData)
            }
        })
    },
    getTableRow(data, type) {       
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.$set(this.formList,"note",`个人原因${$SuperviseStr.operation}`)
      this.OperType = type;  

      let now=new Date()
      let y=now.getFullYear()
      let m=now.getMonth()+1<10?'0'+(now.getMonth()+1):now.getMonth()+1
      let d=now.getDate()<10?'0'+now.getDate():now.getDate()
      let nowDate=y+'-'+m+'-'+d
      console.log(nowDate)
      this.$nextTick(()=>{
        this.$set(this.formList,'expectedDate',nowDate) //离职日期默认选择当天
        console.log(this.permissionsStr)
        if(this.permissionsStr&&this.permissionsStr.indexOf('leaveDatedLimited')>-1){//北京地区限制编辑离职日期
          this.disabledexpectedDate=true              
        }else{
          this.disabledexpectedDate=false
        }
      })

      this.employeeTableList()//员工列表
      // this.getTreeData(this.getTreeDepartlist)
      
    },    
    checkChangeParent(key, data) {//selectTree组件-复选框选中的数据
        console.log(key)
        console.log(data)
        this.$set(this.formList,"departId",key)
        console.log(this.formList.departId)
    },
    checkChange(key, data) {//selectTree组件-复选框选中的数据
        // console.log(key)
        // console.log(data)
        // this.$set(this.formList,"allowedDepartIds",key)
    },
    getTreeData(arr){//递归遍历部门
        arr.forEach(item=>{
             item.label=item.name;
             item.value=item.id;
             if(item.children&&item.children.length<1){
                 item.children=undefined
             }else if(item.children&&item.children.length>0){
               this.getTreeData(item.children)  
             }
         })
    },   
    employeeTableList(){//列表表格-查询结果
        let obj2={domainId:this.$route.query.domainId}
        employeeTableListApi(this.params,obj2).then(response=>{
            if(response.data.data){
                this.tableDataEmployee=response.data.data
                this.params.total=response.data.total
            }
        })
    }, 
    filterMethod(val){//输入框过滤搜索
        console.log(val)//输入框关键词名称
        this.params.keyword=val
        let obj2={domainId:this.$route.query.domainId}
        employeeTableListApi(this.params,obj2).then(response=>{
            if(response.data.data){
                this.tableDataEmployee=response.data.data
                this.params.total=response.data.total
            }
        })
    },  
    selectUser(val){//查询下拉框id对应的名称数组
        console.log(val)
        console.log(this.tableDataEmployee)
        let resultArr=[]
        resultArr=this.tableDataEmployee.filter(item=>{
           return val.indexOf(item.id)>-1
        })
        resultArr.forEach(its=>{
          this.resultArr.push(its)
        })
        let resultArr2=this.resultArr.filter(item=>{
           return val.indexOf(item.id)>-1
        })
        this.resultArr=resultArr2
        this.resultArr=[...new Set(this.resultArr)]
         console.log(this.resultArr)
    },
    removetag(val){
      console.log(val)
      this.resultArr.forEach(item=>{
        if(item.id==val){
          this.resultArr.splice(item,1)
        }
      })
       console.log(this.resultArr)
    },
    submitForm() {   
      console.log(this.resultArr)
      console.log(this.formList)
      this.$set(this.formList,"employeeIds",[])
      console.log(this.employeeList)
      this.employeeList.forEach(item => {
        this.formList.employeeIds.push(item.id)
      })
      console.log(this.formList)
      if(this.employeeList.length == 0){
        this.isshow = true
        return
      }
      // return
      let obj2={domainId:this.$route.query.domainId}     
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {       
          this.$confirm(`即将对选择的${$SuperviseStr.employee}进行离职,提交后无法恢复，是否继续?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            })
            .then(() => {
                this.loading = true; // 开始加载          
                AddUserEmplyeeLeaveApi(this.formList,obj2).then((response) => {
                  //新增
                  if (response.status==200) {                  
                      let newobj = JSON.parse(JSON.stringify(this.formList));
                      this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                      this.cancelForm();
                      this.employeeList = []
                  }
                  else if(response.code=="1000001"){//该职员([pgMCIATB])作为其他职员的上级，请转移上级上级身份后再试
                      let arr=response.data 
                      console.log(this.employeeList)
                      let Newarr=this.employeeList.filter(item=>{
                        return arr.indexOf(item.id)>-1
                      })
                      console.log(Newarr)                      
                      this.showdialogMoveSuper = true;
                      this.$refs.popChildrenMoveSuper.getTableRow(Newarr,0); 
                  }else{
                    // this.$message({type:"warning",message:response.message})
                  }
                }); 
            }).catch(error => {
                console.log(error)
                console.log(error.response)
            }).finally(() => {
              this.loading = false; // 结束加载
            });    
        } else {
          return false;
        }
      });
    },
    cancelForm() {
      //取消关闭
      this.$emit("update:showdialog", false);
      this.employeeList = []
      this.isshow = false
      this.$nextTick(()=>{
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
    refurlist(){

    }
  },
};
</script>
<style lang="scss">
// .el-dialog-single{
//   .el-form-item{
//     display: flex;
//     flex-direction: column;
//     .el-form-item__content{margin-left:20px!important;}
//   }
// }
.elradioLineheight{
    margin-top:5px; 
  .el-radio{display: block; line-height: 30px;}
}
.Selected{
  color: red;
  margin-left: 10px;
}
</style>