<template>
  <div class="organization-manage">
    <div class="part-box part-box-pad box-justify">
      <div></div>
      <div>
        <el-button
          v-if="checkPrivilege('button', 'export')"
          type="primary"
          icon="el-icon-download"
          :loading="loading"
          @click="toExportOrg"
          >导出</el-button
        >
        <el-button
          v-if="checkPrivilege('button', 'import')"
          type="success"
          icon="el-icon-upload2"
          @click="toImport"
          >导入</el-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>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入组织架构"
      :upload-url="uploadUrl"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('org')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
  </div>
</template>

<script>
import {
  organizationList,
  deleteOrganization,
  exportOrganization,
} from "../api";
import ModifyOrganization from "../components/ModifyOrganization";
import ImportFile from "../../../components/ImportFile.vue";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "organization-manage",
  components: { ModifyOrganization, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      orgs: [],
      curOrg: {},
      orgTypes: [{ type: "PRINTING_HOUSE", name: "印刷室" }],
      defaultProps: {
        label: "name",
      },
      loading: false,
      // import
      uploadUrl: "/api/admin/sys/org/import",
      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(() => {});
    },
    async toExportOrg() {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return exportOrganization();
      }, "").catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功！");
      this.getList();
    },
  },
};
</script>
