import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { roleApi, RoleVO } from '../api/Role';
import { deptApi, DeptVO } from '../api/dept';
import { loginApi } from '../api/Login';
import { toast } from 'sonner';
import { Modal, Form, Tag, Card, Switch, Tree, Spin, Select, Space } from 'antd';
import { handleTree } from '../utils/tree';
import { getIntDictOptions, DICT_TYPE, setDictOptions } from '../utils/dict';
import { SystemDataScopeEnum } from '../utils/constants';
import type { DataNode } from 'antd/es/tree';
import { useTranslation } from 'react-i18next';

interface RoleDataPermissionFormProps {
  onSuccess?: () => void;
}

export interface RoleDataPermissionFormRef {
  open: (row: RoleVO) => void;
}

const RoleDataPermissionForm = forwardRef<RoleDataPermissionFormRef, RoleDataPermissionFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [formData, setFormData] = useState<{
    id?: number;
    name: string;
    code: string;
    dataScope?: number;
    dataScopeDeptIds: number[];
  }>({
    id: undefined,
    name: '',
    code: '',
    dataScope: undefined,
    dataScopeDeptIds: [],
  });
  const [deptOptions, setDeptOptions] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [deptExpand, setDeptExpand] = useState(true);
  const [treeNodeAll, setTreeNodeAll] = useState(false);
  const [checkStrictly, setCheckStrictly] = useState(true);
  const [form] = Form.useForm();
  const [dataScopeOptions, setDataScopeOptions] = useState<Array<{ label: string; value: number }>>([]);

  // 将部门数据转换为 Tree 组件需要的格式
  const convertDeptToTreeData = (depts: DeptVO[]): DataNode[] => {
    return depts.map((dept) => ({
      title: dept.name,
      key: dept.id!,
      children: (dept as any).children ? convertDeptToTreeData((dept as any).children) : undefined,
    }));
  };

  // 加载权限范围字典数据
  const loadDataScopeOptions = async () => {
    try {
      // 先从缓存获取
      const cachedOptions = getIntDictOptions('role_scope');
      if (cachedOptions && cachedOptions.length > 0) {
        setDataScopeOptions(cachedOptions.map(item => ({ label: item.label, value: item.value })));
        return;
      }

      // 如果缓存中没有，从 API 获取
      const dictDataList = await loginApi.getDictDataSimpleList();
      const allDictData = (dictDataList as any)?.data || dictDataList || [];
      
      // 过滤出 role_scope 类型的字典数据
      const roleScopeData = allDictData.filter((item: any) => item.dictType === 'role_scope');
      
      if (roleScopeData.length > 0) {
        // 转换为字典格式并缓存
        const dictOptions = roleScopeData.map((item: any) => ({
          dictType: 'role_scope',
          label: item.label,
          value: parseInt(String(item.value)),
          colorType: item.colorType || '',
          cssClass: item.cssClass || '',
        }));
        setDictOptions('role_scope', dictOptions);
        setDataScopeOptions(dictOptions.map(item => ({ label: item.label, value: item.value })));
      } else {
        // 如果 API 没有数据，使用默认选项
        const defaultOptions = getIntDictOptions(DICT_TYPE.SYSTEM_DATA_SCOPE);
        setDataScopeOptions(defaultOptions.map(item => ({ label: item.label, value: item.value })));
      }
    } catch (error: any) {
      console.error(t('role.loadDataScopeDictFailed'), error);
      // 如果加载失败，使用系统默认的数据权限范围
      const defaultOptions = getIntDictOptions(DICT_TYPE.SYSTEM_DATA_SCOPE);
      setDataScopeOptions(defaultOptions.map(item => ({ label: item.label, value: item.value })));
    }
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    open: async (row: RoleVO) => {
      setDialogVisible(true);
      resetForm();
      
      // 加载权限范围字典数据
      await loadDataScopeOptions();
      
      // 加载部门列表
      try {
        const depts = await deptApi.getSimpleDeptList();
        const deptData = (depts as any)?.data || depts;
        const treeData = handleTree(deptData || []);
        const treeNodes = convertDeptToTreeData(treeData);
        setDeptOptions(treeNodes);
        
        // 设置数据
        setFormData({
          id: row.id,
          name: row.name,
          code: row.code,
          dataScope: row.dataScope,
          dataScopeDeptIds: row.dataScopeDeptIds || [],
        });

        form.setFieldsValue({
          dataScope: row.dataScope,
        });

        // 如果是自定义数据权限，设置选中的部门
        if (row.dataScope === SystemDataScopeEnum.DEPT_CUSTOM && row.dataScopeDeptIds) {
          setCheckedKeys(row.dataScopeDeptIds.map((id: number) => id));
          setExpandedKeys(row.dataScopeDeptIds.map((id: number) => id));
        }
      } catch (error: any) {
        console.error(t('role.loadDeptListFailed'), error);
        toast.error(t('role.loadDeptListFailed'));
      }
    },
  }));

  // 提交表单
  const submitForm = async () => {
    try {
      setFormLoading(true);
      
      const data = {
        roleId: formData.id!,
        dataScope: formData.dataScope!,
        dataScopeDeptIds:
          formData.dataScope !== SystemDataScopeEnum.DEPT_CUSTOM
            ? []
            : (checkedKeys as number[]),
      };

      await roleApi.assignRoleDataScope(data);
      toast.success(t('role.updateSuccess'));
      setDialogVisible(false);
      onSuccess?.();
    } catch (error: any) {
      toast.error(error.message || t('role.operationFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    setTreeNodeAll(false);
    setDeptExpand(true);
    setCheckStrictly(true);
    setFormData({
      id: undefined,
      name: '',
      code: '',
      dataScope: undefined,
      dataScopeDeptIds: [],
    });
    setCheckedKeys([]);
    setExpandedKeys([]);
    form.resetFields();
  };

  // 全选/全不选
  const handleCheckedTreeNodeAll = (checked: boolean) => {
    setTreeNodeAll(checked);
    if (checked) {
      const getAllKeys = (nodes: DataNode[]): React.Key[] => {
        let keys: React.Key[] = [];
        nodes.forEach((node) => {
          keys.push(node.key);
          if (node.children) {
            keys = keys.concat(getAllKeys(node.children));
          }
        });
        return keys;
      };
      setCheckedKeys(getAllKeys(deptOptions));
    } else {
      setCheckedKeys([]);
    }
  };

  // 展开/折叠全部
  const handleCheckedTreeExpand = (expanded: boolean) => {
    setDeptExpand(expanded);
    if (expanded) {
      const getAllKeys = (nodes: DataNode[]): React.Key[] => {
        let keys: React.Key[] = [];
        nodes.forEach((node) => {
          keys.push(node.key);
          if (node.children) {
            keys = keys.concat(getAllKeys(node.children));
          }
        });
        return keys;
      };
      setExpandedKeys(getAllKeys(deptOptions));
    } else {
      setExpandedKeys([]);
    }
  };

  // 数据权限范围变化
  const handleDataScopeChange = (value: number) => {
    setFormData(prev => ({ ...prev, dataScope: value }));
    if (value !== SystemDataScopeEnum.DEPT_CUSTOM) {
      setCheckedKeys([]);
    }
  };

  return (
    <Modal
      title={t('role.dataPermission')}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={900}
      destroyOnClose
    >
      <Spin spinning={formLoading}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
        >
          <Form.Item label={t('role.roleName')}>
            <Tag style={{
      fontSize: '16px',
      padding: '8px 16px', 
      lineHeight: '1',
      minHeight: '32px'
    }}>{formData.name}</Tag>
          </Form.Item>

          <Form.Item label={t('role.roleCode')}>
            <Tag style={{
      fontSize: '16px',
      padding: '8px 16px', 
      lineHeight: '1',
      minHeight: '32px'
    }}>{formData.code}</Tag>
          </Form.Item>

          <Form.Item
            label={t('role.dataScope')}
            name="dataScope"
            rules={[{ required: true, message: t('role.dataScopeRequired') }]}
          >
            <Select
              placeholder={t('role.dataScopePlaceholder')}
              onChange={handleDataScopeChange}
              options={dataScopeOptions}
              style={{ maxWidth: '450px' }}
            />
          </Form.Item>

          {formData.dataScope === SystemDataScopeEnum.DEPT_CUSTOM && (
            <Form.Item label={t('role.deptScope')} labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
              <Card
                title={
                  <Space>
                    <span>{t('role.selectAll')}</span>
                    <Switch
                      checked={treeNodeAll}
                      onChange={handleCheckedTreeNodeAll}
                      checkedChildren={t('role.yes')}
                      unCheckedChildren={t('role.no')}
                    />
                    <span style={{ marginLeft: 16 }}>{t('role.expandAll')}</span>
                    <Switch
                      checked={deptExpand}
                      onChange={handleCheckedTreeExpand}
                      checkedChildren={t('role.expand')}
                      unCheckedChildren={t('role.collapse')}
                    />
                    <span style={{ marginLeft: 16 }}>{t('role.parentChildLinkage')}</span>
                    <Switch
                      checked={checkStrictly}
                      onChange={setCheckStrictly}
                      checkedChildren={t('role.yes')}
                      unCheckedChildren={t('role.no')}
                    />
                  </Space>
                }
                style={{ maxHeight: 400, overflowY: 'auto' }}
              >
                <Tree
                  checkable
                  checkedKeys={checkedKeys}
                  expandedKeys={expandedKeys}
                  onCheck={setCheckedKeys}
                  onExpand={setExpandedKeys}
                  treeData={deptOptions}
                  checkStrictly={!checkStrictly}
                  defaultExpandAll
                />
              </Card>
            </Form.Item>
          )}
        </Form>
      </Spin>
    </Modal>
  );
});

RoleDataPermissionForm.displayName = 'RoleDataPermissionForm';

export default RoleDataPermissionForm;

