<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single"
  >
    <el-form
      label-width="200px"
      :model="formList"
      :rules="rules"
      ref="ruleForm"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择用户：" prop="employeeIds" v-if="this.OperType==0">
            <el-select v-model="formList.employeeIds" filterable :filter-method="filterMethod" collapse-tags multiple placeholder="请选择">
              <el-option
                v-for="item in tableDataEmployee"
                :key="item.id"
                :label="item.name+' ('+item.telephone+')'"
                :value="item.id">
              </el-option>
            </el-select>            
          </el-form-item>
          <el-form-item label="用户：" prop="" v-else>
             <span>{{formList.name}}</span>            
          </el-form-item>
        </el-col>
      </el-row>
  
  

      <el-row>
        <el-col :span="24">
            <el-form-item :label="departlabel" prop="departIds">
                <selectTree
                ref="selectTree"
                @getValue="checkChange"
                @loadingTreeDataEventHandler = "loadingDepartTreeDataEventHandler"            
                :curValue="defaulData"
                :data="getTreeDepartlist"    
                :defaulexpand="false" 
                :defaultKey="defaultExpandedKeys"
                :obj="{                  
                    id: 'id',
                    label: 'name',
                    children: 'children',
                }"
                :checkStrictly='true' 
                clearable	
                filterable	
                multiple		
                collapseTags	
                :notParentcheckStrictlyChildcheckStrictly="notParentcheckStrictlyChildcheckStrictly"></selectTree>
            </el-form-item>
        </el-col>
      </el-row>
     
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm()">确 定</el-button>
      <el-button @click="cancelForm()">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import selectTree from "@/components/SelectTree";
