import React, { useState } from 'react';
import { Card, Row, Col, Form, Input, Button, Select, Slider, Tag, Alert, Statistic, Table } from 'antd';
import { SafetyOutlined, CalculatorOutlined, CalendarOutlined, BarChartOutlined } from '@ant-design/icons';
import './RiskControl.css';

const { Option } = Select;
const { Item } = Form;

const RiskControl = () => {
  const [form] = Form.useForm();
  const [positionSize, setPositionSize] = useState(0);
  const [riskLevel, setRiskLevel] = useState(50);

  // 止损策略选项
  const stopLossStrategies = [
    { value: 'fixed', label: '固定止损' },
    { value: 'moving', label: '移动止损' },
    { value: 'percent', label: '百分比止损' },
    { value: 'volatility', label: '波动率止损' }
  ];

  // 换月预警数据
  const rolloverAlerts = [
    { id: 1, symbol: '螺纹钢-RB605', expiryDate: '2026-05-15', daysLeft: 15, urgency: '中等' },
    { id: 2, symbol: '原油-SC606', expiryDate: '2026-06-20', daysLeft: 30, urgency: '低' },
    { id: 3, symbol: '铜-CU604', expiryDate: '2026-04-20', daysLeft: 5, urgency: '高' },
    { id: 4, symbol: '甲醇-MA605', expiryDate: '2026-05-10', daysLeft: 10, urgency: '中等' }
  ];

  // 风险监控数据
  const riskMetrics = [
    { name: '风险价值(VaR)', value: '12,500', unit: '元', level: '中等' },
    { name: '最大回撤', value: '8.5', unit: '%', level: '低' },
    { name: '夏普比率', value: '1.2', unit: '', level: '高' },
    { name: '仓位使用率', value: '65', unit: '%', level: '中等' }
  ];

  // 计算仓位
  const calculatePosition = (values) => {
    const { accountBalance, riskPerTrade, stopLossPercent } = values;
    const riskAmount = accountBalance * (riskPerTrade / 100);
    const position = riskAmount / (stopLossPercent / 100);
    setPositionSize(position);
  };

  // 处理表单提交
  const handleSubmit = (values) => {
    calculatePosition(values);
  };

  // 获取紧急程度颜色
  const getUrgencyColor = (urgency) => {
    if (urgency === '高') return 'red';
    if (urgency === '中等') return 'orange';
    return 'green';
  };

  // 获取风险等级颜色
  const getRiskLevelColor = (level) => {
    if (level === '高') return 'red';
    if (level === '中等') return 'orange';
    return 'green';
  };

  return (
    <div className="risk-control">
      <h2>风控管理</h2>

      {/* 止损策略设置 */}
      <Card 
        title={<span><SafetyOutlined /> 止损策略设置</span>} 
        className="risk-card"
        style={{ marginBottom: 24 }}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <Item label="止损策略" name="stopLossStrategy" rules={[{ required: true }]}>
                <Select placeholder="选择止损策略">
                  {stopLossStrategies.map(strategy => (
                    <Option key={strategy.value} value={strategy.value}>
                      {strategy.label}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col span={8}>
              <Item label="止损百分比" name="stopLossPercent" rules={[{ required: true }]}>
                <Input addonAfter="%" type="number" min={0.1} max={50} step={0.1} />
              </Item>
            </Col>
            <Col span={8}>
              <Item label="止损点位" name="stopLossPrice">
                <Input addonBefore="¥" type="number" step={0.01} />
              </Item>
            </Col>
          </Row>
          <Button type="primary" htmlType="submit" style={{ marginTop: 8 }}>
            应用止损策略
          </Button>
        </Form>
      </Card>

      {/* 仓位管理 */}
      <Card 
        title={<span><CalculatorOutlined /> 仓位管理</span>} 
        className="risk-card"
        style={{ marginBottom: 24 }}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <Item label="账户余额" name="accountBalance" rules={[{ required: true }]}>
                <Input addonBefore="¥" type="number" min={1000} step={1000} />
              </Item>
            </Col>
            <Col span={8}>
              <Item label="每笔交易风险" name="riskPerTrade" rules={[{ required: true }]}>
                <Input addonAfter="%" type="number" min={0.1} max={20} step={0.1} />
              </Item>
            </Col>
            <Col span={8}>
              <Item label="止损百分比" name="stopLossPercent" rules={[{ required: true }]}>
                <Input addonAfter="%" type="number" min={0.1} max={50} step={0.1} />
              </Item>
            </Col>
          </Row>
          <Button type="primary" htmlType="submit" style={{ marginBottom: 16 }}>
            计算仓位
          </Button>
          
          {positionSize > 0 && (
            <Card className="position-result">
              <Statistic 
                title="建议仓位大小" 
                value={positionSize.toFixed(2)} 
                prefix="¥" 
                valueStyle={{ color: '#1890ff' }}
              />
              <Statistic 
                title="风险暴露" 
                value={(positionSize * 0.05).toFixed(2)} 
                prefix="¥" 
                valueStyle={{ color: '#ff4d4f' }}
              />
              <Statistic 
                title="仓位比例" 
                value={(positionSize / form.getFieldValue('accountBalance') * 100).toFixed(2)} 
                suffix="%" 
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          )}
        </Form>

        {/* 风险偏好设置 */}
        <Card title="风险偏好设置" style={{ marginTop: 24 }}>
          <div className="risk-preference">
            <div className="risk-slider">
              <label>风险偏好: </label>
              <Slider 
                min={0} 
                max={100} 
                value={riskLevel} 
                onChange={setRiskLevel}
                marks={{
                  0: '保守',
                  50: '适中',
                  100: '激进'
                }}
              />
              <Tag color={riskLevel < 33 ? 'green' : riskLevel < 66 ? 'orange' : 'red'}>
                {riskLevel < 33 ? '保守' : riskLevel < 66 ? '适中' : '激进'}
              </Tag>
            </div>
            <Alert 
              message="风险提示" 
              description="风险偏好设置将影响系统给出的仓位建议和止损策略，请根据自身风险承受能力合理设置。" 
              type="info" 
              showIcon 
              style={{ marginTop: 16 }}
            />
          </div>
        </Card>
      </Card>

      {/* 换月预警 */}
      <Card 
        title={<span><CalendarOutlined /> 换月预警</span>} 
        className="risk-card"
        style={{ marginBottom: 24 }}
      >
        <Table 
          dataSource={rolloverAlerts} 
          columns={[
            {
              title: '合约',
              dataIndex: 'symbol',
              key: 'symbol'
            },
            {
              title: '到期日',
              dataIndex: 'expiryDate',
              key: 'expiryDate'
            },
            {
              title: '剩余天数',
              dataIndex: 'daysLeft',
              key: 'daysLeft',
              render: (days) => (
                <Tag color={days < 7 ? 'red' : days < 15 ? 'orange' : 'green'}>
                  {days} 天
                </Tag>
              )
            },
            {
              title: '紧急程度',
              dataIndex: 'urgency',
              key: 'urgency',
              render: (urgency) => (
                <Tag color={getUrgencyColor(urgency)}>
                  {urgency}
                </Tag>
              )
            },
            {
              title: '操作',
              key: 'action',
              render: () => (
                <Button type="link">查看详情</Button>
              )
            }
          ]} 
          rowKey="id"
        />
      </Card>

      {/* 风险监控 */}
      <Card 
        title={<span><BarChartOutlined /> 风险监控</span>} 
        className="risk-card"
      >
        <Row gutter={[16, 16]}>
          {riskMetrics.map((metric, index) => (
            <Col span={6} key={index}>
              <Card className="risk-metric-card">
                <Statistic 
                  title={metric.name} 
                  value={metric.value} 
                  suffix={metric.unit} 
                  valueStyle={{ color: getRiskLevelColor(metric.level) }}
                />
                <div className="risk-level">
                  <Tag color={getRiskLevelColor(metric.level)}>
                    {metric.level}风险
                  </Tag>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
        <Alert 
          message="风险监控提示" 
          description="系统会实时监控您的交易风险，当风险指标超过预警阈值时，会及时发出预警通知。" 
          type="warning" 
          showIcon 
          style={{ marginTop: 16 }}
        />
      </Card>
    </div>
  );
};

export default RiskControl;
