<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"
      @reload-table="reloadTable()"
    />

    <!-- 菜单权限 -->
    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="editRoleTitle"
    >
      <div class="py-3 menu-list">
        <n-tree
          block-line
          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, deleteRule } from '@/api/system/role';
import { getMenuTreeAll } from '@/api/system/menu';
import { queryMenuByRole, saveRoleMenu } from '@/api/system/roleMenu';
import { zsDialog } from '@/utils';
import { DialogEnum } from '@/enums/pluginEnum';

const actionRef = ref();
const formRole = ref();
const formRoleValue = reactive({
  id: null,
  roleName: '',
  roleCode: null,
  status: true,
  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');
  Object.assign(formRoleValue, {
    id: null,
    roleName: '',
    roleCode: null,
    status: true,
    description: '',
  });
};

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) {
  Object.assign(formRoleValue, record);
  formRole.value.init('edit');
}

async function handleDelete(record: Recordable) {
  zsDialog({
    type: DialogEnum.ERROR,
    message: `您确定要删除 ${record.roleName} 角色吗?`,
    positiveButtonProps: { type: 'primary', ghost: false },
    onPositiveCallback: async () => {
      const data = await deleteRule({ id: record.id });
      if (data.status === 200) reloadTable();
      window['$message'].success('删除成功');
    },
  });
}

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 getMenuTreeAll();
  const res = mapTreeData(treeMenuList.data);
  expandedKeys.value = treeMenuList.data.map((item) => item.key);
  treeData.value = res;
});
</script>