import { employeeTableListApi,AddDepartmentsAdminApi, EditDepartmentsAdminApi,getEmployeeIddepartAdminsApi } from "@/api/staffApi.js"
export default {
  emits:["loadingDepartTreeDataEventHandler"],
  props: {
    showdialog: {
      type: Boolean,
      default: false
    },
    getTreeDepartlist: {
      type: Array,
      default() {
        return []
      }
    }
  },
  watch: {
    showdialog() {
      this.dialogFormVisible = this.showdialog;
    },
    "formList.employeeIds"() {
      if (this.formList.employeeIds) {
        this.$refs.ruleForm.clearValidate(['employeeIds'])//清除验证
      }
    },
    "formList.departIds"() {
      if (this.formList.departIds) {
        this.$refs.ruleForm.clearValidate(['departIds'])//清除验证
      }
    }
  },
  components: {
    selectTree //注册组件
  },
  data() {
    return {
      title: "",
      dialogFormVisible: this.showdialog,
      OperType: 0, //0 新增  1修改
      formList: {},
      params: {//搜索条件
        pageIndex: 1,
        pageSize: 10,
        keyword: '',
        total: 0
      },
      rules: {
        employeeIds: [{ required: true, message: "请选择选择用户", trigger: "blur" }],
        departIds: [{ required: true, message: `请选择要设置的${$SuperviseStr.depart}`, trigger: "blur" }],
      },
      defaulDataParent: '',//上级部门默认回选数据
      defaulData: [],
      parentIdShow: true,
      tableDataEmployee: [],
      // getTreeDepartlist:[],
      departlabel: `要设置的${$SuperviseStr.depart}：`,
      notParentcheckStrictlyChildcheckStrictly: 1,//子选中，孙跟着选中，但父不选中--》1代表用此方案，0代表不用此方案
      defaulDataArr: [],//编辑选中的id
      loadedEmployeeIds: {}
    };
  },
  computed: {
    defaultExpandedKeys: function () {
      var allData = this.getTreeDepartlist;
      if (allData?.length > 0) {
        return [allData[0].id];
      }
      return [];
    }
  },
  methods: {
    loadingDepartTreeDataEventHandler: function (keyword) {
      this.$emit("loadingDepartTreeDataEventHandler", keyword);
    },
    selectClickT(val) {
      console.log("当前的事件为:")
      console.log(val)
      this.getTreeDepartlist = val
    },
    sortTableData(arr) {//递归排序
      if (arr.length) {
        arr.forEach(item => {
          item.displayOrderNumber = item.displayOrder
          if (item.children.length) {
            this.sortTableData(item.children)
          }
        })
      }
    },
    getTableRow(data, type) {
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type;
      if (this.OperType == 0) {
        this.title = "添加";
        this.defaulData = []
      } else {
        this.title = "编辑";
      }

      this.employeeTableList()//列表表格
      this.getTreeData(this.getTreeDepartlist)
    },
    checkChangeParent(key, data) {//selectTree组件-复选框选中的数据
      // console.log(typeof key)
      // console.log(data)
      // // this.formList.parentId=key
      // this.$set(this.formList,"parentId",key)
      // console.log(this.formList.parentId)
    },
    checkChange(key, data) {//selectTree组件-复选框选中的数据
      // debugger
      console.log(key)
      console.log(data)
      this.$set(this.formList, "departIds", 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)
        }
      })
      if (this.OperType == 1) {//编辑，根据员工id获取部门管理
        this.getEmployeeIddepartAdmins()
      }
    },
    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) {
      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
        }
      })
    },
    getEmployeeIddepartAdmins() {
      var self = this;
      if (!self.loadedEmployeeIds[self.formList.employeeId]) {
        self.loadedEmployeeIds[self.formList.employeeId] = true;
        let obj2 = { domainId: this.$route.query.domainId }
        getEmployeeIddepartAdminsApi(self.formList, obj2).then(response => {
          if (response.status == 200) {
            this.defaulDataArr = [] //重置              
            if (response.data) {
              response.data.forEach(item => {
                // debugger
                this.defaulDataArr.push(item.departId)//第一步：将列表页面返回过来的部门id，赋值给数组
                this.getChildrenDepartId(item, this.getTreeDepartlist)//第二步：递归循环获取子级id，选中                     
              })
            }
            this.$nextTick(() => {
              let Arr = [...new Set(this.defaulDataArr)]//数组去重es6最快捷方法==》new Set([1,2,3,2]) 返回集合，[...new Set([1,2,3,2])] 表示把集合转完数组；Array.from(new Set(arr))等同于[...new Set(arr)]
              this.defaulData = Arr
              console.log('在next这边输出--curValue')
            })
          }
        })
      } else {
        console.log("调用getEmployeeIddepartAdmins..." + self.loadedEmployeeIds);
      }
    },
    getChildrenDepartId(item, getTreeDepartlistItem) {
      // debugger
      if (Array.isArray(getTreeDepartlistItem)) {//Array.isArray()判断是否数组
        getTreeDepartlistItem.forEach(its => {
          if (this.defaulDataArr.indexOf(its.parentId) > -1) {//this.defaulDataArr.indexOf(its.parentId)>-1 表示选中的id跟子级的父id（parentId）一样，也一起加入选中，获取子级id给数组
            this.defaulDataArr.push(its.id)
          }
          this.getChildrenDepartId(item, its.children) //递归循环获取子级id，选中           
        })
      }
    },
    submitForm() {
      let obj2 = { domainId: this.$route.query.domainId }
      if (this.OperType == 0) {
        //新增
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.OperType == 0) {
            AddDepartmentsAdminApi(this.formList, obj2).then((response) => {
              //新增
              if (response.status == 200) {
                let newobj = JSON.parse(JSON.stringify(this.formList));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            });
          } else {
            EditDepartmentsAdminApi(this.formList, obj2).then((response) => {
              //修改
              if (response.status == 200) {
                let newobj = JSON.parse(JSON.stringify(this.formList));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    cancelForm() {
      //取消关闭
      this.$emit("update:showdialog", false);
      this.$nextTick(function () {
        this.$refs.ruleForm.resetFields(); //重置输入框提示
      });
    },
  },
};
</script>
<style lang="scss">
.elradioLineheight{
    margin-top:5px; 
  .el-radio{display: block; line-height: 30px;}
}
</style>