import React, { Fragment, useState, useEffect } from 'react';
import { useAccess } from '@umijs/max';
import { getModelConfig, saveModelConfig } from '@/services/application/modelManagement';
import {
  Card,
  Row,
  Col,
  Form,
  Button,
  message,
  Menu,
  Space,
  Modal,
  Slider,
  InputNumber,
} from 'antd';
import {
  SaveOutlined,
  ReloadOutlined,
  SettingOutlined,
  UserOutlined,
  CalculatorOutlined,
  EyeOutlined,
  TrophyOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';

interface ConfigItem {
  createTime: string | null;
  id: number;
  configName: string;
  configValue: string;
  modelType: string;
  isWeight?: boolean;
}

interface ModelConfig {
  [key: string]: ConfigItem[];
}

function ModelManagement() {
  const access = useAccess();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedModel, setSelectedModel] = useState<string>('');
  const [configData, setConfigData] = useState<ModelConfig>({});
  const [totalWeight, setTotalWeight] = useState<number>(0);
  const [modelTypes, setModelTypes] = useState<string[]>([]);

  // 图标映射
  const iconMap: { [key: string]: React.ReactNode } = {
    位置匹配模型: <EnvironmentOutlined />,
    人岗精准匹配模型: <UserOutlined />,
    基于求职者行为推荐模型: <EyeOutlined />,
    竞争力计算模型: <TrophyOutlined />,
    人岗匹配度计算模型: <CalculatorOutlined />,
  };

  const defaultIcon = <SettingOutlined />;

  // 生成模型菜单
  const generateModelMenu = () => {
    return modelTypes.map((modelType) => ({
      key: modelType,
      label: modelType,
      icon: iconMap[modelType] || defaultIcon,
    }));
  };

  // 计算总权重
  const calculateTotalWeight = (modelType: string, formValues: any) => {
    const modelConfigs = configData[modelType] || [];
    const total = modelConfigs.reduce((sum: number, config: ConfigItem) => {
      if (!!config.isWeight) {
        const value = parseFloat(formValues[config.configName] || 0);
        return sum + Math.round(value * 100);
      }
      return sum;
    }, 0);

    setTotalWeight(total / 100);
  };

  const handleFormChange = (changedValues: any, allValues: any) => {
    calculateTotalWeight(selectedModel, allValues);
  };

  // 设置表单值
  const setFormValues = (modelType: string, configs: ConfigItem[]) => {
    const initialValues: any = {};
    configs.forEach((config) => {
      // 确保值为数字类型，如果解析失败则使用0
      const value = parseFloat(config.configValue);
      initialValues[config.configName] = isNaN(value) ? 0 : value;
    });

    // 确保设置表单值
    setTimeout(() => {
      form.setFieldsValue(initialValues);
      calculateTotalWeight(modelType, initialValues);
    }, 30);
  };

  // 加载配置数据
  const loadConfigData = async () => {
    setLoading(true);
    try {
      const res = await getModelConfig('');
      if (res.code === 200) {
        const data = res.data as ConfigItem[];

        // 按模型类型分组
        const groupedData: ModelConfig = {};
        const types: string[] = [];
        const names = '人岗匹配度计算模型';

        data.forEach((item: ConfigItem) => {
          if (!groupedData[item.modelType]) {
            groupedData[item.modelType] = [];
            types.push(item.modelType);
          }
          groupedData[item.modelType].push(item);
          // 匹配度 ---------记得删除
          if ('人岗精准匹配模型' === item.modelType) {
            if (!groupedData[names]) {
              groupedData[names] = [];
              types.push(names);
            }
            groupedData[names].push(item);
          }
        });

        setConfigData(groupedData);
        setModelTypes(types);

        // 设置默认选中的模型 - 修复：使用最新的 groupedData
        if (types.length > 0) {
          const currentModel = selectedModel || types[0];
          setSelectedModel(currentModel);
          setFormValues(currentModel, groupedData[currentModel]);
        }
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      message.error('加载配置失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取单位
  const getUnit = (configName: string): string => {
    if (configName.includes('薪资') || configName.includes('工资')) {
      return '元';
    }
    if (configName.includes('距离') || configName.includes('半径') || configName.includes('通勤')) {
      return 'Km';
    }
    return '';
  };

  // 校验权重
  const validateWeight = (modelType: string, values: any) => {
    const modelConfigs = configData[modelType] || [];
    const hasWeight = modelConfigs.some((config) => !!config.isWeight);

    if (!hasWeight) {
      return true;
    }

    const total =
      modelConfigs.reduce((sum: number, config: ConfigItem) => {
        if (!!config.isWeight) {
          const value = values[config.configName] || 0;
          return sum + Math.round(value * 100);
        }
        return sum;
      }, 0) / 100;

    return Math.abs(total - 1) < 0.01;
  };

  const handleSaveConfig = async (values: any) => {
    if (!validateWeight(selectedModel, values)) {
      message.error(`当前模型权重总和为 ${totalWeight.toFixed(2)}，应等于 1.00 。`);
      return;
    }
    await performSave(values);
  };

  // 保存
  const performSave = async (values: any) => {
    setLoading(true);
    try {
      const modelConfigs = configData[selectedModel] || [];

      const saveData = modelConfigs.map((config) => ({
        createTime: config.createTime,
        id: config.id,
        configName: config.configName,
        configValue: values[config.configName].toString(),
        modelType: config.modelType,
        isWeight: config.isWeight,
      }));

      const resData = await saveModelConfig({ modelConfigList: saveData });
      if (resData.code === 200) {
        message.success('配置保存成功');
        // 修复：保存成功后重新加载数据，确保使用最新的接口数据
        await loadConfigData();
      } else {
        message.error(resData.msg || '保存失败');
      }
    } catch (error) {
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 重置 - 修复：确保重置后表单数据正确更新
  const handleResetConfig = async () => {
    Modal.confirm({
      title: '重置确认',
      content: '确定要重置当前模型的配置参数吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 重新加载数据，确保使用服务器的最新数据
        await loadConfigData();
      },
    });
  };

  // 模型切换 - 修复：使用最新的 configData
  const handleModelChange = (key: string) => {
    setSelectedModel(key);
    let modelConfigs = configData[key] || [];
    setFormValues(key, modelConfigs);
  };

  // 颜色
  const getWeightColor = () => {
    if (Math.abs(totalWeight - 1) < 0.01) return '#52c41a';
    if (totalWeight > 1) return '#ff4d4f';
    return '#faad14';
  };

  // 状态文本
  const getWeightStatusText = () => {
    if (Math.abs(totalWeight - 1) < 0.01) return '权重分配合理';
    if (totalWeight > 1) return '权重超出范围';
    return '权重分配不足';
  };

  // 检查当前模型是否有权重配置
  const hasWeightConfig = () => {
    const modelConfigs = configData[selectedModel] || [];
    return modelConfigs.some((config) => !!config.isWeight);
  };

  // 渲染表单组件 - 修复：添加默认值处理
  const renderFormComponent = () => {
    const modelConfigs = configData[selectedModel] || [];

    return modelConfigs.map((config: ConfigItem) => {
      const unit = getUnit(config.configName);
      const isWeight = !!config.isWeight;

      return (
        <Form.Item
          key={config.id}
          label={
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>{config.configName}</div>
              {isWeight && (
                <div
                  style={{
                    color: '#1890ff',
                    fontSize: '13px',
                    marginTop: '1px',
                    marginLeft: '10px',
                  }}
                >
                  权重: {(form.getFieldValue(config.configName) || 0).toFixed(2)}
                </div>
              )}
            </div>
          }
          name={config.configName}
          initialValue={parseFloat(config.configValue) || 0}
          rules={[
            { required: true, message: `请输入${config.configName}` },
            {
              validator: (_, value) => {
                if (value === null || value === undefined) return Promise.resolve();
                if (value < 0) return Promise.reject(new Error('不能小于0'));
                if (isWeight && value > 1) return Promise.reject(new Error('权重不能大于1'));
                return Promise.resolve();
              },
            },
          ]}
        >
          {isWeight ? (
            <Slider
              min={0}
              max={1}
              step={0.05}
              marks={{
                0: '0',
                0.2: '0.2',
                0.4: '0.4',
                0.6: '0.6',
                0.8: '0.8',
                1: '1',
              }}
              tooltip={{
                formatter: (value) => `${(value || 0).toFixed(2)}${unit ? ` ${unit}` : ''}`,
              }}
            />
          ) : (
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              step={unit === '元' ? 100 : unit === 'Km' ? 1 : 0.1}
              placeholder={`请输入${config.configName}`}
              addonAfter={unit}
            />
          )}
        </Form.Item>
      );
    });
  };

  useEffect(() => {
    loadConfigData();
  }, []);

  return (
    <Fragment>
      <div style={{ width: '100%', height: 'calc(100vh - 400px)' }}>
        <Row gutter={16} style={{ height: '100%' }}>
          {/* 左侧模型导航 */}
          <Col span={6}>
            <Card title="模型导航" style={{ height: '100%' }} bodyStyle={{ padding: 0 }}>
              <Menu
                mode="inline"
                selectedKeys={[selectedModel]}
                style={{ border: 'none', height: '100%' }}
                items={generateModelMenu()}
                onClick={({ key }) => handleModelChange(key)}
              />
            </Card>
          </Col>

          {/* 右侧参数配置区 */}
          <Col span={18}>
            <Card
              loading={loading}
              title={
                <Space>
                  <SettingOutlined />
                  {selectedModel}
                </Space>
              }
              extra={
                <Space>
                  {hasWeightConfig() && (
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '8px',
                        padding: '2px 12px',
                        backgroundColor: '#f8f9fa',
                        borderRadius: '6px',
                        border: `1px solid ${getWeightColor()}`,
                        minWidth: '140px',
                      }}
                    >
                      <div style={{ textAlign: 'center' }}>
                        <div
                          style={{
                            fontSize: '14px',
                            fontWeight: 'bold',
                            color: getWeightColor(),
                          }}
                        >
                          总权重
                        </div>
                        <div
                          style={{
                            fontSize: '16px',
                            fontWeight: 'bold',
                            color: getWeightColor(),
                            lineHeight: '1.2',
                          }}
                        >
                          {totalWeight.toFixed(2)}
                        </div>
                      </div>
                      <div
                        style={{
                          width: '1px',
                          height: '30px',
                          backgroundColor: '#d9d9d9',
                        }}
                      />
                      <div style={{ textAlign: 'center' }}>
                        <div
                          style={{
                            fontSize: '12px',
                            color: '#666',
                            lineHeight: '1.2',
                          }}
                        >
                          权重状态
                        </div>
                        <div
                          style={{
                            fontSize: '12px',
                            color: getWeightColor(),
                            fontWeight: 'bold',
                            lineHeight: '1.2',
                          }}
                        >
                          {getWeightStatusText()}
                        </div>
                      </div>
                    </div>
                  )}
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={handleResetConfig}
                    loading={loading}
                    disabled={!access.hasPerms('model:config:update')}
                  >
                    重置
                  </Button>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    onClick={() => form.submit()}
                    loading={loading}
                    disabled={!access.hasPerms('model:config:update')}
                  >
                    保存配置
                  </Button>
                </Space>
              }
              style={{ height: '100%' }}
              styles={{ body: { height: 'calc(80vh)', overflowY: 'auto', padding: '25px 60px' } }}
            >
              <Form
                form={form}
                layout="vertical"
                onFinish={handleSaveConfig}
                onValuesChange={handleFormChange}
                style={{ height: '100%' }}
              >
                {renderFormComponent()}
              </Form>
            </Card>
          </Col>
        </Row>
      </div>
    </Fragment>
  );
}

export default ModelManagement;
