/**
 * KRA - Data Permission Component
 * Configure data/resource permissions for authority/role
 */
import React, { useState, useEffect } from 'react';
import { Checkbox, Button, message, Space } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { setDataAuthority } from '@/services/kratos/authority';
import WarningBar from '@/components/WarningBar/WarningBar';

interface Authority {
  authorityId: string;
  authorityName: string;
  parentId: string;
  children?: Authority[];
  dataAuthorityId?: Authority[];
}

interface DataPermissionProps {
  row: Authority;
  authority: Authority[];
  onChangeRow: (key: string, value: any) => void;
}

const DataPermission: React.FC<DataPermissionProps> = ({ row, authority, onChangeRow }) => {
  const [flatAuthorities, setFlatAuthorities] = useState<Authority[]>([]);
  const [selectedAuthorities, setSelectedAuthorities] = useState<Authority[]>([]);

  useEffect(() => {
    // 平铺角色树
    const flat: Authority[] = [];
    const flatten = (items: Authority[]) => {
      items.forEach((item) => {
        flat.push({
          authorityId: item.authorityId,
          authorityName: item.authorityName,
          parentId: item.parentId,
        });
        if (item.children) {
          flatten(item.children);
        }
      });
    };
    flatten(authority);
    setFlatAuthorities(flat);

    // 初始化已选中的数据权限
    if (row.dataAuthorityId) {
      const selected = row.dataAuthorityId.map((item) => ({
        authorityId: item.authorityId,
        authorityName: item.authorityName,
        parentId: item.parentId || '',
      }));
      setSelectedAuthorities(selected);
    }
  }, [authority, row.dataAuthorityId]);

  // 全选
  const handleSelectAll = () => {
    setSelectedAuthorities([...flatAuthorities]);
    onChangeRow('dataAuthorityId', flatAuthorities);
  };

  // 本角色
  const handleSelectSelf = () => {
    const self = flatAuthorities.filter((item) => item.authorityId === row.authorityId);
    setSelectedAuthorities(self);
    onChangeRow('dataAuthorityId', self);
  };

  // 本角色及子角色
  const handleSelectSelfAndChildren = () => {
    const ids: string[] = [];
    const getChildrenIds = (item: Authority) => {
      ids.push(item.authorityId);
      if (item.children) {
        item.children.forEach(getChildrenIds);
      }
    };
    
    // 找到当前角色在原始树中的位置
    const findInTree = (items: Authority[]): Authority | undefined => {
      for (const item of items) {
        if (item.authorityId === row.authorityId) {
          return item;
        }
        if (item.children) {
          const found = findInTree(item.children);
          if (found) return found;
        }
      }
      return undefined;
    };

    const currentInTree = findInTree(authority);
    if (currentInTree) {
      getChildrenIds(currentInTree);
    } else {
      ids.push(row.authorityId);
    }

    const selected = flatAuthorities.filter((item) => ids.includes(item.authorityId));
    setSelectedAuthorities(selected);
    onChangeRow('dataAuthorityId', selected);
  };

  // 选择变化
  const handleCheckChange = (item: Authority, checked: boolean) => {
    let newSelected: Authority[];
    if (checked) {
      newSelected = [...selectedAuthorities, item];
    } else {
      newSelected = selectedAuthorities.filter((s) => s.authorityId !== item.authorityId);
    }
    setSelectedAuthorities(newSelected);
    onChangeRow('dataAuthorityId', newSelected);
  };

  // 确认提交
  const handleConfirm = async () => {
    try {
      const res = await setDataAuthority({
        authorityId: row.authorityId,
        dataAuthorityId: selectedAuthorities,
      });
      if (res.code === 0) {
        message.success('资源设置成功');
      }
    } catch (error) {
      message.error('设置失败');
    }
  };

  // 检查是否选中
  const isChecked = (item: Authority) => {
    return selectedAuthorities.some((s) => s.authorityId === item.authorityId);
  };

  return (
    <div>
      <WarningBar
        title="此功能仅用于创建角色和角色的many2many关系表，具体使用还须自己结合表实现业务，详情参考示例代码（客户示例）。此功能不建议使用，建议使用插件市场【组织管理功能】来管理资源权限。"
        type="warning"
      />
      <div style={{ display: 'flex', gap: 8, marginTop: 16, marginBottom: 16, position: 'sticky', top: 0, background: '#fff', zIndex: 10, padding: '8px 0' }}>
        <Button type="primary" onClick={handleSelectAll}>
          全选
        </Button>
        <Button type="primary" onClick={handleSelectSelf}>
          本角色
        </Button>
        <Button type="primary" onClick={handleSelectSelfAndChildren}>
          本角色及子角色
        </Button>
        <Button type="primary" onClick={handleConfirm} style={{ marginLeft: 'auto' }}>
          确定
        </Button>
      </div>
      <div style={{ paddingTop: 16 }}>
        <Checkbox.Group
          value={selectedAuthorities.map((s) => s.authorityId)}
          style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}
        >
          {flatAuthorities.map((item) => (
            <Checkbox
              key={item.authorityId}
              value={item.authorityId}
              checked={isChecked(item)}
              onChange={(e: CheckboxChangeEvent) => handleCheckChange(item, e.target.checked)}
            >
              {item.authorityName}
            </Checkbox>
          ))}
        </Checkbox.Group>
      </div>
    </div>
  );
};

export default DataPermission;
