<template>
  <div>
    <div style="height: calc(100vh - 200px)">
      <obj-table-plus
        ref="oTable"
        style="height: 100%"
        :tableCols="tableCols"
        :tableProp="tableProp"
        @query="queryList"
        v-model="dataList"
        :tableEvent="tableEvent"
      >
        <template slot="tableTop">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="角色名称">
              <el-input
                placeholder="请输入角色名称"
                v-model="formInline.name"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="$refs.oTable.reload()"
                >查询</el-button
              >
              <el-button type="primary" @click="Reset">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="mb-2">
            <el-button type="primary" size="small" @click="addBanner"
              >新增角色</el-button
            >
          </div>
        </template>
      </obj-table-plus>
    </div>
    <!-- 新增角色 -->
    <addOrUpdate
      ref="addOrUpdate"
      @queryList="$refs.oTable.reload()"
    ></addOrUpdate>
    <el-dialog
      v-if="isShow"
      title="菜单权限"
      :visible.sync="dialogTableVisible"
    >
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="角色权限：">
          <el-tree
            style="margin-top: 10px"
            ref="tree"
            :data="data"
            show-checkbox
            node-key="url"
            :default-expand-all="true"
            :default-checked-keys="menuCheckKeys"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sure">确定</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenu } from "@/utils";
import addOrUpdate from "./popup/add-or-update.vue";
import { mapState } from "vuex";
import FULL_ROUTERS from "@/router/full-routers";
export default {
  components: { addOrUpdate },
  data() {
    return {
      dialogTableVisible: false,
      activeName: "5",
      advanceSellStatus: "",
      dataList: [],
      form: {},
      formInline: {
        name: "",
      },
      tableProp: {
        "auto-resize": true,
        border: true,
        height: "auto",
        "row-id": "id",
        "show-overflow": false,
      },
      selectList: [],
      data: [],
      defaultProps: {
        children: "list",
        label: "name",
        value: "url",
      },
      menuCheckKeys: [],
      roleId: "",
      isShow: false,
    };
  },
  methods: {
    addBanner() {
      this.$refs.addOrUpdate.toggle().add(this.formInline);
    },
    queryList(pageNo, pageSize) {
      let permissionsData = getMenu(
        JSON.parse(sessionStorage.getItem("userInfo")).role,
        JSON.parse(sessionStorage.getItem("userInfo")).manageMode
      );
      this.data = this.filterTreeData(FULL_ROUTERS.menuList, permissionsData);

      this.$api.role
        .roleList({
          ownerId: JSON.parse(sessionStorage.getItem("userInfo")).managerId
            ? JSON.parse(sessionStorage.getItem("userInfo")).managerId
            : JSON.parse(sessionStorage.getItem("userInfo")).merchantId,
        })
        .then((res) => {
          console.log(res);
          this.$refs.oTable.complete(res.data.data, Number(res.data.total));
        })
        .catch((err) => {
          this.$refs.oTable.complete(false);
        });
    },
    Reset() {
      this.formInline = {
        name: "",
      };
      this.$refs.oTable.reload();
    },
    sure() {
      console.log(this.$refs.tree.getHalfCheckedKeys());
      console.log(this.$refs.tree.getCheckedKeys());
      this.$api.role
        .updatePermissionUpdate({
          roleId: this.roleId,
          permissions: [
            ...this.$refs.tree.getHalfCheckedKeys(),
            ...this.$refs.tree.getCheckedKeys(),
          ],
        })
        .then((res) => {
          console.log(res);
          this.dialogTableVisible = false;
          this.$refs.oTable.reload();
        });
    },
    handleNodeClick(data) {
      console.log(data);
    },
    filterTreeData(data, permissions) {
      console.log(data);
      // return data; //临时性返回所有菜单方便调试
      return data.reduce((filtered, node) => {
        // 如果节点的权限在权限数组中
        if (permissions.includes(node.url)) {
          // 递归过滤子节点
          const list = this.filterTreeData(node.list || [], permissions);
          // 创建一个新的节点，包含过滤后的子节点
          filtered.push({
            ...node,
            list,
          });
        }
        return filtered;
      }, []);
    },
  },
  watch: {
    dialogTableVisible(e) {
      if (!e) {
        this.isShow = false;
      }
    },
  },
  computed: {
    tableCols() {
      return [
        // { type: "checkbox", width: "60px", fixed: "left" },
        {
          type: "seq",
          width: "60px",
          fixed: "left",
          align: "center",
          title: "序号",
        },
        {
          title: "角色名称",
          align: "center",
          field: "name",
        },
        {
          title: "备注",
          align: "center",
          field: "remark",
        },
        {
          title: "操作",
          fixed: "right",
          type: "jsx",
          width: "380px",
          align: "center",
          render: ({ row }) => {
            //权限
            let permission = () => {
              this.roleId = row.id;
              this.isShow = true;
              this.$api.role.getRoleList({ roleId: row.id }).then((res) => {
                let arr = [
                  "operation-management",
                  "datacenter",
                  "presale",
                  "marketing",
                ];
                this.menuCheckKeys = res.data.data.filter((item) => {
                  return !arr.includes(item);
                });
                this.dialogTableVisible = true;
              });
            };
            let updateBanner = () => {
              this.$refs.addOrUpdate.toggle(row).update();
            };
            let deleteBanner = () => {
              this.$api.role.deleteRoleList({ id: row.id }).then((res) => {
                this.$refs.oTable.reload();
              });
            };
            let onCancel = () => {};
            return (
              <div>
                <el-button
                  style="margin-right:10px"
                  size="mini"
                  type="warning"
                  onClick={permission}
                >
                  菜单权限
                </el-button>
                <el-button
                  style="margin-right:20px"
                  size="mini"
                  type="primary"
                  onClick={updateBanner}
                >
                  编辑
                </el-button>
                <el-popconfirm
                  onConfirm={deleteBanner}
                  onCancel={onCancel}
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除吗？"
                >
                  <el-button size="mini" type="danger" slot="reference">
                    删除
                  </el-button>
                </el-popconfirm>
              </div>
            );
          },
        },
      ];
    },
    tableEvent() {
      return {
        "checkbox-all": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        },
        "checkbox-change": ({ records, reserves }) => {
          this.selectList = [...records, ...reserves];
        },
      };
    },
    ...mapState("userData", [
      "isMerchant",
      "marketList",
      "storeList",
      "marketId",
      "shopId",
    ]),
  },
};
</script>

<style lang="scss" scoped></style>
