<template>
  <div class="box pagePadding MenuOperator">
    <div
      class="MenuOperator-main"
      v-if=" powers.some((i) => i == '001')"
    >
      <el-row class="MenuOperator-search">
        <el-col :span="24" style="padding: 5px">
          <el-col :span="3" style="width: 195px; float: right">
            <el-button
              type="primary"
              :size="searchSize"
              style="float: right; margin-left: 5px"
              @click="searchList"
            >
              刷新
            </el-button>
            <el-button
              v-if="powers.some((i) => i == '003')"
              type="success"
              :size="searchSize"
              style="float: right"
              @click="addEditFn(0, '0', 1, false, true, {})"
            >
              添加
            </el-button>
          </el-col>
        </el-col>
      </el-row>

      <el-row  class="MenuOperator-show">
        <el-col :span="24" v-loading="loading">
          <shy-tree
            :value="tableData"
            :level="1"
            @addEdit="addEditFn"
            @openChildren="openChildren"
            @remove="remove"
            @deleteMenu="deleteMenu"
          />
        </el-col>
      </el-row>

      <add-edit
        :id="modelId"
        :show-model="showModel"
        :level="level"
        :parent-ids="parentIds"
        :is-add="isAdd"
        :form-data="formData"
        :type="parmValue.type"
        :is-detail="isDetail"
        @refresh="submitRefresh"
        @cancel="showModel = false"
      />
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>

<script>
import mixinPage from "@/mixins/elPaginationHandle";
import asyncRequest from "@/apis/service/system/menu";
import addEdit from "@/views/system/menuOperator/addEdit";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
export default {
  name: "MenuOperator",
  components: {
    addEdit,
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "menuOperator"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      loading: true,
      showModel: false,
      showInterface: false,
      isDetail: false,
      isAdd: true,
      level: 1,
      modelId: 0,
      formData: {},
      parentIds: "",
      parmValue: {
        parentId: 0, // 父级Id
        code: "", // 编码
        status: "", // 状态（1启用 2禁用）
        type: 1, // 类型（1.运营菜单 2.物业菜单）
        menuCategory: "", // 菜单类别（1.导航菜单 2.按钮）
        current: 1, // 页码
        size: 15, // 每页显示条数
      },
      tableData: [],
    };
  },
  mounted() {
    this.searchList();
  },
  methods: {
    addEditFn(id, parentIds, level, isDetail, isAdd, formData) {
      this.showModel = true;
      this.modelId = id;
      this.level = level;
      this.parentIds = parentIds;
      this.isDetail = isDetail;
      this.isAdd = isAdd;
      this.formData = formData;
    },
    async submitRefresh(id, parentIds, level) {
      if (level < 3) {
        await this.searchList();
      } else {
        this.getchildList(parentIds);
      }
    },
    async remove(id, parentIds, level, status) {
      await this.$confirm(`确定要${status === "0" ? "启用" : "禁用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
            status: status === "1" ? "0" : "1",
          };
          let res = {};
          if (level === 3) {
            res = await asyncRequest.actionstatus(model);
          } else {
            res = await asyncRequest.menustatus(model);
          }

          if (res && res.code === 0) {
            this.$notify.success({
              title: "修改成功！",
              message: "",
            });
            if (level === 3) {
              this.getchildList(parentIds);
            } else {
              await this.searchList();
            }
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    async deleteMenu(id, parentIds, level, status) {
      await this.$confirm(`确定要删除？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: id,
          };
          let res = {};
          if (level === 3) {
            res = await asyncRequest.actiondel(model);
          } else {
            res = await asyncRequest.menudel(model);
          }

          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功！",
              message: "",
            });
            if (level === 3) {
              this.getchildList(parentIds);
            } else {
              await this.searchList();
            }
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    openChildren(id, parentIds, level, isOpen) {
      if (isOpen) {
        if (level === 1) {
          this.tableData = this.tableData.map((v) => {
            if (v.id === id) {
              v.child = [];
            }
            return v;
          });
        } else {
          this.tableData = this.tableData.map((v) => {
            if (v.id === parentIds) {
              v.child = v.child.map((val) => {
                if (val.id === id) val.child = [];
                return val;
              });
            }
            return v;
          });
        }
      } else {
        if (level === 1) {
          this.concatData(id, "0", level);
        } else {
          this.getchildList(id);
        }
      }
    },
    async getchildList(id) {
      this.loading = true;
      const res = await asyncRequest.actionList({ id: id });
      let tableData = [];
      if (res && res.code === 0 && res.data) {
        tableData = res.data;
        // tableData = tableData.map((val) => {
        //   let index = btnList.findIndex((e) => val.action_code === e.code);
        //   if (index !== -1) {
        //     val.menu_name = btnList[index].name;
        //   }
        //   return val;
        // });
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      let arr = JSON.parse(JSON.stringify(this.tableData));
      arr = arr.map((val, index) => {
        if (val && val.child && val.child.length > 0) {
          val.child.forEach((el, eli) => {
            if (id === el.id) {
              el.child = tableData;
            }
            return el;
          });
        }
        return val;
      });
      this.tableData = arr;
      this.loading = false;
    },
    async concatData(id, parentIds, level) {
      this.loading = true;
      const res = await asyncRequest.list({});
      let tableData = [];
      if (res && res.code === 0 && res.data) {
        tableData = res.data;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      let arr = JSON.parse(JSON.stringify(this.tableData));
      arr = arr.map((val, index) => {
        if (level === 1 ? id : parentIds === val.id) {
          val.child = tableData[index].child;
        }
        return val;
      });

      this.tableData = arr;
      this.loading = false;
    },
    async searchList() {
      this.loading = true;
      const res = await asyncRequest.list({});
      this.tableData = [];
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
      }
      this.loading = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.MenuOperator {
  position: relative;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
 
  .MenuOperator-main {
    position: relative;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    .MenuOperator-search{
      position: absolute;
      top:0;
      left:0;
      width: 100%;
      z-index: 2;
      background: #fff;
    }
      
    .MenuOperator-show{
      position: relative;
      height: 100%;
      padding: 40px 0 0 0;
      overflow-y: scroll;
    }
  }
}
</style>