<template>
  <div class="setBtn">
    <div class="processPermission_show_box" v-if="powers.some((i) => i == '001')">
      <ul class="role-list fl" v-loading="menuLoading">
        <p class="role-list__title">菜单列表</p>
        <p
          v-if="menuTableData.length == 0"
          style="line-height: 60px; text-align: center; color: #909399"
        >
          暂无数据
        </p>

        <el-tree
          :data="menuTableData"
          accordion
          :props="defaultProps"
          :current-node-key="keyId"
          @node-click="handleNodeClick"
        ></el-tree>
      </ul>
      <div class="rule-view fr">
        <ex-table
          v-loading="loading"
          v-if="powers.some((i) => i == '001')"
          :table="table"
          :data="tableData"
          :columns="columns"
          :page="pageInfo"
          :size="size"
          @page-curr-change="handlePageChange"
          @page-size-change="handleSizeChange"
          @screen-reset="
            pageInfo.curr = 1;
            searchList();
          "
          @screen-submit="
            pageInfo.curr = 1;
            searchList();
          "
        >
          <template #table-header="{}">
            <div style="width: 100%; padding: 0 0 0 80px">
              <el-row>
                <el-col :span="24">
                  <el-col :span="3" style="width: 66px; float: right">
                    <el-button
                      type="primary"
                      :size="searchSize"
                      style="float: right"
                      @click="searchList"
                    >
                      刷新
                    </el-button>
                  </el-col>
                  <el-col
                    :span="3"
                    style="width: 66px; float: right"
                    v-if="powers.some((i) => i == '003')"
                  >
                    <el-button
                      :size="searchSize"
                      type="success"
                      style="float: right"
                      @click="openModal('add', {})"
                    >
                      添加
                    </el-button>
                  </el-col>
                </el-col>
              </el-row>
            </div>
          </template>
          <template #status="{ scope }">
            <el-tag
              :size="tablebtnSize"
              :type="scope.row.status == '0' ? 'warning' : ''"
              v-text="
                (statusOptions.find((item) => item.id == scope.row.status) || {}).label ||
                '--'
              "
            ></el-tag>
          </template>

          <template #operation="{ scope }">
            <el-tooltip
              v-if="powers.some((i) => i == '007')"
              effect="dark"
              content="详情"
              placement="top"
            >
              <i class="el-icon-view tb-icon" @click="openModal('view', 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" @click="openModal('edit', 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"
                @click="changeStatus(scope.row.id, 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"
                @click="changeStatus(scope.row.id, 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" @click="deleteItem(scope.row.id)"></i>
            </el-tooltip>
          </template>
        </ex-table>
      </div>
      <add-edit
        :show-model="showModel"
        :form-data="formData"
        :type="modelType"
        @refresh="searchList"
        @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/setBtn/addEdit";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";

