<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible="dialogFormVisible"
    @close="cancelForm"
    :close-on-click-modal="false"
    class="el-dialog-single"
  >
    <el-form label-width="150px" :model="formList" :rules="rules" ref="ruleForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="departlabel" prop="name">
            <el-input
              auto-complete="off"
              v-model="formList.name"
              :placeholder="departplaceholder"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="parentIdShow">
        <el-col :span="24">
          <el-form-item
            :label="departlabel2"
            prop="parentId"
            v-if="parentIdShow"
          >
            <selectTree
              ref="selectTreeParent"
              @getValue="checkChangeParent"
              :curValue="defaulDataParent"
              :data="getTreeDepartlist"
              :obj="{
                id: 'id',
                label: 'name',
                children: 'children',
              }"
              checkStrictly
              clearable
              filterable
              collapseTags
            ></selectTree>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="设置为部门主管:" prop="leaderEmployeeIdList">
            <el-select
              v-model="leaderEmployeeIdList"
              placeholder="请选择"
              multiple
              clearable
              filterable

              collapse-tags
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in tData"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="parentIdShow">
        <el-col :span="24">
          <el-form-item label="排序：" prop="displayOrder" v-if="parentIdShow">
            <el-input
              auto-complete="off"
              v-model.number="formList.displayOrder"
              clearable
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="通讯录权限：" prop="permissionType">
            <el-radio-group
              v-model="formList.permissionType"
              class="elradioLineheight"
            >
              <el-radio label="JustSelf">可见自己</el-radio>
              <el-radio label="JustOnDepart"
                >可见所在{{ $SuperviseStr.depart }}成员</el-radio
              >
              <el-radio label="OnDepartAndSub"
                >可见所在{{ $SuperviseStr.depart }}及下级{{
                  $SuperviseStr.depart
                }}成员</el-radio
              >
              <el-radio label="Whole">可见全部成员</el-radio>
              <el-radio label="Special"
                >可见指定{{ $SuperviseStr.depart }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="formList.permissionType == 'Special'">
        <el-col :span="24">
          <el-form-item label="" prop="allowedDepartIds">
            <selectTree
              ref="selectTree"
              @getValue="checkChange"
              @selectClickT="selectClickT"
              :curValue="defaulData"
              :data="getTreeDepartlist"
              :obj="{
                id: 'id',
                label: 'name',
                children: 'children',
              }"
              checkStrictly
              clearable
              filterable
              multiple
              collapseTags
            ></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 {
  StaffDepartmentListApi,
  AddDepartmentsApi,
  EditDepartmentsApi,
  UserDeptListApi,
} from "@/api/staffApi.js";
export default {
  props: ["showdialog"],
  watch: {
    showdialog() {
      this.leaderEmployeeIdList=[]
      this.dialogFormVisible = this.showdialog;
    },
    "formList.parentId"() {
      console.log(this.formList.parentId);
      if (this.formList.parentId) {
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate(["parentId"]); //清除验证
        });
      }
    },
  },
  components: {
    selectTree, //注册组件
  },
  data() {
    return {
      title: "",
      dialogFormVisible: this.showdialog,
      OperType: 0, //0 新增  1修改
      leaderEmployeeIdList:[],
      formList: {
   

      },
      rules: {
        name: [
          {
            required: true,
            message: `请输入${$SuperviseStr.depart}名称`,
            trigger: "blur",
          },
        ],
        parentId: [
          {
            required: true,
            message: `请选择上级${$SuperviseStr.depart}`,
            trigger: "blur",
          },
        ],
        permissionType: [
          { required: true, message: "请选择通讯录权限", trigger: "blur" },
        ],
        allowedDepartIds: [
          {
            required: true,
            message: `请可见指定${$SuperviseStr.depart}`,
            trigger: "blur",
          },
        ],
      },
      defaulDataParent: "", //上级部门默认回选数据
      defaulData: [],
      getTreeDepartlist: [],
      parentIdShow: true,
      departlabel: `${$SuperviseStr.depart}名称：`,
      departlabel2: `上级${$SuperviseStr.depart}：`,
      departplaceholder: `请输入${$SuperviseStr.depart}名称`,
      tData: [],
    };
  },
  methods: {
    async getTableRow(data, type, staffDepartmentData) {
      let newRowData = JSON.parse(JSON.stringify(data)); //拷贝一份存储对象
      this.formList = newRowData; //拷贝一份存储对象引用不同地址
      this.OperType = type;
      UserDeptListApi({
        //搜索条件
        pageIndex: 1,
        pageSize: 10000,
        keyword: "",
        departIds: [data.id],
        total: 0,
      }).then((response) => {
        if (response.data.data) {
          this.tData = response.data.data;
          this.leaderEmployeeIdList = response.data.data.filter(el => el.departLeader)?.map(e => e.id)
        }
      });

      this.tableDatalist(staffDepartmentData); //表格部门列表--异步--同步化

      console.log("async第二步");
      if (this.OperType == 0) {
        this.title = "添加";
        this.$set(this.formList, "permissionType", "JustSelf");
        this.defaulDataParent = [];
        this.formList.allowedDepartIds = [];
        this.parentIdShow = true;
      } else {
        this.title = "编辑";
        this.defaulDataParent = this.formList.parentId;
        this.defaulData = this.formList.allowedDepartIds;

        if (this.formList.parentId == undefined) {
          //undefined表示顶级
          this.parentIdShow = false;
        } else {
          this.parentIdShow = true;
        }
      }
    },
    tableDatalist(staffDepartmentData) {
        this.getTreeDepartlist = staffDepartmentData;
        this.sortTableData(this.getTreeDepartlist);
      //表格列表
    //   return new Promise((resolve, reject) => {
    //     let obj = { domainId: this.$route.query.domainId }; //获取url域domainId
    //     StaffDepartmentListApi(obj).then((response) => {
    //       if (response.data) {
    //         this.getTreeDepartlist = response.data;
    //         this.sortTableData(this.getTreeDepartlist);
    //         console.log("async第一步");
    //         resolve();
    //       }
    //     });
    //   });
    },
    sortTableData(arr) {
      //递归排序
      if (arr.length) {
        arr.forEach((item) => {
          item.displayOrderNumber = item.displayOrder;
          let allowedDepartsStr = [];
          if (item.allowedDeparts && item.allowedDeparts.length) {
            item.allowedDeparts.forEach((its) => {
              allowedDepartsStr.push(its.name);
            });
            item.allowedDepartsStr = allowedDepartsStr.join(",");
          }
          if (item.children.length) {
            this.sortTableData(item.children);
          }
        });
      }
    },
    selectClickT(val) {
      console.log(val);
      this.getTreeDepartlist = val;
    },
    checkChangeParent(key, data) {
      //selectTree组件-复选框选中的数据
      console.log(key);
      console.log(data);
      this.$set(this.formList, "parentId", key);
    },
    checkChange(key, data) {
      //selectTree组件-复选框选中的数据
      console.log(key);
      console.log(data);
      if (key.length) {
        this.$set(this.formList, "allowedDepartIds", key); //有值才赋值，不然有bug，关闭必须清除this.defaulData=[]
      }
    },
    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);
        }
      });
    },
    submitForm() {
      console.log(this.formList,this.leaderEmployeeIdList);
      if (
        this.formList.allowedDepartIds &&
        this.formList.allowedDepartIds.length
      ) {
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate(["allowedDepartIds"]); //清除验证
        });
      }
      let obj2 = { domainId: this.$route.query.domainId };
      if (this.OperType == 0) {
        //新增
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.OperType == 0) {
            AddDepartmentsApi({...this.formList,leaderEmployeeIdList:this.leaderEmployeeIdList}, obj2).then((response) => {
              //新增
              if (response.status == 200) {
                let newobj = JSON.parse(JSON.stringify(this.formList));
                this.$emit("refurlist", newobj); //确定后发送$emit绑定父数据
                this.cancelForm();
              }
            });
          } else {
            EditDepartmentsApi({...this.formList,  leaderEmployeeIdList:this.leaderEmployeeIdList}, 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(); //重置输入框提示
        this.defaulDataParent = [];
        this.defaulData = [];
      });
    },
  },
};
</script>
<style lang="scss">
.elradioLineheight {
  margin-top: 5px;
  .el-radio {
    display: block;
    line-height: 30px;
  }
}
</style>
