<template>
  <div class="template-container">
    <el-dialog  z-index="2000"
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single"
  >
      <el-form
        label-width="200px"
        :model="formData"
        :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="formData.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>{{bindData.name}}</span>            
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
              <el-form-item prop="departIds">
                <div class="item-flex-caption">
                    <div><label>{{ departlabel + '('+formData.departIds.length+')' }}</label></div>
                    <div class="button"><el-button @click="openSelectDepartment">选择部门</el-button><el-button type="danger" @click="clearSelectedDepartment">清除选中部门</el-button></div>
                  </div>
                  <div class="item-flex">
                    <el-tag v-for="tag in departments" :key="tag.id" closable @close="removeSelectedDepartment(tag)">
                      {{ tag.name }}
                    </el-tag>
                  </div>
              </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>
    <el-dialog class="depart-admin-dialog" :visible="true"  :visiblexxx="bindData.showSelectDepartmentDialog" v-if="bindData.showSelectDepartmentDialog"
      @close="depart_dialog_closeSelectDepartment" z-index="2001">
        <select-department :selectedDepartIds="formData.departIds"
        :loadingDepartment.sync="bindData.showSelectDepartmentDialog"
        @apply-selected-department-handler="depart_dialog_handleApplySelectedDepartment"
        @cancel-selected-department-handler="depart_dialog_closeSelectDepartment"></select-department>
      </el-dialog> 
  </div>
</template>
<script>
import { employeeTableListApi, AddDepartmentsAdminApi, EditDepartmentsAdminApi, getEmployeeIddepartAdminsApi,StaffDepartmentListApi  } from "@/api/staffApi.js"
import { defineAsyncComponent } from 'vue'
import selectDepartment from "./SelectDepartment.vue"
import { number } from "@/utils/validate";