export default {
  name: "setBtn",
  components: {
    addEdit,
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((item) => item.menu_route == "setBtn") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      defaultProps: {
        children: "child",
        label: "menu_name",
      },
      keyId: "",

      // 状态
      statusOptions: [
        { id: 0, label: "禁用" },
        { id: 1, label: "启用" },
      ],
      menuLoading: true,
      loading: true,
      showModel: false,
      showInterface: false,
      isDetail: false,
      isAdd: true,
      level: 1,
      modelType: 0,
      formData: {},
      parentIds: "",
      parmValue: {
        parentId: 0, // 父级Id
        code: "", // 编码
        status: "", // 状态（1启用 2禁用）
        type: 1, // 类型（1.运营菜单 2.物业菜单）
        menuCategory: "", // 菜单类别（1.导航菜单 2.按钮）
        current: 1, // 页码
        size: 15, // 每页显示条数
      },
      menuTableData: [],
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: [
        {
          prop: "id",
          label: "ID",
        },
        {
          prop: "action_name",
          label: "按钮名称",
        },
        {
          prop: "action_code",
          label: "按钮编号",
        },

        {
          prop: "status",
          label: "状态",
          _slot_: "status",
        },

        {
          prop: "addtime",
          label: "创建时间",
        },

        {
          prop: "",
          label: "操作",
          fixed: "right",
          width: "160px",
          _slot_: "operation",
        },
      ],
    };
  },
  mounted() {
    this.getMenuList();
  },
  methods: {
    async getMenuList() {
      this.menuLoading = true;
      const { code, data } = await asyncRequest.list({});
      this.menuTableData = [];
      if (code === 0) {
        this.menuTableData = data;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.menuTableData = [];
      }
      this.menuLoading = false;
      if (this.menuTableData.length > 0) {
        this.handleNodeClick(this.menuTableData[0], 1);
      } else {
        this.tableData = [];
        this.loading = false;
      }
    },
    async handleNodeClick(data, type) {
      const { id, pid, child } = data;
      if (Number(pid) !== 0) {
        this.keyId = id;
        await this.searchList();
      } else {
        if (type === 1 && child.length > 0) {
          this.keyId = child[0].id;
          await this.searchList();
        }
      }
    },

    openModal(type, formData) {
      if (type == "add") {
        this.formData = { menuid: this.keyId };
      } else {
        this.formData = formData;
      }
      this.modelType = type;
      this.showModel = true;
    },

    async changeStatus(id, status) {
      await this.$confirm(`确定要${status + "" === "0" ? "启用" : "禁用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            id: String(id ?? ""),
            status: String(status ?? "") === "1" ? "0" : "1",
          };
          const { code, message } = await asyncRequest.actionstatus(model);

          if (code === 0) {
            this.$notify.success({
              title: "修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(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 = await asyncRequest.actiondel(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    async searchList() {
      this.loading = true;
      const res = await asyncRequest.actionList({ id: this.keyId });
      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>
@import "~@/styles/mixin.scss";
.setBtn {
  position: relative;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
  .processPermission_show_box {
    // position: relative;
    // height: calc(100% - 50px);
    // min-height: calc(100% - 50px);

    display: relative;
    width: 100%;
    height: calc(100vh - 50px);
    overflow: hidden;
    text-align: left;
    //左侧
    .role-list {
      height: 100%;
      overflow-y: auto;
      width: 300px;
      padding: 8px 16px;
      min-height: 100%;
      flex-shrink: 0;
      border-right: 2px solid #dfe6ec;
      @include scrollBar();
      &::after {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
        width: 2px;
        background-color: #e4e7ed;
        z-index: 1;
      }
      .role-list__title {
        color: #b4b6c0;
        line-height: 32px;
      }
      .role-list__item {
        position: relative;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        height: 32px;
        line-height: 32px;
        padding-left: 8px;
        color: rgb(48, 49, 51);
        cursor: pointer;
        i {
          position: absolute;
          right: 0;
          line-height: 32px;
        }
      }
      .role-list__item.active {
        color: #6954f0;
        background: #f7f7f7;
      }
    }
    //右侧
    .rule-view {
      height: 100%;
      //calc(100% - 50px);
      width: calc(100% - 300px);
      overflow-y: auto;
      padding: 0 16px;
      @include scrollBar();
      .rule-list {
        border-right: 1px solid #dfe6ec;
        .title {
          padding: 18px 18px 12px 18px;
          border-bottom: 1px dashed #dfe6ec;
          font-size: 15px;
          color: #000;
        }
        .main {
          padding: 18px 18px 12px 18px;
          border-bottom: 1px solid #dfe6ec;
        }
        .main-title {
          width: 80px;
        }
        .main-item {
          width: calc(100% - 80px);
        }
      }
    }
    .rule-bottom {
      padding: 10px 18px 8px 0;
      background: #fff;
      width: calc(100% - 200px);
      position: absolute;
      text-align: right;
      bottom: 0;
      right: 0;
      &::before {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        height: 2px;
        width: 100%;
        background-color: #e4e7ed;
        z-index: 1;
      }
    }
  }

  .setBtn-main {
    position: relative;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    .setBtn-search {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      z-index: 2;
      background: #fff;
    }

    .setBtn-show {
      position: relative;
      height: 100%;
      padding: 40px 0 0 0;
      overflow-y: scroll;
    }
  }
}
</style>
