<!--
* @name: 菜单管理
* @date: 2022-09-09
-->
<template>
  <div style="display: flex; height: 100%">
    <base-layout
      title="菜单管理"
      :operateButtonSwitch="false"
      style="width: 260px"
    >
      <div slot="main" flex style="height: 100%">
        <div
          style="
            width: 100%;
            border-right: 1px solid #dfe6ec;
            height: 100%;
            overflow: auto;
          "
        >
          <base-tree
            ref="baseTree"
            :isCenter="false"
            :isSaveBtn="false"
            :Allshow="false"
            :expandAll="true"
            :showCheckbox="false"
            :menuData="menuData"
            @handleNodeClick="formClick"
          >
          </base-tree>
        </div>
      </div>
    </base-layout>
    <base-layout
      title="菜单树编辑区"
      :defaultButtonSwitch="false"
      :buttonList="buttonList"
      @onFuncBtn="getFuncBtn"
      style="flex: 1"
    >
      <div slot="main" style="padding: 0 12px; height: 300px">
        <base-form
          ref="customForm"
          :formRow="formRow"
          :isFunBtn="isFunBtn"
          @elDialogClick="elDialogClick"
          :formdata="ruleForm"
          @onSubmit="getSubmit"
          @resetForm="handleReset"
        >
          <template v-slot:menuIcon="row">
            <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                ref="upload"
                :show-file-list="false"
                :on-progress="handleProgress"
                :before-upload="beforeUpload"
                :on-success="handleAvatarSuccess"
                :limit="1"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </template>
        </base-form>
      </div>
    </base-layout>
    <base-organization
      ref="baseOrganization"
      :menuData="menuData"
      @handleConfirmClick="handleConfirmClick"
    >
    </base-organization>
  </div>
</template>

<script>
import router from "@/router";
import baseLayout from "@/components/base/baseNewLayout";
import baseForm from "@/components/base/baseNewForm/index.vue";
import baseTree from "@/components/base/BaseMenuTree/index.vue";
import baseTreeclick from "@/components/base/baseTreeClick/index.vue";
import baseDialog from "@/components/base/BaseNewDialog";
import baseOrganization from "./baseOrganization";
import configData from "./configData";
import { GetOrganTree } from "@/api/apis/organization";
import {
  GetMenuTree,
  GetBillData,
  MenuSaveData,
  MenuDelData,
} from "@/api/apis/menuManage";
import { authApi } from "@/api/apis/auth";
import request from "@/utils/request";

