<template>
  <div class="organization-manage">
    <div class="box-justify mb-2">
      <div></div>
      <div>
        <el-button
          type="success"
          icon="el-icon-download"
          v-if="checkPrivilege('button', 'import')"
          ><a :href="downloadUrl" :download="dfilename">模板下载</a></el-button
        >
        <upload-button
          v-if="checkPrivilege('button', 'import')"
          btn-icon="el-icon-circle-plus-outline"
          btn-content="导入组织架构"
          btn-type="success"
          :upload-url="uploadUrl"
          :format="['xls', 'xlsx']"
          accept=".xls,.xlsx"
          @valid-error="validError"
          @upload-success="uploadSuccess"
        >
        </upload-button>
      </div>
    </div>
    <div class="part-box part-box-pad part-box-border">
      <div class="org-tree-head">
        <div>机构名称</div>
        <div>操作</div>
        <div>机构类型</div>
      </div>
      <el-tree
        :data="orgs"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :props="defaultProps"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <div class="org-edit">
            <div class="org-type">
              {{ data.type | orgTypeFilter }}
            </div>
            <div class="org-actions" v-if="data.type === 'SCHOOL'">
              <el-button
                v-if="checkPrivilege('button', 'Add')"
                class="btn-primary"
                type="text"
                @click="() => toAdd(data)"
                >子部门</el-button
              >
            </div>
            <div class="org-actions" v-else>
              <el-button
                v-if="
                  data.type !== 'PRINTING_HOUSE' &&
                    checkPrivilege('link', 'Add')
                "
                class="btn-primary"
                type="text"
                @click="() => toAdd(data)"
                >子部门</el-button
              >
              <el-button
                v-if="checkPrivilege('link', 'Edit')"
                class="btn-primary"
                type="text"
                @click="() => edit(node, data)"
                >修改</el-button
              >
              <el-button
                v-if="checkPrivilege('link', 'Delete')"
                class="btn-danger"
                type="text"
                @click="() => remove(node, data)"
                >删除</el-button
              >
            </div>
          </div>
        </span>
      </el-tree>
    </div>

    <!-- ModifyOrganization -->
    <modify-organization
      ref="ModifyOrganization"
      :instance="curOrg"
      :org-types="orgTypes"
      @confirm="getList"
    ></modify-organization>
  </div>
</template>

<script>
import { organizationList, deleteOrganization } from "../api";
import ModifyOrganization from "../components/ModifyOrganization";
import UploadButton from "../../../components/UploadButton";

export default {
  name: "organization-manage",
  components: { ModifyOrganization, UploadButton },
  data() {
    return {
      orgs: [],
      curOrg: {},
      orgTypes: [{ type: "PRINTING_HOUSE", name: "印刷室" }],
      defaultProps: {
        label: "name"
      },
      // import
      uploadUrl: "/api/admin/sys/org/import",
      downloadUrl: "/temps/orgTemplate.xlsx",
      dfilename: "组织架构导入模板.xlsx"
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "LIST")) return;
      const orgs = await organizationList();
      this.orgs = orgs || [];
      if (this.orgs.length) {
        this.orgs[0].children.sort((a, b) => {
          if (a.type === "PRINTING_HOUSE") return 1;
          if (b.type === "PRINTING_HOUSE") return -1;

          return 0;
        });
      }
    },
    toAdd(data) {
      if (data.type === "PRINTING_HOUSE") return;

      this.orgTypes =
        data.type === "SCHOOL"
          ? [{ type: "PRINTING_HOUSE", name: "印刷室" }]
          : [];
      this.curOrg = { parentId: data.id, parentName: data.name };
      this.$refs.ModifyOrganization.open();
    },
    edit(node, data) {
      console.log(data);
      if (data.type !== "PRINTING_HOUSE") {
        this.orgTypes = [];
      } else {
        this.orgTypes = [{ type: "PRINTING_HOUSE", name: "印刷室" }];
      }

      if (
        data.type === "PRINTING_HOUSE" ||
        (data.type !== "PRINTING_HOUSE" &&
          node.parent.data.type === "SCHOOL" &&
          !data.children.length)
      ) {
        this.orgTypes = [{ type: "PRINTING_HOUSE", name: "印刷室" }];
      } else {
        this.orgTypes = [];
      }

      this.curOrg = {
        ...data,
        parentName: data.parentId
          ? node.parent.data.name
          : this.$ls.get("schoolName")
      };
      this.$refs.ModifyOrganization.open();
    },
    remove(node, data) {
      this.$confirm(`确定要删除【${data.name}】吗？`, "提示", {
        type: "warning"
      })
        .then(async () => {
          await deleteOrganization(data.id);

          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);

          this.$message.success("删除成功！");
        })
        .catch(() => {});
    },
    // import
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.getList();
    }
  }
};
</script>
