<template>
  <div class="common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div class="add-department-container">
          <div class="setting-cell depart-info" v-if="$route.query.type == 'group'">
            <p class="title">部门信息</p>
            <el-form class="department-info-form" label-position="right" :rules="rules" :model="departInfo" ref="departForm" label-width="120px">
              <el-form-item label="部门名称" prop="name">
                <el-input v-model="departInfo.name"></el-input>
              </el-form-item>
              <el-form-item label="部门排序调整" prop="parentId">
                <el-input :disabled="disabled" v-model="departInfo.chainName" @focus="callGroupSelector" suffix-icon="el-icon-arrow-down"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="setting-cell depart-info" v-else>
            <p class="title">企业信息</p>
            <el-form class="department-info-form" label-position="right" :rules="rules" :model="departInfo" ref="departForm" label-width="120px">
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="departInfo.name" disabled></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="setting-cell" v-if="!isAddNew">
            <p class="title">权限设置</p>
            <permission-setting v-if="!disabled" @callPerSelector="callPerSelector" :departInfo="departInfo" :selfButList="selfButList" :butList="butList" :specialList="specialList" :visibleSpecialLsit="testList" :onlySelfApartList="testList" :treeData="treeData"></permission-setting>
          </div>
          <div class="setting-cell">
            <div class="btn-area">
              <el-button type="primary" @click="saveEdit">保存</el-button>
              <el-button type="primary" @click="saveEdit('continue')">保存并继续添加</el-button>
              <el-button @click="cancel">取消</el-button>
            </div>
          </div>
          <vue-select-employee :changed="changed" :onlyPerson="onlyPerson" :onlyGroup="onlyGroup" :defaultSelection="defaultSelection" :treeSet="treeSet" @handleSelectedList="handleSelectedList" :treeData="treeData"></vue-select-employee>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import permissionSetting from "components/contacts/permissionSet/permissionSetting";