var localSelectedDepartmentsFromDialog = {};
var localLoadedDepartments = false;
export default {
  props: {
    showdialog: {
      type: Boolean,
      default: false
    },
    getTreeDepartlist: {
      type: Array,
      default() {
        return []
      }
    },
    paramOperType: {
      type: Number,
      default() {
        return 0
      }
    },
    paramData: {
      type: Object,
      default() {
        return {}
      }
    }
  },

  components: {
    "select-department": selectDepartment
  },
  data() {
    return {
      title: "",
      dialogFormVisible: this.showdialog,
      OperType: this.paramOperType, //0 新增  1修改
      params: {//搜索条件
        pageIndex: 1,
        pageSize: 10,
        keyword: '',
        total: 0
      },
      rules: {
        employeeIds: [{ required: true, message: "请选择选择用户", trigger: "blur" }],
        departIds: [{ required: true, message: `请选择要设置的${$SuperviseStr.depart}`, trigger: ["change", "blur"] }],
      },
      departments: [],


      filteredDepartments: [],
      defaulData: [],
      tableDataEmployee: [],
      departlabel: `要设置的${$SuperviseStr.depart}：`,
      defaulDataArr: [],//编辑选中的id

      departmentsForSelectList: [],

      bindData: {
        employeeId: null,
        name: null,
        showSelectDepartmentDialog: false,
        renderDepartmentDialog: false
      },
      formData: {
        departIds: [],
        employeeIds: []
      }
    };
  },
  watch: {
    showdialog() {
      
    },
    "formData.employeeIds"() {
      if (this.formData.employeeIds) {
        //this.$refs.ruleForm.clearValidate(['employeeIds'])//清除验证
      }
    },
    "formData.departIds"(nValue,oValue) {
      var self = this;
      if (self.formData.departIds?.length > 0) {
        //self.$refs.ruleForm.clearValidate(['departIds'])//清除验证
      }
    }
  },
  mounted() {

    var self = this;
    var data = this.paramData;
    self.bindData.employeeId = data.employeeId;
    self.bindData.name = data.name;
    self.formData.employeeId = data.employeeId;
    self.OperType = this.paramOperType;
    if (self.OperType == 0) {
      self.title = "添加";
      this.defaulData = []
    } else {
      self.title = "编辑";
    }
    console.log("mounted 监控节点信息...",data);
    self.dialogFormVisible = this.showdialog;
    if (self.dialogFormVisible) {
      if (!self.formData.employeeId) {
        self.departments = [];
        self.formData.departIds = []
        self.formData.employeeIds = [];
        self.filterMethod("")//列表表格
        return;
      }

      let obj2 = { domainId: this.$route.query.domainId }
      getEmployeeIddepartAdminsApi({
        employeeId: self.bindData.employeeId
      }, obj2).then(response => {
        if (response.status == 200) {
          this.defaulDataArr = [] //重置              
          if (response.data) {
            var selectedDepartIds = [];
            var selectedDeparts = [];
            response.data.forEach(item => {
              selectedDeparts.push({
                id: item.departId,
                name: item.departName
              });

              selectedDepartIds.push(item.departId);
            })

            self.departments = selectedDeparts;
            self.formData.departIds = selectedDepartIds;
          }
          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
          })
        }
      })
    }
  },
  computed: {
    defaultExpandedKeys: function () {
      var allData = this.getTreeDepartlist;
      if (allData?.length > 0) {
        return [allData[0].id];
      }
      return [];
    }
  },
  methods: {
    /**
     * 来自父页面的刷新的时候调用到
     * @param data 
     * @param type 
     */
    getTableRow(data, type) {
      /**
       * 选择该人员
       */
      this.bindData.employeeId = data.employeeId;
      this.bindData.name = data.name;
      this.formData.employeeId = data.employeeId;
      this.OperType = type;
      if (this.OperType == 0) {
        this.title = "添加";
        this.defaulData = []
      } else {
        this.title = "编辑";
      }

      /**
       * 刷新父页面的列表数据
       */
      //this.employeeTableList()//列表表格
      //this.getTreeData(this.getTreeDepartlist)
    },
    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
        }
      })
    },
    submitForm() {
      console.log("当前提交的表单信息为", this.formData);

      if (this.OperType == 0) {
        //新增
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let obj2 = { domainId: this.$route.query.domainId }
          if (this.OperType == 0) {
            AddDepartmentsAdminApi(this.formData, obj2).then((response) => {
              //新增
              if (response.status == 200) {
                let newobj = JSON.parse(JSON.stringify(this.formData));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            });
          } else {
            EditDepartmentsAdminApi(this.formData, obj2).then((response) => {
              //修改
              if (response.status == 200) {
                let newobj = JSON.parse(JSON.stringify(this.formData));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            });
          }
        } else {
          console.log("表单执行失败", valid);
          return false;
        }
      });
    },
    cancelForm() {
      //取消关闭
      var self = this;
      self.$emit("update:showdialog", false);
      /*
      this.$nextTick(function () {
          setTimeout(() => {
            self.$refs.ruleForm.resetFields(); //重置输入框提示
          }, 10);
      });*/
    },

    openSelectDepartment() {
      var self = this;
      self.$refs.ruleForm.clearValidate(["employeeIds", "departIds"]); //重置输入框提示

      if (!self.bindData.renderDepartmentDialog) {
        self.bindData.renderDepartmentDialog = true;
      }
      self.bindData.showSelectDepartmentDialog = true;
    },

    clearSelectedDepartment() {
      this.formData.departIds = [];
      this.departments = [];
    },

    removeSelectedDepartment(data) {
      var self = this;
      self.formData.departIds = self.formData.departIds.filter(ii => ii != data.id);
      self.departments = self.departments.filter(ii => ii != data);
    },

    /**
     * 弹框选择部门的功能
     */
    depart_dialog_closeSelectDepartment() {
      this.bindData.showSelectDepartmentDialog = false;
    },
    depart_dialog_handleApplySelectedDepartment(dpts) {
      var self = this;

      self.bindData.showSelectDepartmentDialog = false;

      var dptIds = [];
      for (var i = 0; i < dpts.length; i++) {
        dptIds.push(dpts[i].id);
      }
      self.departments = dpts;

      self.formData.departIds = dptIds;
    }
  },
};
</script>
<style lang="scss">
.elradioLineheight{
    margin-top:5px; 
  .el-radio{display: block; line-height: 30px;}
}

.item-flex-caption{
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.item-flex-caption .button{
  flex: 0.6;
}

.item-flex{
  max-height: 260px;
  overflow-y: auto;
}
.item-flex .el-tag{
  margin-left: 10px;
}
.depart-admin-dialog .contentBox{
  height: 300px;
  overflow-y: auto;
}
</style>