<template>
  <div class="organizManage-main">
    <div class="organizManage-mainLeft">
      <div class="public-function-div">
        机构树
        <el-button
          @click="orgShowHidden"
          type="success"
          size="small"
          class="orgShowHidden"
          >{{ isAllDataShow ? "显示停用组织" : "隐藏停用组织" }}</el-button
        >
        <el-button
          @click="controllNode()"
          type="success"
          size="small"
          class="refresh"
          >{{ isSpread ? "展开" : "收起" }}</el-button
        >
        <el-button
          @click="handleReset('formItem')"
          type="primary"
          size="small"
          class="_refresh3"
          v-privilege="activeMenu + 'ADD'"
          >新增顶级</el-button
        >
      </div>
      <el-input
        placeholder="输入关键字进行过滤"
        class="filterTree"
        v-model="filterText"
      >
      </el-input>
      <el-tree
        ref="orgTree"
        :data="orgTree"
        :props="defaultProps"
        node-key="orgId"
        @node-expand="nodeExpand"
        @node-click="nodeClick"
        :expand-on-click-node="true"
        :style="{ height: treeHeight + 'px' }"
        :filter-node-method="filterOrgTree"
        v-loading="treeLoading"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span class="nodeOperate">
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                <i
                  class="el-icon-arrow-down icore-icon-size"
                  style="color: #111; background-color: #61f06e"
                ></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'add', node: node, data: data }"
                    class="el-icon-plus addMenuPr"
                    >添加</el-dropdown-item
                  >
                </el-row>
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'delete', node: node, data: data }"
                    class="el-icon-delete delMenuPr"
                    >删除</el-dropdown-item
                  >
                </el-row>
                <el-row v-show="data.status === '0'">
                  <el-dropdown-item
                    :command="{ str: 'enable', node: node, data: data }"
                    class="el-icon-share unlockMenuPr"
                    >启用</el-dropdown-item
                  >
                </el-row>
                <el-row v-show="data.status === '1'">
                  <el-dropdown-item
                    :command="{ str: 'disable', node: node, data: data }"
                    class="el-icon-remove lockMenuPr"
                    >停用</el-dropdown-item
                  >
                </el-row>
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'up', node: node, data: data }"
                    class="el-icon-upload2 upMenuPr"
                    >上移</el-dropdown-item
                  >
                </el-row>
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'down', node: node, data: data }"
                    class="el-icon-download downMenuPr"
                    >下移</el-dropdown-item
                  >
                </el-row>
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'left', node: node, data: data }"
                    v-if="node.level > 1"
                    class="el-icon-d-arrow-left leftMenuPr"
                    >左移</el-dropdown-item
                  >
                </el-row>
                <el-row>
                  <el-dropdown-item
                    :command="{ str: 'right', node: node, data: data }"
                    v-if="
                      node.level === 1 && node === node.parent.childNodes[0]
                        ? false
                        : true
                    "
                    class="el-icon-d-arrow-right rightMenuPr"
                    >右移</el-dropdown-item
                  >
                </el-row>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="organizManage-mainRight">
      <div class="public-function-div">编辑区</div>
      <el-form
        ref="formItem"
        :model="formItem"
        :rules="ruleValidate"
        label-width="80px"
        class="FormorganizManage-main"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="父机构" prop="pName">
              <el-input
                v-model="formItem.pName"
                disabled
                size="small"
                style="vertical-align: top"
              >
                <el-button slot="append" @click="handleReset('formItem')"
                  >清空</el-button
                >
              </el-input>
            </el-form-item>
            <el-form-item label="机构id" prop="orgId" style="display: none">
              <el-input
                v-model="formItem.orgId"
                placeholder="请输入"
                disabled
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="orgCode">
              <el-input
                v-model="formItem.orgCode"
                placeholder="请输入"
                :disabled="!(operateStatus === 'add')"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称" prop="orgName">
              <el-input
                v-model="formItem.orgName"
                placeholder="请输入"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位(负责)" prop="dutys">
              <el-select
                v-model="formItem.dutys"
                placeholder="请选择职务"
                size="small"
                multiple
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dutyList"
                  :key="item.dutyId"
                  :label="item.dutyName"
                  :value="item.dutyId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门分类" prop="depType">
              <el-select
                v-model="formItem.depType"
                placeholder="请选择部门分类"
                size="small"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in depTypeList"
                  :key="item.dictCode + index"
                  :label="item.dictName"
                  :value="item.dictCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formItem.remark"
                placeholder="请输入"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5 }"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            size="small"
            v-show="operateStatus === 'edit'"
            style="float: right"
            type="primary"
            @click="handleSubmit('formItem')"
            v-privilege="activeMenu + 'EDIT'"
            :loading="addLoading1"
            >保存
          </el-button>
          <el-button
            size="small"
            v-show="operateStatus === 'add'"
            style="float: right"
            type="primary"
            @click="handleSubmit('formItem')"
            v-privilege="activeMenu + 'ADD'"
            :loading="addLoading2"
            >添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import store from "@/store/index.js";
