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

      <div style="padding: 50px 0 0 0">
        <el-table
          border
          ref="table"
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          v-loading="loading"
          :default-expand-all="false"
          size="mini"
          lazy
          :load="load"
          :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
        >
          <el-table-column
            prop="menu_name"
            label="菜单名称"
            width="180"
            show-overflow-tooltip
          />
          <el-table-column prop="name" label="图标" width="50" show-overflow-tooltip>
            <template slot-scope="scope"> <i :class="scope.row.menu_img" /></template
          ></el-table-column>
          <el-table-column
            prop="menu_route"
            label="path"
            width="180"
            show-overflow-tooltip
          />
          <el-table-column prop="weight" label="权重" width="80" show-overflow-tooltip />
          <el-table-column prop="address" label="类型" width="80" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag
                :size="tablebtnSize"
                :type="Number(scope.row.pid) == 0 ? 'success' : ''"
                v-text="Number(scope.row.pid) == 0 ? '菜单' : '页面'"
              ></el-tag> </template
          ></el-table-column>
          <el-table-column prop="status" label="状态" width="80" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag
                :size="tablebtnSize"
                :type="Number(scope.row.status) == 0 ? 'warning' : ''"
                v-text="
                  (
                    statusList.find(
                      (item) => Number(item.code) == Number(scope.row.status)
                    ) || {}
                  ).name || '--'
                "
              ></el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="menu_url" label="文件路径" show-overflow-tooltip />
          <el-table-column prop="address" label="操作" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="详情" placement="top">
                <i
                  class="el-icon-view tb-icon"
                  size="mini"
                  @click="
                    openModal(
                      scope.row.id,
                      scope.row.pid,
                      Number(scope.row.pid) === 0 ? 1 : 2,
                      true,
                      false,
                      scope.row
                    )
                  "
                ></i>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="修改"
                placement="top"
                v-if="powers.some((i) => i == '005')"
              >
                <i
                  class="el-icon-edit tb-icon"
                  size="mini"
                  @click="
                    openModal(
                      scope.row.id,
                      scope.row.pid,
                      Number(scope.row.pid) === 0 ? 1 : 2,
                      false,
                      false,
                      scope.row
                    )
                  "
                ></i>
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.status + '' === '1' && powers.some((i) => i == '004')"
                effect="dark"
                content="禁用"
                placement="top"
              >
                <i
                  class="el-icon-video-pause tb-icon"
                  size="mini"
                  @click="
                    changeStatus(
                      scope.row.id,
                      scope.row.pid,
                      scope.row.level,
                      scope.row.status
                    )
                  "
                ></i>
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.status + '' === '0' && powers.some((i) => i == '003')"
                effect="dark"
                content="启用"
                placement="top"
              >
                <i
                  class="el-icon-video-play tb-icon"
                  size="mini"
                  @click="
                    changeStatus(
                      scope.row.id,
                      scope.row.pid,
                      scope.row.level,
                      scope.row.status
                    )
                  "
                ></i>
              </el-tooltip>
              <el-tooltip
                v-if="powers.some((i) => i == '006')"
                effect="dark"
                content="删除"
                placement="top"
              >
                <i
                  class="el-icon-delete tb-icon"
                  size="mini"
                  @click="
                    deleteItem(
                      scope.row.id,
                      scope.row.pid,
                      scope.row.level,
                      scope.row.status
                    )
                  "
                ></i>
              </el-tooltip>
              <el-tooltip
                v-if="Number(scope.row.pid) === 0 && powers.some((i) => i == '002')"
                effect="dark"
                content="添加"
                placement="top"
              >
                <i
                  class="el-icon-circle-plus-outline tb-icon"
                  size="mini"
                  @click="openModal(0, scope.row.id, 2, false, true, {}, scope.row)"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <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>
</template>

<script>
import mixinPage from "@/mixins/elPaginationHandle";
import asyncRequest from "@/apis/service/system/setMenu";
import addEdit from "@/views/system/setMenu/addEdit";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import { statusList } from "@/assets/js/statusList";
export default {
  name: "setMenu",
  components: {
    addEdit,
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((item) => item.menu_route == "setMenu") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      // 状态
      refreshId: 0,
      loadMap: new Map(),
      statusList,
      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: {
    async load(row, treeNode, resolve) {
      // console.log(row)
      const { id: pid } = row;
      this.loadMap.set(pid, { row, treeNode, resolve });
      const { code, data } = await asyncRequest.list({ pid });
      if (code === 1) resolve(data.map((item) => ({ ...item, hasChildren: false })));
    },
    reloadTree(pid) {
      pid = pid ? parseInt(pid) : 0;
      if (pid === 0) return null;
      const result = this.loadMap.get(pid);
      if (!result) return null;
      this.$refs.table.store.states.lazyTreeNodeMap[pid] = [];
      const { row, treeNode, resolve } = result;
      if (row.id === 0) {
        row.pid = row.id;
        row.id = 0;
      }
      this.load(row, treeNode, resolve);
    },
    openModal(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(_1, _2, level, isAdd, parentIds) {
      if (level === 0 && isAdd) {
        this.reloadTree(parentIds);
      } else if (level === 2) {
        this.reloadTree(parentIds);
      } else {
        this.searchList();
      }
    },
    async changeStatus(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);
          }
          const { code } = res;
          if (code === 1) {
            this.$notify.success({
              title: "修改成功！",
              message: "",
            });

            if (level === 0 && parentIds !== 0) {
              this.reloadTree(parentIds);
            } else {
              await this.searchList();
            }
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    async deleteItem(id, parentIds, level, status) {
      console.log(level, parentIds);
      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);
          }
          const { code } = res;
          if (code === 1) {
            this.$notify.success({
              title: "删除成功！",
              message: "",
            });

            if (level === 0 && parentIds !== 0) {
              this.reloadTree(parentIds);
            } else {
              await this.searchList();
            }
          }
        })
        .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 {code,data} = await asyncRequest.actionList({ menu_id: id });
      let tableData = [];
      if (code === 1 ) {
        tableData = rdata;
      }
      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 {code,data} = await asyncRequest.list({});
      let tableData = [];
      if (code === 1 ) {
        tableData = data;
      } 
      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 { code, data } = await asyncRequest.list({});
      this.tableData = [];
      if (code === 1) {
        this.tableData = data.map((item) => ({
          hasChildren: true,
          ...item,
        }));
      } 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>