import vueSelectEmployee from "components/common/vueSelectEmployee";
import { getRequest, postRequest, postJsonRequest } from '@/api/api';
export default {
  name: "addDepartment",
  components: {
    navCrumb,
    permissionSetting,
    vueSelectEmployee
  },
  data() {
    return {
      // 面包屑参数
      navpath: [{
          name: '首页',
          path: '/index'
        },
        {
          name: '企业通讯录',
          path: '/administrativeFrame'
        },
        {
          name: '行政架构',
          path: '/administrativeFrame'
        },
        {
          name: '添加子分组',
          path: ''
        }
      ],
      departInfo: {},
      testList: [],
      treeSet: {
        isSelectPerson: false,
        dialogVisible: false,
        isSingle: true // 是否单选
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择父级部门', trigger: 'blur' }
        ]
      },
      treeData: {},
      disabled: true,
      defaultSelection: [],
      defaultParent: [],
      selectorType: "parent",
      changed: "parent",
      onlyPerson: false,
      onlyGroup: [],
      butList: [], // 仅可见本部门，个别员工除外
      specialList: [], // 指定部门/人员可见
      selfButList: []
    };
  },
  methods: {
    /**
     * 获取部门信息
     */
    getDepartInfo() {
      let that = this;
      let params = {
        groupId: that.$route.query.departmentId
      };
      getRequest("/haoban-manage-web/dept/findDeptById", params)
        .then(res => {
          if (res.data.errorCode == 1) {
            this.formatGroupInfo(res.data.result);
          } else {
            that.$message.error({
              duration: 1000,
              message: res.data.message
            });
          }
        })
        .catch(e => {
          that.$message.error({
            duration: 1000,
            message: e.message
          });
        })
    },
    /**
     *
     * 处理部门信息
     */
    formatGroupInfo(obj) {
      let that = this;
      that.departInfo.parentName = obj.chainName;
      that.defaultParent = [{
        label: that.departInfo.parentName,
        id: obj.parentId,
        groupId: obj.parentId
      }];
      obj.noPreClerkList = obj.noPreClerkList || [];
      obj.allowClerkList = obj.allowClerkList || [];
      obj.allowDeptList = obj.allowDeptList || [];
      obj.noPreClerkList.forEach(clerk => {
        clerk.label = clerk.name;
        clerk.id = clerk.employeeClerkId;
      });
      obj.allowClerkList.forEach(clerk => {
        clerk.label = clerk.name;
        clerk.id = clerk.employeeClerkId;
      });
      obj.allowDeptList.forEach(group => {
        group.label = group.name;
        group.id = group.groupId;
      });
      that.specialList = obj.allowDeptList.concat(obj.allowClerkList);
      if (obj.type == 1) {
        that.butList = obj.noPreClerkList;
        that.selfButList = [];
      } else if (obj.type == 2) {
        that.selfButList = obj.noPreClerkList;
        that.butList = [];
      }
      that.departInfo = obj;
    },
    /**
     * 唤起部门选择器
     */
    callGroupSelector() {
      this.selectorType = "parent";
      this.defaultSelection = this.defaultParent;
      this.onlyPerson = false;
      this.onlyGroup = [];
      this.changed = "parent";
      this.treeSet = {
        dialogVisible: true,
        isSingle: true,
        isSelectPerson: false
      };
    },
    callPerSelector(type, list) {
      if (type == "but") {
        this.selectorType = type;
        this.defaultSelection = list;
        this.onlyPerson = true;
        this.onlyGroup = [this.$route.query.departmentId];
        this.changed = type;
        this.treeSet = {
          dialogVisible: true,
          isSingle: false,
          isSelectPerson: true
        };
      } else {
        this.selectorType = type;
        this.defaultSelection = list;
        this.onlyPerson = false;
        this.onlyGroup = [];
        this.changed = type;
        this.treeSet = {
          dialogVisible: true,
          isSingle: false,
          isSelectPerson: true
        };
      }
    },
    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      console.log(group);
      if (this.changed == "parent") {
        this.departInfo.parentId = group ? group.id : "";
        this.departInfo.parentName = group ? group.label : "";
      } else if (this.changed == "but") {
        this.butList = group;
      } else if (this.changed == "special") {
        this.specialList = group;
      }
    },
    saveEdit(goAhead = "") {
      console.log(this.departInfo);
      let _this = this;
      this.$refs.departForm.validate(valid => {
        if (!valid) {
          return false;
        }
        let type = _this.departInfo.type;
        let idArr = [];
        if (type != "") {
          _this[type == 1 ? "butList" : "selfButList"].forEach(per => {
            idArr.push(per.id);
          });
        }
        let allowCherkIds = [];
        let allowDepartIds = [];
        _this.specialList.forEach(per => {
          if (per.employeeClerkId) {
            allowCherkIds.push(per.id);
          } else {
            allowDepartIds.push(per.id);
          }
        });
        let ids = idArr.join(",")
        let params = {
          type,
          noPreCherkIds: ids,
          allowCherkIds: allowCherkIds.join(","),
          allowDepartIds: allowDepartIds.join(","),
          parentId: _this.departInfo.parentId,
          name: _this.departInfo.name
        }
        if (!_this.isAddNew) params.groupId = _this.$route.query.departmentId;
        let url = _this.isAddNew ? "/haoban-manage-web/dept/insert" : "/haoban-manage-web/dept/update";
        getRequest(url, params)
          .then(res => {
            console.log(res);
            if (res.data.errorCode == 1) {
              _this.$message.success({
                duration: 1000,
                message: "操作成功！"
              });
              console.log(goAhead);
              if (goAhead == "continue") {
                _this.departInfo = {
                  name: "",
                  parentName: "",
                  parentId: ""
                }
                _this.disabled = true;
                _this.getGroupData();
              } else {
                window.history.go(-1);
              }
            } else {
              _this.$message.error({
                duration: 1000,
                message: res.data.message
              });
            }
          })
          .catch(e => {
            _this.$message.error({
              duration: 1000,
              message: e.message
            });
          });
      });
    },
    getGroupData() {
      let _this = this;
      let params = {
        isStoreGroup: 0
      };
      getRequest("/haoban-manage-web/dept/deptListForCompany", params)
        .then(res => {
          let treeData = [];
          let personData = [];
          if (res.data.errorCode == 1) {
            treeData = res.data.result.departmentList || [];
            personData = res.data.result.searchList || []
          }
          // _this.formatGroupData(treeData, personData);
          _this.treeData = {
            treeData,
            personData
          };
          _this.disabled = false;
        })
        .catch(e => {
          console.log(e, "error");
        });
    },
    cancel() {
      this.$confirm(" 是否确认取消，取消后当前页面信息将丢失 ？", "提示", {
        type: "warning"
      }).then(() => {
        window.history.go(-1);
      }).catch(e => {
        console.log(e);
      });
    }
  },
  beforeMount() {
    this.getGroupData();
    if (!this.isAddNew) {
      this.getDepartInfo();
    }
  },
  computed: {
    isAddNew() {
      return !!(this.$route.query.addnew == 1);
    }
  }
};

</script>
<style lang="scss">
.add-department-container {
  .setting-cell {
    background: #fff;
    margin-bottom: 24px;

    .title {
      height: 55px;
      line-height: 55px;
      border-bottom: 1px solid #E4E7ED;
      text-indent: 32px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .department-info-form {
      padding: 24px 32px;

      .el-input {
        width: 380px;
      }
    }

    .btn-area {
      width: 100%;
      text-align: center;
      padding: 12px;
    }
  }
}

</style>
