<template>
  <div class="box pagePadding MenuOperator">
    <div class="MenuOperator-main" v-if="powers.some((i) => i == '001')">
      <el-row class="MenuOperator-search clear" style="padding: 10px 0">
        <!-- <el-col :span="24" style="width: 90px; float: right">
          <el-button
            type="success"
            :size="searchSize"
            style="float: right"
            @click="btnVisible = true"
          >
            添加按钮
          </el-button>
        </el-col> -->

        <el-col :span="24" style="width: 66px; float: right">
          <el-button
            v-if="powers.some((i) => i == '003')"
            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-col>
      </el-row>
      <div style="padding: 50px 0 0 0">
        <el-table
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          v-loading="loading"
          border
          :default-expand-all="false"
          size="mini"
          :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="menu_name" label="菜单名称" width="180" />
          <el-table-column prop="name" label="图标" width="50">
            <template slot-scope="scope"> <i :class="scope.row.menu_img" /></template
          ></el-table-column>
          <el-table-column prop="menu_route" label="path" width="180" />
          <el-table-column prop="weight" label="权重" width="80" />
          <el-table-column prop="address" label="类型" width="100">
            <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="100">
            <template slot-scope="scope">
              <el-tag
                :size="tablebtnSize"
                :type="Number(scope.row.status) == 0 ? 'warning' : ''"
                v-text="
                  (
                    statusOptions.find((item) => item.id == Number(scope.row.status)) ||
                    {}
                  ).label || '--'
                "
              ></el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="menu_url" label="文件路径" />
          <el-table-column prop="address" label="操作" width="180">
            <template slot-scope="scope">
              <el-tooltip
                v-if="powers.some((i) => i == '007')"
                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
                v-if="powers.some((i) => i == '005')"
                effect="dark"
                content="修改"
                placement="top"
              >
                <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="powers.some((i) => i == '004') && scope.row.status + '' === '1'"
                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="powers.some((i) => i == '004') && scope.row.status + '' === '0'"
                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="powers.some((i) => i == '003') && Number(scope.row.pid) === 0"
                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, {})"
                ></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 v-else>
      <no-auth></no-auth>
    </div>

    <ButtonModal :visible.sync="btnVisible" />
  </div>
</template>

<script>
import mixinPage from "@/mixins/elPaginationHandle";
import asyncRequest from "@/apis/service/system/menu";
import addEdit from "@/views/system/menuOperator/addEdit";
import ButtonModal from "./button-modal.vue"
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";

export default {
  name: "MenuOperator",
  components: {
    addEdit,
    ButtonModal
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((item) => item.menu_route == "menuOperator") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      btnVisible:false,
      // 状态
      statusOptions: [
        { id: 0, label: "禁用" },
        { id: 1, label: "启用" },
      ],
      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: {
    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(id, parentIds, level) {
      if (level < 3) {
        await this.searchList();
      } else {
        this.getchildList(parentIds);
      }
    },
    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);
          }

          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 deleteItem(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>
