<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { enableStatusRecord } from '@/constants/business';
import {
  fetchAddRoleMenu,
  fetchDelRoleMenu,
  fetchEditRoleMenu,
  fetchGetMenuTree,
  fetchGetRoleForm,
  fetchGetRoleList,
  fetchGetRoleMenuIds,
  fetchUpdateRoleMenus
} from '@/service/api';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { $t } from '@/locales';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
const columns: NaiveUI.TableColumn<Api.System.roleList>[] = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'index',
    title: $t('common.index'),
    align: 'center',
    width: 64,
    render: (_, index) => index + 1
  },
  {
    key: 'name',
    title: '角色名称',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'code',
    title: '角色编码',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null) {
        return null;
      }

      const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'error'
      };

      const status = row.status as unknown as Api.Common.EnableStatus;
      const label = $t(enableStatusRecord[status]);
      return <NTag type={tagMap[status]}>{label}</NTag>;
    }
  }
];
const menuData = ref<Api.SystemManage.MenuTree[]>([]);
const checkedKeys = ref([]);
const rowData = ref<Api.System.roleList>();
const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'keywords',
        label: '角色名称',
        component: 'NInput'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '角色列表',
    showAddButton: true,
    scrollX: 1200,
    opWdith: 220
  }
});

async function handleDelete(row: Recordable) {
  setTableLoading(true);
  await fetchDelRoleMenu([row.id].join(','));
  refresh();
}
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue, setModalLoading }] = useModalFrom({
  modalConfig: {
    title: '角色 ',
    width: 800,
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'id',
        label: '',
        component: 'NInput',
        show: false
      },
      {
        field: 'name',
        label: '角色名称',
        component: 'NInput',
        required: true
      },
      {
        field: 'code',
        label: '角色编码',
        component: 'NInput',
        required: true
      },
      {
        field: 'dataScope',
        label: '数据权限',
        component: 'NSelect',
        required: true,
        componentProps: {
          options: [
            {
              label: '全部数据',
              value: 0
            },
            {
              label: '部门及子部门数据',
              value: 1
            },
            {
              label: '本部门数据',
              value: 2
            },
            {
              label: '本人数据',
              value: 3
            }
          ]
        }
      },
      {
        field: 'status',
        label: '状态',
        component: 'NRadioGroup',
        required: true,
        componentProps: {
          options: [
            {
              label: '启用',
              value: 1
            },
            {
              label: '禁用',
              value: 0
            }
          ]
        },
        defaultValue: 1
      }
    ],
    labelWidth: 120,
    gridProps: {
      cols: '1'
    }
  }
});
const [registerModalMenu, { openModal: openMenu, closeModal: closeMenu, setSubLoading }] = useModal({
  title: '权限分配',
  height: 800
});
async function handleSubmit() {
  const form = await getFieldsValue();
  if (form.id) {
    await fetchEditRoleMenu(form);
  } else {
    await fetchAddRoleMenu(form);
  }
  closeModal();
  refresh();
}

async function edit(row: Recordable) {
  setModalLoading(true);
  openModal(row);
  const res = await fetchGetRoleForm(row.id);
  setModalLoading(false);
  setFieldsValue({ ...res.data });
}
async function handleOpenMenu(row: Api.System.roleList) {
  openMenu();
  rowData.value = row;
  const { data } = await fetchGetMenuTree();
  menuData.value = data as Api.SystemManage.MenuTree[];
  const { data: menuId } = await fetchGetRoleMenuIds(Number(row.id));
  console.log(menuId, '数据');
  checkedKeys.value = menuId;
}
async function handleSubmitMenu() {
  if (checkedKeys.value.length) {
    setSubLoading(true);
    await fetchUpdateRoleMenus(rowData.value?.id as number, checkedKeys.value);
    closeMenu();
  } else {
    window.$message?.error('请选择需要分配的权限');
  }
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetRoleList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" @click="handleOpenMenu(row)">分配权限</NButton>
        <NButton size="small" ghost type="primary" @click="edit(row)">编辑</NButton>
        <NPopconfirm @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost>删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
    </ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
    <BasicModal @register="registerModalMenu" @ok="handleSubmitMenu">
      <NTree
        v-model:checked-keys="checkedKeys"
        :data="menuData"
        key-field="value"
        checkable
        default-expand-all
        block-line
      />
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