export default {
  components: {
    baseLayout,
    baseTree,
    baseForm,
    baseTreeclick,
    baseDialog,
    baseOrganization,
  },
  data() {
    return {
      // treeHight: '350',
      dialogVisible: false,
      dialogTitle: "选择上级菜单",
      leftTitle: "菜单树",
      rightTitle: "菜单及上级菜单",
      mainColor: "#f8f8f8 ",
      buttonList: [
        {
          menuName: "新增根节点",
          icon: "el-icon-plus",
        },
        {
          menuName: "新增子节点",
          icon: "el-icon-plus",
        },
        {
          menuName: "删除节点",
          icon: "el-icon-delete",
          type: "danger",
        },
      ],
      delId: "",
      menuData: [],
      ruleForm: {},
      rules: {},
      formRow: configData.formRow,
      isFunBtn: true,
      clickTree: {}, //当前点击树
      imageUrl: "",
    };
  },
  mounted() {
    // this.$refs.baseTree.getMenuList()
    this.initPage();
  },
  methods: {
    // 文件上传相关时间
    handleProgress(file, fileList) {
      this.handleAvatarSuccess({}, fileList);
    },
    handlePreview(file) {},
    async handleAvatarSuccess(res, file) {
      file.raw.type;
      if (file.raw.type.indexOf("image/") == -1) {
        return false;
      } else if (file.raw.size >= 20000000) {
        return false;
      }
      this.$refs.upload.clearFiles(); //清理文件上传状态

      this.imageUrl = URL.createObjectURL(file.raw);
      let formData = new FormData();
      formData.append("file", file.raw);
      formData.append("fileFlag", true);
      formData.append("businessType", "application");
      return request({
        url: "/kangarooDataCenterV3/entranceController/fileUpload",
        method: "post",
        data: formData,
      }).then((resData) => {
        if (resData.status && resData.status === "200") {
          this.$vmNews("上传成功", "success");
          this.$refs.customForm.getField("menuIcon", resData.attribute.id);
        }
        return true;
      });
    },
    async beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$message({
          type: "warning",
          message: "只能上传jpg/png文件",
        });
        return false;
      } else {
        if (file.size >= 20000000) {
          this.$message({
            type: "warning",
            message: "文件大小不超过20MB",
          });
          return false;
        }
      }
    },
    //页面初始化
    initPage() {
      // this.delId = ""
      this.getMenuData();
    },
    // 获得树状图
    async getMenuData() {
      let res = await authApi(
        "sysMenuConfigService",
        "",
        "queryEntityTree",
        "",
        {}
      );
      if (res.status == 200) {
        let arr = res.attribute[0];
        this.menuData = res.attribute;
      }
    },
    // 操作按钮事件
    getFuncBtn(btnEven) {
      if (btnEven.menuName == "新增根节点") {
        let newRuleForm = {
          parentMenuName: "",
          parentMenuId: 0,
        };
        this.$nextTick(() => {
          this.$refs.customForm.resetForm("ruleForm");
          this.imageUrl = "";
          this.$refs.customForm.choiceAssignment(newRuleForm);
        });
      }
      if (btnEven.menuName == "新增子节点") {
        if (!this.delId) {
          this.$vmNews("请选择处理的信息");
          return;
        }
        let newRuleForm = {
          parentMenuName: this.ruleForm.menuName,
          parentMenuId: this.ruleForm.id,
        };
        this.$nextTick(() => {
          this.$refs.customForm.resetForm("ruleForm");
          this.imageUrl = "";
          this.$refs.customForm.choiceAssignment(newRuleForm);
        });
      }
      if (btnEven.menuName == "删除节点") {
        if (this.clickTree.formId) {
          this.$vmNews("系统自动生成的菜单不允许删除");
          return;
        }
        this.$confirm("确认删除该菜单吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.menuDel();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    async menuDel() {
      let params = {
        id: this.delId,
      };
      let res = await authApi(
        "sysMenuConfigService",
        "",
        "deleteEntity",
        "",
        params
      );
      if (res.status == 200) {
        this.$vmNews("删除成功", "success");
        this.ruleForm = {};
        this.imageUrl = "";
        this.getMenuData();
        this.$refs.customForm.choiceAssignment({});
      }
    },
    // 获取详情
    async getDetail(id) {
      let params = {
        id: id,
      };
      let res = await authApi(
        "sysMenuConfigService",
        "",
        "getEntity",
        "",
        params
      );
      if (res.status == 200) {
        console.log(res, "res");
        this.ruleForm = res.attribute;
        this.$nextTick(() => {
        this.imageUrl = ""
          this.$refs.customForm.choiceAssignment(res.attribute);
          let menuIcon = res.attribute.menuIcon ? res.attribute.menuIcon : "";
          if (menuIcon && !menuIcon.includes("icon")) {
            this.getLogoUrl(menuIcon);
          }
        });
      }
    },
    //下载logo
    getLogoUrl(id) {
      return request({
        url:
          "/kangarooDataCenterV3/entranceController/fileDownloadNew?id=" + id,
        method: "get",
        responseType: "arraybuffer",
      }).then((res) => {
        this.imageUrl =
          "data:image/png/jpg;base64," +
          btoa(
            new Uint8Array(res).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
      });
    },
    async getSubmit(data) {
      let params = {
        ...data,
      };
      let res;
      if (params.id) {
        res = await authApi(
          "sysMenuConfigService",
          "",
          "updateEntity",
          "",
          params
        );
      } else {
        res = await authApi(
          "sysMenuConfigService",
          "",
          "saveEntity",
          "",
          params
        );
      }
      if (res.status == 200) {
        this.$vmNews("保存成功", "success");
        this.ruleForm = {};
        this.imageUrl = "";
        this.getMenuData();
        this.$refs.customForm.choiceAssignment({});
        this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
          // 根据roles权限生成可访问的路由表
          for (let i = 0, length = accessRoutes.length; i < length; i += 1) {
            const element = accessRoutes[i];
            router.addRoutes(accessRoutes); // 动态添加可访问路由表
          }
          localStorage.setItem("routeList", JSON.stringify(accessRoutes));
        });
      }
    },
    //父节点点击事件
    elDialogClick(row, index, indexRow) {
      this.$refs.baseOrganization.dialogVisible = true;
    },
    handleConfirmClick(val) {
      this.ruleForm.parentMenuName = val.label;
      this.ruleForm.parentMenuId = val.id;
      this.$refs.customForm.incomingParameters(this.ruleForm);
      this.$refs.baseOrganization.dialogVisible = false;
    },
    formClick(data) {
      this.delId = data.id;
      this.clickTree = data;
      this.getDetail(data.id);
    },
    handleReset() {
      this.imageUrl = "";
    },
  },
};
</script>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
::v-deep .avatar {
  width: 50px;
  height: 50px;
  display: block;
}
.organizationBody {
  display: flex;
  justify-content: space-evenly;
  background-color: #f2f3f4;
  padding: 10px;
  max-height: 400px;
  overflow: auto;
}

.container {
  height: auto;
}

/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

/deep/ input[type="number"] {
  -moz-appearance: textfield !important;
}
</style>