import dataDictionary from "@/store/dataDictionary.js";
import {
  checkCharLength,
  checkCharLength2,
  checkCharNoChinese,
  checkTel,
  checkEmail,
  checkNumber,
  checkChar,
} from "@/utils/validator.js";
import { objAssign, dgTree } from "@/utils/util.js";
import { proPath } from "@/config/config.js";
export default {
  data() {
    return {
      companys: [], // 用户公司列表
      companyId: "", // 选择公司Id
      companyName: "", // 选择公司名称
      filterText: "",
      store,
      dataDictionary,
      addLoading1: false,
      addLoading2: false,
      treeLoading: false,
      operateStatus: "add",
      treeHeight: 600,
      formItem: {
        orgId: "",
        pId: "",
        pName: "",
        pCode: "",
        pDeptId: "",
        pDeptCode: "",
        cate: "",
        orgCode: "",
        dutys: [],
        orgName: "",
        qrCode: "",
        orgBrief: "",
        contact: "",
        pathName: "",
        tel: "",
        citycode: "",
        officeAddr: "",
        country: "",
        email: "",
        remark: "",
        post: "",
        status: "1",
        isVirtual: "",
        companyId: "",
        depType: "",
      },
      activeMenu: "",
      ruleValidate: {
        orgCode: [
          { required: true, message: "机构编码不能为空", trigger: "change" },
          { validator: checkCharLength, max: 32, trigger: "change" },
          { validator: checkCharNoChinese, trigger: "change" },
        ],
        orgName: [
          { required: true, message: "机构名称不能为空", trigger: "change" },
          { validator: checkChar, trigger: "change" },
          { validator: checkCharLength, max: 240, trigger: "change" },
        ],
        cate: [
          { required: true, message: "机构类别不能为空", trigger: "change" },
        ],
        remark: [
          { validator: checkCharLength2, max: 300, trigger: "change" },
          { validator: checkChar, trigger: "change" },
        ],
        tel: [
          { validator: checkNumber, trigger: "change" },
          { validator: checkTel, trigger: "change" },
          { validator: checkCharLength2, max: 11, trigger: "change" },
        ],
        email: [
          { validator: checkEmail, trigger: "change" },
          { validator: checkCharLength2, max: 100, trigger: "change" },
        ],
        contact: [{ validator: checkCharLength2, max: 100, trigger: "change" }],
        orgBrief: [
          { validator: checkCharLength2, max: 100, trigger: "change" },
        ],
        officeAddr: [
          { validator: checkCharLength2, max: 100, trigger: "change" },
        ],
        post: [
          { validator: checkNumber, trigger: "change" },
          {
            validator: checkCharLength2,
            max: 6,
            message: "请输入正确的邮政编码",
            trigger: "change",
          },
        ],
        depType: [
          { required: true, message: "机构分类不能为空", trigger: "change" },
        ],
      },
      dutyList: [], // 机构关联职级
      oldDutyList: [], // 原有职务信息
      isSpread: true,
      isAllDataShow: true,
      depTypeList: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.orgTree.filter(val);
    },
  },
  computed: {
    //  菜单树数据
    orgTree() {
      let orgTree = this.store.state.system.organizManage.tree;
      // 页面筛选注释掉
      // let orgTree = this.companyId !== '' ? this.getTreeAll(_orgTree, this.companyId) : _orgTree;
      return orgTree;
    },
    //  树配置
    defaultProps() {
      return this.store.state.system.organizManage.defaultProps;
    },
    //  展开数组
    expandedKeys: {
      get: function () {
        return this.store.state.system.organizManage.expandedKeys;
      },
      set: function (data) {
        this.store.commit("system/organizManage/expandedKeys", data);
      },
    },
    //  选中节点数据
    orgItem() {
      return this.store.state.system.organizManage.item;
    },
    //  树配置
    formItemCate() {
      return this.store.state.system.organizManage.formItemCate;
    },
    //  是否虚机构
    formItemIsVirtual() {
      return this.store.state.system.organizManage.formItemIsVirtual;
    },
  },
  created() {
    this.activeMenu = window.top.localStorage.getItem("activeMenu");
  },
  mounted() {
    //移除表单自动校验
    this.$nextTick(() => {
      this.$refs["formItem"].clearValidate();
    });
    // 获取公司信息
    this.companys = JSON.parse(window.top.localStorage.getItem("companys"));
    this.companyId = window.top.localStorage.getItem("companyId");
    if (this.companyId !== "" && this.companyId !== null) {
      this.companyName = this.companys.find(
        (x) => x.id === this.companyId
      ).companyName;
    }
    this.initData();
    this.getDepType();
    //  设置树区域高度
    this.treeHeight = this.getTreeHeight(this.$refs["orgTree"].$el);
  },
  methods: {
    initData() {
      //  查询列表
      this.treeLoading = true;
      this.store
        .dispatch("system/organizManage/tree", this.companyId)
        .then((res) => {
          if (res.code === "0") {
            this.store.commit("system/organizManage/tree", res.data);
            this.$nextTick(() => {
              console.log('this.checkPrivilege(this.activeMenu + "UNLOCK")');
              console.log(this.activeMenu);
              console.log(this.checkPrivilege(this.activeMenu + "UNLOCK"));
              $(".delMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "DELET")
                  ? "inline-block"
                  : "none"
              );
              $(".addMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "ADD")
                  ? "inline-block"
                  : "none"
              );
              $(".unlockMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "UNLOCK")
                  ? "inline-block"
                  : "none"
              );
              $(".lockMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "LOCK")
                  ? "inline-block"
                  : "none"
              );
              $(".upMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".downMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".rightMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".leftMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".nodeOperate").css(
                "display",
                this.checkPrivilege(this.activeMenu + "MENUDELET") ||
                  this.checkPrivilege(this.activeMenu + "MENUADD") ||
                  this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
            });
            this.treeLoading = false;
          } else {
            this.$message.error(res.message);
            this.treeLoading = false;
          }
        });
      this.getDutyList();
    },
    // 下拉选择公司
    selectComPany(command) {
      this.companyId = command.id;
      this.companyName = command.companyName;
      this.initData();
    },
    // 获取职务
    getDutyList() {
      let form = {
        pageNum: 1,
        pageSize: 100000,
        companyId: this.companyId,
      };
      this.axios
        .get("pass/v1/sysdutys/", { params: form })
        .then((res) => {
          if (res.code === "0") {
            this.dutyList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getUserOldDuty(val) {
      let form = {
        pageNum: 1,
        pageSize: 100000,
        companyId: this.companyId,
        resourceId: this.formItem.orgId,
        resourceType: "2",
      };
      this.axios
        .get("pass/v1/sysuserdutys/", { params: form })
        .then((res) => {
          if (res.code === "0") {
            this.oldDutyList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 遍历树获取相应公司菜单
    getTreeAll(tree, id) {
      let arr = [];
      if (!!tree && tree.length !== 0) {
        tree.forEach((item) => {
          let obj = {};
          obj = { ...item };
          if (obj.hasOwnProperty("companyId") && obj.companyId === id) {
            obj.children = this.getTreeAll(item.children);
            arr.push(obj);
          }
        });
      }
      return arr;
    },
    nodeExpand() {
      this.$nextTick(() => {
        $(".delMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "DELET")
            ? "inline-block"
            : "none"
        );
        $(".addMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "ADD") ? "inline-block" : "none"
        );
        $(".unlockMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "UNLOCK")
            ? "inline-block"
            : "none"
        );
        $(".lockMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "LOCK")
            ? "inline-block"
            : "none"
        );
        $(".upMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".downMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".rightMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".leftMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".nodeOperate").css(
          "display",
          this.checkPrivilege(this.activeMenu + "MENUDELET") ||
            this.checkPrivilege(this.activeMenu + "MENUADD") ||
            this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
      });
    },
    //  点击树事件
    nodeClick(item, el) {
      //  放入
      this.store.commit("system/organizManage/item", item);
      //  清空
      this.$refs["formItem"].resetFields();
      this.getOrgInfo(item.id, el);
      this.getOrgOldDuty(item.id);
      //  点击时为编辑状态
      this.operateStatus = "edit";
      this.$nextTick(() => {
        $(".delMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "DELET")
            ? "inline-block"
            : "none"
        );
        $(".addMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "ADD") ? "inline-block" : "none"
        );
        $(".unlockMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "UNLOCK")
            ? "inline-block"
            : "none"
        );
        $(".lockMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "LOCK")
            ? "inline-block"
            : "none"
        );
        $(".upMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".downMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".rightMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".leftMenuPr").css(
          "display",
          this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
        $(".nodeOperate").css(
          "display",
          this.checkPrivilege(this.activeMenu + "MENUDELET") ||
            this.checkPrivilege(this.activeMenu + "MENUADD") ||
            this.checkPrivilege(this.activeMenu + "EDIT")
            ? "inline-block"
            : "none"
        );
      });
    },
    getOrgInfo(orgId, el) {
      this.axios
        .get("pass/v1/sysorgs/" + orgId)
        .then((res) => {
          if (res.code === "0") {
            //  加入
            this.formItem = objAssign(this.formItem, res.data);
            if (
              this.formItem.dutys !== null &&
              this.formItem.dutys.length > 0
            ) {
              let list = [];
              for (let duty of this.formItem.dutys) {
                list.push(duty.dutyId);
              }
              this.formItem.dutys = list;
            } else {
              this.formItem.dutys = [];
            }
            this.formItem.pName = el.parent.label;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取机构关联职务
    getOrgOldDuty(orgId) {
      let form = {
        pageNum: 1,
        pageSize: 100000,
        companyId: this.companyId,
        resourceId: orgId,
        resourceType: "2",
      };
      this.axios
        .get("pass/v1/sysuserdutys/", { params: form })
        .then((res) => {
          if (res.code === "0") {
            this.oldDutyList = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    addOrgDutys(orgId, list) {
      for (let item of list) {
        let form = {
          dutyId: item,
          resourceId: orgId,
          resourceType: "2",
          companyId: this.companyId,
        };
        this.axios
          .post("pass/v1/sysuserdutys/", form)
          .then((res) => {
            if (res.code === "0") {
              // do
            } else {
              this.$message.error("职务添加失败");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 删除
    deleteOldDuty() {
      for (let item of this.oldDutyList) {
        this.axios
          .delete("pass/v1/sysuserdutys/" + item.id)
          .then((res) => {
            if (res.code === "0") {
              // do
            } else {
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    //  清空 清空为添加，添加直接添加顶级目录
    handleReset(name) {
      this.$refs[name].resetFields();
      this.formItem.pName = "";
      this.operateStatus = "add";
    },
    //  添加点击
    addTreeNode(node, item) {
      this.operateStatus = "add";
      this.$refs["formItem"].resetFields();
      //  设置pId为当前ID
      this.formItem.pId = item.orgId;
      this.formItem.pName = item.orgName;
      //  机构类别：1-机构 0-部门
      if (item.cate === "1") {
        this.formItem.pId = item.orgId;
        this.formItem.pCode = item.orgCode;
      } else if (item.cate === "0") {
        this.formItem.pDeptId = item.orgId;
        this.formItem.pDeptCode = item.orgCode;
      }
      //  清空ID
      this.formItem.orgId = "";
    },
    //  计算树区域高度
    getTreeHeight(dom) {
      return window.innerHeight - dom.offsetTop;
    },
    // 节点上移
    nodeUp(node, data) {
      let that = this;
      console.log(node);
      console.log(data);
      let children = node.parent.childNodes;
      console.log(children);
      if (node === children[0]) {
        that.$message.error("已移至当前顶级，无法继续上移");
      } else {
        let node2 = {};
        for (let i = 0; i < children.length; i++) {
          if (node === children[i]) {
            node2 = children[i - 1];
          }
        }
        let changeList = [node.data, node2.data];
        console.log(changeList);
        this.store
          .dispatch("system/organizManage/dragOrg", {
            dropType: "before",
            changeList: changeList,
          })
          .then((res) => {
            console.log(res);
            if (res.code === "0") {
              this.$refs["orgTree"].remove(node.data.id);
              this.$refs["orgTree"].insertBefore(node.data, node2.data);
              this.$message.success("上移成功");
            } else {
              this.$message({ message: res.message, type: "error" });
            }
          });
      }
    },
    // 节点下移
    nodeDown(node, data) {
      let that = this;
      console.log(node);
      console.log(data);
      let children = node.parent.childNodes;
      console.log(children);
      let index = children.length;
      if (node === children[index - 1]) {
        that.$message.error("已移至当前底级，无法继续下移");
      } else {
        let node2 = {};
        for (let i = 0; i < children.length; i++) {
          if (node === children[i]) {
            node2 = children[i + 1];
          }
        }
        let changeList = [node.data, node2.data];
        console.log(changeList);
        this.store
          .dispatch("system/organizManage/dragOrg", {
            dropType: "after",
            changeList: changeList,
          })
          .then((res) => {
            if (res.code === "0") {
              this.$refs["orgTree"].remove(node.data.id);
              this.$refs["orgTree"].insertAfter(node.data, node2.data);
              this.$message.success("下移成功");
            } else {
              this.$message({ message: res.message, type: "error" });
            }
          });
      }
    },
    // 节点右移
    nodeRight(node, data) {
      let that = this;
      console.log(node);
      console.log(data);
      let children = node.parent.childNodes;
      console.log(children);
      if (node.level === 1 && node === children[0]) {
        that.$message.error("顶级第一个菜单不可降级！");
      } else if (children.length <= 1) {
        that.$message.error("此节点无同级节点以供降级！");
      } else if (children.length > 1) {
        let node2 = {};
        if (node === children[0]) {
          that.$message.error(
            "此节点位于同级中第一个，若要降级请先调整此节点顺序!"
          );
        } else {
          for (let i = 0; i < children.length; i++) {
            if (node === children[i]) {
              node2 = children[i - 1];
              if (node2.hasOwnProperty("data")) {
                // for (let j = 0; j < node2.data.children.length; j++){
                //     if (node.data.orgName === node2.data.children[j].orgName) {
                //         that.$message.error(node2.data.orgName + '中已有同名机构！');
                //     } else if (node.data.orgCode === node2.data.children[j].orgCode) {
                //         that.$message.error(node2.data.orgName + '中已有相同编码机构！')
                //     }else {
                let changeList = [node.data, node2.data];
                console.log(changeList);
                this.store
                  .dispatch("system/organizManage/dragOrg", {
                    dropType: "right",
                    changeList: changeList,
                  })
                  .then((res) => {
                    if (res.code === "0") {
                      this.$refs["orgTree"].remove(node.data.id);
                      this.$refs["orgTree"].append(node.data, node2.data);
                      this.$message.success("已降至前一个同级菜单中");
                    } else {
                      this.$message({ message: res.message, type: "error" });
                    }
                  });
                //     }
                // }
              } else {
                that.$message.error(
                  "未定义情景，请联系管理员添加前端右移逻辑代码！"
                );
              }
            }
          }
        }
      }
    },
    // 节点左移
    nodeLeft(node, data) {
      let that = this;
      console.log(node);
      console.log(data);
      let node2 = {};
      node2 = node.parent;
      if (node2.hasOwnProperty("data")) {
        // for (let i = 0; i < node2.parent.childNodes.length; i++) {
        //     if (node.data.orgCode === node2.parent.childNodes[i].data.orgCode) {
        //         that.$message.error(node.data.orgName + '同级中已有相同编码机构存在');
        //     } else if (node.data.orgName === node2.parent.childNodes[i].data.orgName) {
        //         that.$message.error(node.data.orgName + '同级中已有相同名称机构存在');
        //     } else {
        let changeList = [node.data, node2.data];
        console.log(changeList);
        this.store
          .dispatch("system/organizManage/dragOrg", {
            dropType: "left",
            changeList: changeList,
          })
          .then((res) => {
            if (res.code === "0") {
              this.$refs["orgTree"].remove(node.data.id);
              this.$refs["orgTree"].insertAfter(node.data, node2.data);
              this.$message.success("已升至当前父菜单同级");
            } else {
              this.$message({ message: res.message, type: "error" });
            }
          });
        //     }
        // }
      } else {
        that.$message.error("未定义情景，请联系管理员添加前端左移逻辑代码！");
      }
    },
    handleCommand(command) {
      let that = this,
        str = command.str,
        node = command.node,
        data = command.data;
      switch (str) {
        case "add":
          that.addTreeNode(node, data);
          break;
        case "delete":
          that.delTreeNode(node, data);
          break;
        case "up":
          that.nodeUp(node, data);
          break;
        case "down":
          that.nodeDown(node, data);
          break;
        case "left":
          that.nodeLeft(node, data);
          break;
        case "right":
          that.nodeRight(node, data);
          break;
        case "enable":
          that.updateMenuStatus(node, data, "enable");
          break;
        case "disable":
          that.updateMenuStatus(node, data, "disable");
          break;
      }
    },
    // renderContent (h, { node, data, store }) {
    //     let render = [];
    //     render = [
    //         h('span', {
    //             class: 'el-icon-delete icore-icon-size delMenuPr',
    //             attrs: {
    //                 title: '删除'
    //             },
    //             on: {
    //                 click: (event) => {
    //                     this.delTreeNode(node, data);
    //                     event.stopPropagation();
    //                 }
    //             }
    //         })
    //     ];
    //     //  如果是机构增加 添加按钮
    //     render = [h('span', {
    //         class: 'el-icon-plus icore-icon-size addMenuPr',
    //         attrs: {
    //             title: '添加'
    //         },
    //         on: {
    //             click: (event) => {
    //                 this.addTreeNode(node, data);
    //                 event.stopPropagation();
    //             }
    //         }
    //     })].concat(render);
    //     //下拉菜单
    //     // render = [h('span',{
    //     //     label: '其他',
    //     //     class: 'el-icon-arrow-down icore-icon-size',
    //     //     attrs: {
    //     //         title: '树节点上下左右移动操作'
    //     //     },
    //     // })
    //     // ].concat(render)
    //     //  机构下移 下箭头按钮
    //     render = [h('span', {
    //         class: 'el-icon-download icore-icon-size downMenuPr',
    //         attrs: {
    //             title: '下移'
    //         },
    //         on: {
    //             click: (event) => {
    //                 this.nodeDown(node, data);
    //                 event.stopPropagation();
    //             }
    //         }
    //     })].concat(render);
    //     //  机构上移 上箭头按钮
    //     render = [h('span', {
    //         class: 'el-icon-upload2 icore-icon-size upMenuPr',
    //         attrs: {
    //             title: '上移'
    //         },
    //         on: {
    //             click: (event) => {
    //                 this.nodeUp(node, data);
    //                 event.stopPropagation();
    //             }
    //         }
    //     })].concat(render);
    //     if (node.level > 1) {
    //         //  降到下一级
    //         render = [h('span', {
    //             class: 'el-icon-right icore-icon-size rightMenuPr',
    //             attrs: {
    //                 title: '降至后一级菜单'
    //             },
    //             on: {
    //                 click: (event) => {
    //                     this.nodeRight(node, data);
    //                     event.stopPropagation();
    //                 }
    //             }
    //         })].concat(render);
    //         //  升到上一级
    //         render = [h('span', {
    //             class: 'el-icon-back icore-icon-size leftMenuPr',
    //             style: "font-size: 16px;",
    //             attrs: {
    //                 title: '升至前一级菜单'
    //             },
    //             on: {
    //                 click: (event) => {
    //                     this.nodeLeft(node, data);
    //                     event.stopPropagation();
    //                 }
    //             }
    //         })].concat(render);
    //     }
    //     return h('span',
    //         {
    //             style: {
    //                 position: 'relative',
    //                 width: '100%',
    //                 fontSize: '12px'
    //             },
    //             class: 'og-st-ellipsis'
    //         },
    //         [
    //             h('span', node.label),
    //             h('span', {
    //                 style: {
    //                     position: 'absolute',
    //                     right: '0px'
    //                 }
    //             }, render)
    //         ]);
    // },
    /**
     * 保存数据
     * */
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.operateStatus === "edit") {
            if (!this.formItem.orgId) {
              this.$message.error("请选择数据再来操作");
              return;
            }
            this.$confirm("确定要修改已选择的记录吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                //  修改数据
                this.addLoading1 = true;
                this.formItem.cate = 1;
                this.formItem.companyId = this.companyId;
                // 原有职务删除后重建
                if (
                  this.formItem.dutys !== null &&
                  this.oldDutyList.length > 0
                ) {
                  this.deleteOldDuty();
                }
                if (
                  this.formItem.dutys !== null &&
                  this.formItem.dutys.length > 0
                ) {
                  this.addOrgDutys(this.formItem.orgId, this.formItem.dutys);
                }
                let data = JSON.parse(JSON.stringify(this.formItem));
                for (let key in data) {
                  if (key === "dutys") {
                    delete data[key];
                  }
                }
                this.store
                  .dispatch("system/organizManage/editOrg", {
                    id: this.orgItem.id,
                    form: data,
                  })
                  .then((res) => {
                    this.addLoading1 = false;
                    //
                    if (res.code === "0") {
                      let pId = null;
                      if (res.data.pId) {
                        pId = res.data.pId;
                      }
                      let map = {
                        orgId: res.data.orgId,
                        depType: res.data.depType,
                        orgName: res.data.orgName,
                        pId: pId,
                      };
                      //调用物流系统的资源管理模块的接口，修改组织机构。
                      this.axios
                        .post("/api/v1/rms/updateShipperResult", map)
                        .then((res) => {
                          console.log(res, "物流修改成功");
                          if (res.data.code == "200") {
                            this.$message.success("保存成功");
                          } else {
                            this.store
                              .dispatch(
                                "system/organizManage/delOrg",
                                map.orgId
                              )
                              .then((res) => {
                                if (res.code === "0") {
                                  this.$message.error("保存失败");
                                  this.$router.go(0);
                                }
                              });
                          }
                        })
                        .catch((err) => {
                          this.store
                            .dispatch("system/organizManage/delOrg", map.orgId)
                            .then((res) => {
                              if (res.code === "0") {
                                this.$message.error("保存失败");
                                this.$router.go(0);
                              }
                            });
                        });
                      // //  更新菜单项
                      let tempItem = null;
                      dgTree(this.orgTree, "children", (item) => {
                        if (item.orgId === this.formItem.orgId) {
                          tempItem = item;
                        }
                      });
                      tempItem = Object.assign(tempItem, this.formItem);
                      this.store.commit(
                        "system/organizManage/tree",
                        this.orgTree
                      );
                    } else {
                      this.$message.error(res.message);
                    }
                  })
                  .catch((err) => {
                    console.log(err);
                    this.addLoading1 = false;
                  });
              })
              .catch((err) => {
                console.log(err);
                this.$message.info("已取消操作");
              });
          } else if (this.operateStatus === "add") {
            //   添加
            this.addLoading2 = true;

            this.formItem.cate = 1;
            this.formItem.companyId = this.companyId;
            //
            let data = JSON.parse(JSON.stringify(this.formItem));
            for (let key in data) {
              if (key === "dutys") {
                delete data[key];
              }
            }
            this.store
              .dispatch("system/organizManage/addOrg", data)
              .then((res) => {
                //
                this.addLoading2 = false;
                //
                if (res.code === "0") {
                  if (
                    this.formItem.dutys !== null &&
                    this.formItem.dutys.length > 0
                  ) {
                    this.addOrgDutys(res.data.orgId, this.formItem.dutys);
                  }
                  console.log(res, "sso添加成功");
                  let pId = null;
                  if (res.data.pId) {
                    pId = res.data.pId;
                  }
                  let map = {
                    orgId: res.data.orgId,
                    depType: res.data.depType,
                    orgName: res.data.orgName,
                    pId: pId,
                    orgCode:res.data.orgCode,
                  };
                  //调用物流系统的资源管理模块的接口，新增组织机构。
                  this.axios
                    .post("/api/v1/rms/addShipperResult", map)
                    .then((res) => {
                      console.log(res, "物流添加成功");
                      if (res.data.code == "200") {
                        this.$message.success("添加成功");
                      } else {
                        this.store
                          .dispatch("system/organizManage/delOrg", map.orgId)
                          .then((res) => {
                            if (res.code === "0") {
                              this.$message.error("新增失败");
                              this.$router.go(0);
                            }
                          });
                      }
                    })
                    .catch((err) => {
                      this.store
                        .dispatch("system/organizManage/delOrg", map.orgId)
                        .then((res) => {
                          if (res.code === "0") {
                            this.$message.error("新增失败");
                            this.$router.go(0);
                          }
                        });
                    });
                  //  更新树
                  this.$refs["orgTree"].append(res.data, this.formItem.pId);
                  this.$refs["orgTree"].setCurrentKey(res.data.id);
                  this.$nextTick(() => {
                    $(".delMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "DELET")
                        ? "inline-block"
                        : "none"
                    );
                    $(".addMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "ADD")
                        ? "inline-block"
                        : "none"
                    );
                    $(".unlockMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "UNLOCK")
                        ? "inline-block"
                        : "none"
                    );
                    $(".lockMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "LOCK")
                        ? "inline-block"
                        : "none"
                    );
                    $(".upMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "EDIT")
                        ? "inline-block"
                        : "none"
                    );
                    $(".downMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "EDIT")
                        ? "inline-block"
                        : "none"
                    );
                    $(".rightMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "EDIT")
                        ? "inline-block"
                        : "none"
                    );
                    $(".leftMenuPr").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "EDIT")
                        ? "inline-block"
                        : "none"
                    );
                    $(".nodeOperate").css(
                      "display",
                      this.checkPrivilege(this.activeMenu + "MENUDELET") ||
                        this.checkPrivilege(this.activeMenu + "MENUADD") ||
                        this.checkPrivilege(this.activeMenu + "EDIT")
                        ? "inline-block"
                        : "none"
                    );
                  });
                  this.handleReset("formItem");
                } else {
                  this.$message({ message: res.message, type: "error" });
                }
              })
              .catch((err) => {
                console.log(err);
                this.addLoading2 = false;
              });
          }
        }
      });
    },
    /**
     * 删除树节点元素
     */
    delTreeNode(node, data) {
      if (data.orgId !== "924126339513061376" &&  data.orgId !== "924126716337721344") {
        if (
          (data.children && data.children.length > 0) ||
          (node.childNodes && node.childNodes.length > 0)
        ) {
          this.$message.error("此节点有子节点，不允许删除");
          return false;
        }
        //
        this.$confirm("确定要删除已选择的记录吗？", "提示", {
          customClass: "org-Manage-changeprimaryforbutton",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.store
              .dispatch("system/organizManage/delOrg", data.orgId)
              .then((res) => {
                if (res.code === "0") {
                  this.axios
                    .post("/api/v1/rms/deleteShipperResult", {
                      orgId: data.orgId,
                    })
                    .then((res) => {
                      console.log(res);
                      this.$message.success("删除成功");
                    });
                  //  更新树
                  this.handleReset("formItem");
                  console.log(node, node);
                  this.$refs["orgTree"].remove(node);
                } else {
                  this.$message.error(res.message);
                }
              });
          })
          .catch(() => {
            this.$message.info("已取消操作");
          });

        this.$nextTick(() => {
          document
            .getElementsByClassName("org-Manage-changeprimaryforbutton")[0]
            .getElementsByClassName("el-message-box__btns")[0]
            .getElementsByTagName("button")[0]
            .classList.add("el-button--primary");
          document
            .getElementsByClassName("org-Manage-changeprimaryforbutton")[0]
            .getElementsByClassName("el-message-box__btns")[0]
            .getElementsByTagName("button")[1]
            .classList.remove("el-button--primary");
        });
      }else{
        this.$message.error("此组织为基础数据不能进行删除");
      }
    },
    // 树形控件过滤数据
    filterOrgTree(value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },
    setCheckedKeys() {
      this.defaultExpand = false;
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[i].expanded =
          this.defaultExpand;
      }
    },
    setCheckedNodes() {
      this.defaultExpand = true; // 展开所有节点
      for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
        this.$refs.orgTree.store._getAllNodes()[i].expanded =
          this.defaultExpand;
      }
    },
    orgShowHidden() {
      this.treeLoading = true;
      let status = this.isAllDataShow ? "0" : "1";
      //console.log(status);
      this.axios
        .get(
          proPath +
            "v1/sysorgs/listtree?companyId=" +
            this.companyId +
            "&status=" +
            status
        )
        .then((res) => {
          if (res.code === "0") {
            this.store.commit("system/organizManage/tree", res.data);
            this.$nextTick(() => {
              $(".delMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "DELET")
                  ? "inline-block"
                  : "none"
              );
              $(".addMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "ADD")
                  ? "inline-block"
                  : "none"
              );
              $(".unlockMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "UNLOCK")
                  ? "inline-block"
                  : "none"
              );
              $(".lockMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "LOCK")
                  ? "inline-block"
                  : "none"
              );
              $(".upMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".downMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".rightMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".leftMenuPr").css(
                "display",
                this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
              $(".nodeOperate").css(
                "display",
                this.checkPrivilege(this.activeMenu + "MENUDELET") ||
                  this.checkPrivilege(this.activeMenu + "MENUADD") ||
                  this.checkPrivilege(this.activeMenu + "EDIT")
                  ? "inline-block"
                  : "none"
              );
            });
            this.treeLoading = false;
          } else {
            this.$message.error(res.message);
            this.treeLoading = false;
          }
        });
      this.getDutyList();
      this.isAllDataShow = !this.isAllDataShow;
    },
    controllNode() {
      this.isSpread = !this.isSpread;
      if (!this.isSpread) {
        this.setCheckedNodes();
      } else {
        this.setCheckedKeys();
      }
    },
    updateMenuStatus(node, data, status) {
      this.$confirm("确定要修改已选择的记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //  修改数据
          this.addLoading1 = true;
          //
          this.store
            .dispatch("system/organizManage/editOrg", {
              id: data.id,
              form: {
                orgName: data.orgName,
                orgId: data.orgId,
                orgCode: data.orgCode,
                companyId: data.companyId,
                status: status === "enable" ? "1" : "0",
              },
            })
            .then((res) => {
              this.addLoading1 = false;
              if (res.code === "0") {
                this.$message.success("修改成功");
                this.isAllDataShow = true;
                this.orgShowHidden();
                // this.$refs["menuTree"].setCurrentKey(res.data.id);
              } else {
                this.$message({ message: res.message, type: "error" });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    getDepType() {
      this.axios
        .get(proPath + "v1/sysdicts/dicttype/DEP_TYPE", {
          params: {
            companyId: this.companyId,
          },
        })
        .then((res) => {
          this.depTypeList = res.data || [];
        });
    },
  },
};
</script>
<style scoped>
.og-st-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: keep-all;
  padding-right: 60px;
}

.organizManage-main {
  position: relative;
  min-width: 1000px;
  /* height: 600px; */
}

.public-function-div {
  font-size: 16px;
  padding: 10px 20px;
  border-bottom: 1px solid #d5d5d5;
  position: relative;
}

.organizManage-mainLeft {
  width: 30%;
  border-right: 1px solid #e0e0e0;
  float: left;
  overflow: hidden;
  height: inherit;
}
._company-select {
  padding: 10px 15px 9px 15px;
  border-bottom: 1px solid #d5d5d5;
}
.el-dropdown {
  font-weight: bold;
  font-size: 14px;
  cursor: pointer;
}
.el-dropdown-menu {
  overflow-y: scroll;
  max-height: 200px;
}
.el-tree {
  overflow-x: hidden !important;
}

.el-icon-back:before {
  content: "\E6EA";
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.organizManage-mainRight {
  width: 70%;
  float: left;
}

.FormorganizManage-main {
  margin: 20px 20px;
}

.filterTree {
  width: 95%;
  margin: 10px 2.5%;
}
.el-tree-node__content .el-icon-plus {
  margin-right: 20px;
}
.postionTop {
  position: absolute;
  top: 0px;
}

.public-function-div .refresh {
  position: absolute;
  right: 15px;
  top: 10px;
}
.public-function-div .refresh2 {
  position: absolute;
  right: 80px;
  top: 10px;
}
.public-function-div ._refresh3 {
  position: absolute;
  right: 80px;
  top: 10px;
}
.orgShowHidden {
  position: absolute;
  right: 170px;
  top: 10px;
}
.delMenuPr,
.upMenuPr,
.downMenuPr,
.rightMenuPr,
.leftMenuPr,
.addMenuPr,
.unlockMenuPr,
.lockMenuPr {
  display: none;
}
.el-tree-node__content:hover {
  background-color: #bbdffb;
}
.el-tree-node:focus .el-tree-node__content {
  background-color: #bbdffb;
}
.el-tree .is-current .el-tree-node__content {
  background-color: #bbdffb;
}
.is-current .el-tree-node__children .el-tree-node .el-tree-node__content {
  background-color: #fff;
}
</style>
