import { PermTree } from '@/pages/Admin/_shared/PermTree';
import { fetchPermList } from '@/services/perm';
import { fetchBindRolePerms, fetchRoleDetail } from '@/services/role';
import { Button, Drawer, Spin, message } from 'antd';
import { useEffect, useState } from 'react';

interface RolePermDrawerProps {
  roleId: number;
  productCode: string;
  open: boolean;
  onClose: () => void;
}

export const RolePermDrawer = ({ roleId, productCode, open, onClose }: RolePermDrawerProps) => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [allPerms, setAllPerms] = useState<API.PermItem[]>([]);
  const [checkedIds, setCheckedIds] = useState<number[]>([]);

  useEffect(() => {
    if (!open) return;
    setLoading(true);
    Promise.all([fetchRoleDetail({ id: roleId }), fetchPermList({ productCode, pageSize: 9999 })])
      .then(([roleRes, permRes]) => {
        setAllPerms(permRes.data ?? []);
        setCheckedIds(roleRes.data?.permIds ?? []);
      })
      .finally(() => setLoading(false));
  }, [open, roleId, productCode]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await fetchBindRolePerms({ roleId, permIds: checkedIds });
      message.success('保存成功');
      onClose();
    } finally {
      setSaving(false);
    }
  };

  return (
    <Drawer
      title="绑定权限"
      open={open}
      onClose={onClose}
      width={560}
      extra={
        <Button type="primary" loading={saving} onClick={handleSave}>
          保存
        </Button>
      }
    >
      <Spin spinning={loading}>
        <PermTree
          mode="edit"
          allPerms={allPerms}
          checkedPermIds={checkedIds}
          onChange={setCheckedIds}
        />
      </Spin>
    </Drawer>
  );
};
