<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addRole">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <!-- 添加角色 -->
    <RoleModal ref="formRole" :formRoleValue="formRoleValue" />

    <!-- 菜单权限 -->
    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="editRoleTitle"
    >
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :expanded-keys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? "收起" : "展开" }}
          </n-button>

          <n-button
            type="info"
            ghost
            icon-placement="left"
            @click="checkedAllHandle"
          >
            全部{{ checkedAll ? "取消" : "选择" }}
          </n-button>
          <n-button
            type="primary"
            :loading="formBtnLoading"
            @click="confirmForm"
            >提交</n-button
          >
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { BasicTable, TableAction } from "@/components/Table";

import { columns } from "./columns";
import { PlusOutlined } from "@vicons/antd";
import { getTreeAll } from "@/utils";
import { getRuleList } from "@/api/system/role";
import { getMenuTree } from "@/api/system/menu";
import { queryMenuByRole, saveRoleMenu } from "@/api/system/roleMenu";

const actionRef = ref();
const formRole = ref();
const formRoleValue = reactive({
  id: null,
  roleName: "",
  roleCode: null,
  status: 1,
  description: "",
});
const lastMenuIds = ref([]);
const showModal = ref(false);
const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref("");
const treeData = ref([]);
const expandedKeys = ref([]);
const checkedKeys: Ref<any[]> = ref([]);
const roleId = ref(null);
const params = reactive({
  roleName: "",
});

const actionColumn = reactive({
  width: 250,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record) {
    return h(TableAction, {
      style: "button",
      actions: [
        {
          label: "菜单权限",
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
        },
        {
          label: "编辑",
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
        {
          label: "删除",
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
        },
      ],
    });
  },
});

const mapTreeData = (data) => {
  return data.map((ele) => ({
    ...ele,
    key: ele.id,
    label: ele.meta.title,
    children: ele.children ? mapTreeData(ele.children) : undefined,
  }));
};

// 新增按钮
const addRole = () => {
  formRole.value.init("add");
};

const loadDataTable = async (res: any) => {
  let _params = {
    ...unref(params),
    ...res,
  };
  const { data } = await getRuleList(_params);
  return data;
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

async function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  const res = await saveRoleMenu({
    roleId: roleId.value,
    menuIds: checkedKeys.value,
    lastMenuIds: lastMenuIds.value,
  });
  if (res.status === 200) {
    showModal.value = false;
    reloadTable();
    window["$message"].success("保存成功");
    formBtnLoading.value = false;
  }
}

function handleEdit(record: Recordable) {
  console.log("点击了编辑", record);
}

function handleDelete(record: Recordable) {
  console.log("点击了删除", record);
}

async function handleMenuAuth(record: Recordable) {
  editRoleTitle.value = `分配 ${record.roleName} 的菜单权限`;
  roleId.value = record.id;
  const res = await queryMenuByRole({ roleId: record.id });
  lastMenuIds.value = res.data;

  checkedKeys.value = res.data; // 根据roleid查询权限菜单
  showModal.value = true;
}

function checkedTree(keys) {
  checkedKeys.value = keys;
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = treeData.value.map((item: any) => item.key) as [];
  }
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = getTreeAll(treeData.value);
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

onMounted(async () => {
  const treeMenuList = await getMenuTree();
  const res = mapTreeData(treeMenuList.data);
  expandedKeys.value = treeMenuList.data.map((item) => item.key);
  treeData.value = res;
});
</script>

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