/**
 * [FE-AILOG-001] AI决策日志页面
 * 全链路追溯AI决策过程，支持查询、统计、链路追踪
 * AI注意: 此页面用于展示AI决策日志，支持决策追溯和分析
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  DatePicker,
  Select,
  Input,
  Row,
  Col,
  Statistic,
  Tooltip,
  Drawer,
  Timeline,
  Descriptions,
  Badge,
  Spin,
  message,
  Typography,
  Tabs,
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  LinkOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  BarChartOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import { Line, Pie } from '@ant-design/charts';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Search } = Input;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

// 决策类型
const DECISION_TYPES = [
  { value: 'PRICING', label: '定价决策', color: 'blue' },
  { value: 'INVENTORY', label: '库存决策', color: 'cyan' },
  { value: 'AD_OPTIMIZE', label: '广告优化', color: 'purple' },
  { value: 'PRODUCT_SELECT', label: '选品决策', color: 'green' },
  { value: 'LOGISTICS', label: '物流决策', color: 'orange' },
  { value: 'RISK_CONTROL', label: '风控决策', color: 'red' },
  { value: 'CUSTOMER_SERVICE', label: '客服决策', color: 'pink' },
  { value: 'SETTLEMENT', label: '结算决策', color: 'gold' },
  { value: 'OTHER', label: '其他', color: 'default' },
];

// 决策状态
const DECISION_STATUS = {
  PENDING: { label: '待执行', color: 'default', icon: <ClockCircleOutlined /> },
  EXECUTING: { label: '执行中', color: 'processing', icon: <ClockCircleOutlined /> },
  SUCCESS: { label: '成功', color: 'success', icon: <CheckCircleOutlined /> },
  FAILED: { label: '失败', color: 'error', icon: <CloseCircleOutlined /> },
  REJECTED: { label: '已拒绝', color: 'warning', icon: <ExclamationCircleOutlined /> },
  ROLLED_BACK: { label: '已回滚', color: 'default', icon: <ExclamationCircleOutlined /> },
};

// 模拟数据
const MOCK_LOGS = [
  {
    id: 'ADL-1710851200000-abc123',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    task_id: 'TASK-001',
    trace_id: 'TRACE-1710851200000-xyz789',
    decision_type: 'PRICING',
    business_type: 'TOC',
    status: 'SUCCESS',
    input_data: {
      context: { product_id: 'P001', current_price: 99.99, competitor_price: 89.99 },
      parameters: { min_margin: 0.2, max_discount: 0.1 },
      constraints: { max_price: 120, min_price: 80 },
    },
    output_data: {
      decision: '降价至89.99',
      confidence: 0.92,
      reasoning: '竞争对手价格较低，建议降价保持竞争力',
      alternatives: [
        { option: '维持原价', score: 0.65 },
        { option: '降价至89.99', score: 0.92 },
        { option: '降价至85.99', score: 0.78 },
      ],
      expected_result: { sales_increase: 0.15, margin_impact: -0.05 },
    },
    execution_result: {
      success: true,
      actual_result: { new_price: 89.99, sales_change: 0.18 },
      deviation: 0.03,
      execution_time: 1.2,
    },
    created_at: '2026-03-20T10:00:00Z',
    updated_at: '2026-03-20T10:01:30Z',
    executed_at: '2026-03-20T10:00:05Z',
    completed_at: '2026-03-20T10:01:30Z',
  },
  {
    id: 'ADL-1710851300000-def456',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    task_id: 'TASK-002',
    trace_id: 'TRACE-1710851300000-uvw456',
    decision_type: 'INVENTORY',
    business_type: 'TOB',
    status: 'SUCCESS',
    input_data: {
      context: { sku_id: 'SKU-001', current_stock: 50, sales_velocity: 10 },
      parameters: { safety_stock: 20, lead_time: 7 },
      constraints: { max_order: 500, budget: 10000 },
    },
    output_data: {
      decision: '补货200件',
      confidence: 0.88,
      reasoning: '库存低于安全库存，建议补货',
      alternatives: [
        { option: '不补货', score: 0.45 },
        { option: '补货100件', score: 0.72 },
        { option: '补货200件', score: 0.88 },
      ],
      expected_result: { stock_days: 25, cost: 8000 },
    },
    execution_result: {
      success: true,
      actual_result: { ordered: 200, cost: 8000 },
      deviation: 0,
      execution_time: 2.5,
    },
    created_at: '2026-03-20T09:30:00Z',
    updated_at: '2026-03-20T09:32:00Z',
    executed_at: '2026-03-20T09:30:10Z',
    completed_at: '2026-03-20T09:32:00Z',
  },
  {
    id: 'ADL-1710851400000-ghi789',
    tenant_id: 'tenant-001',
    shop_id: 'shop-002',
    task_id: 'TASK-003',
    trace_id: 'TRACE-1710851400000-rst123',
    decision_type: 'AD_OPTIMIZE',
    business_type: 'TOC',
    status: 'FAILED',
    input_data: {
      context: { campaign_id: 'CAMP-001', current_bid: 2.5, ctr: 0.03 },
      parameters: { target_cpa: 50, max_bid: 5 },
      constraints: { daily_budget: 500 },
    },
    output_data: {
      decision: '提高出价至3.0',
      confidence: 0.75,
      reasoning: 'CTR低于预期，建议提高出价',
      alternatives: [
        { option: '维持出价', score: 0.55 },
        { option: '提高出价至3.0', score: 0.75 },
      ],
      expected_result: { ctr_improvement: 0.02, cost_increase: 0.2 },
    },
    execution_result: {
      success: false,
      actual_result: {},
      deviation: 0,
      execution_time: 0.8,
      error_message: 'API调用失败，平台返回错误',
    },
    created_at: '2026-03-20T09:00:00Z',
    updated_at: '2026-03-20T09:01:00Z',
    executed_at: '2026-03-20T09:00:05Z',
    completed_at: '2026-03-20T09:01:00Z',
  },
  {
    id: 'ADL-1710851500000-jkl012',
    tenant_id: 'tenant-001',
    shop_id: 'shop-001',
    task_id: 'TASK-004',
    trace_id: 'TRACE-1710851500000-mno345',
    decision_type: 'PRODUCT_SELECT',
    business_type: 'TOC',
    status: 'REJECTED',
    input_data: {
      context: { category: '电子产品', price_range: [50, 100] },
      parameters: { min_roi: 0.3, min_rating: 4.5 },
      constraints: { max_competition: 'MEDIUM' },
    },
    output_data: {
      decision: '选择商品P-NEW-001',
      confidence: 0.85,
      reasoning: 'ROI预期30%，评分4.6，符合选品标准',
      alternatives: [
        { option: '选择商品P-NEW-002', score: 0.78 },
        { option: '选择商品P-NEW-001', score: 0.85 },
      ],
      expected_result: { roi: 0.32, sales_potential: 'HIGH' },
    },
    human_intervention: {
      operator_id: 'USER-001',
      operator_name: '张三',
      action: 'REJECT',
      comment: '该供应商历史质量不稳定，暂不选品',
      timestamp: '2026-03-20T08:45:00Z',
    },
    created_at: '2026-03-20T08:30:00Z',
    updated_at: '2026-03-20T08:45:00Z',
    executed_at: '2026-03-20T08:30:05Z',
    completed_at: '2026-03-20T08:45:00Z',
  },
  {
    id: 'ADL-1710851600000-mno345',
    tenant_id: 'tenant-001',
    shop_id: 'shop-002',
    task_id: 'TASK-005',
    trace_id: 'TRACE-1710851600000-pqr678',
    decision_type: 'RISK_CONTROL',
    business_type: 'TOB',
    status: 'SUCCESS',
    input_data: {
      context: { order_id: 'ORDER-001', amount: 50000, customer_history: 'GOOD' },
      parameters: { risk_threshold: 0.3 },
      constraints: { max_single_order: 100000 },
    },
    output_data: {
      decision: '通过审核',
      confidence: 0.95,
      reasoning: '客户历史良好，金额在限额内',
      alternatives: [
        { option: '拒绝订单', score: 0.15 },
        { option: '人工审核', score: 0.45 },
        { option: '通过审核', score: 0.95 },
      ],
      expected_result: { risk_score: 0.1 },
    },
    execution_result: {
      success: true,
      actual_result: { approved: true, risk_score: 0.1 },
      deviation: 0,
      execution_time: 0.5,
    },
    created_at: '2026-03-20T08:00:00Z',
    updated_at: '2026-03-20T08:00:30Z',
    executed_at: '2026-03-20T08:00:05Z',
    completed_at: '2026-03-20T08:00:30Z',
  },
];

// 模拟统计数据
const MOCK_STATISTICS = {
  total_count: 156,
  success_count: 128,
  failed_count: 18,
  rejected_count: 10,
  success_rate: 82,
  avg_execution_time: 1.85,
  by_type: {
    PRICING: { count: 45, success_rate: 88 },
    INVENTORY: { count: 38, success_rate: 92 },
    AD_OPTIMIZE: { count: 32, success_rate: 75 },
    PRODUCT_SELECT: { count: 28, success_rate: 78 },
    LOGISTICS: { count: 8, success_rate: 95 },
    RISK_CONTROL: { count: 5, success_rate: 100 },
  },
  by_day: [
    { date: '2026-03-15', count: 20, success_count: 16 },
    { date: '2026-03-16', count: 25, success_count: 21 },
    { date: '2026-03-17', count: 30, success_count: 25 },
    { date: '2026-03-18', count: 28, success_count: 23 },
    { date: '2026-03-19', count: 32, success_count: 26 },
    { date: '2026-03-20', count: 21, success_count: 17 },
  ],
};

const AIDecisionLogPage: React.FC = () => {
  const [logs, setLogs] = useState<any[]>([]);
  const [statistics, setStatistics] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState<any>(null);
  const [filters, setFilters] = useState({
    decision_type: undefined,
    status: undefined,
    date_range: null,
    search: '',
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 加载数据
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setLogs(MOCK_LOGS);
      setStatistics(MOCK_STATISTICS);
      setPagination(prev => ({ ...prev, total: MOCK_LOGS.length }));
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  // 表格列定义
  const columns = [
    {
      title: '决策ID',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      render: (id: string) => (
        <Text copyable={{ text: id }} style={{ fontFamily: 'monospace' }}>
          {id.substring(0, 20)}...
        </Text>
      ),
    },
    {
      title: '决策类型',
      dataIndex: 'decision_type',
      key: 'decision_type',
      width: 120,
      render: (type: string) => {
        const config = DECISION_TYPES.find(t => t.value === type);
        return <Tag color={config?.color}>{config?.label || type}</Tag>;
      },
    },
    {
      title: '业务类型',
      dataIndex: 'business_type',
      key: 'business_type',
      width: 100,
      render: (type: string) => (
        <Tag color={type === 'TOC' ? 'blue' : 'purple'}>
          {type === 'TOC' ? 'B2C' : 'B2B'}
        </Tag>
      ),
    },
    {
      title: '决策内容',
      dataIndex: 'output_data',
      key: 'decision',
      render: (data: any) => (
        <Tooltip title={data?.reasoning}>
          <Text ellipsis style={{ maxWidth: 200 }}>
            {data?.decision}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '置信度',
      dataIndex: 'output_data',
      key: 'confidence',
      width: 100,
      render: (data: any) => (
        <Badge
          count={`${Math.round((data?.confidence || 0) * 100)}%`}
          style={{
            backgroundColor: (data?.confidence || 0) >= 0.9 ? '#52c41a' :
              (data?.confidence || 0) >= 0.7 ? '#faad14' : '#f5222d',
          }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: keyof typeof DECISION_STATUS) => {
        const config = DECISION_STATUS[status];
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.label}
          </Tag>
        );
      },
    },
    {
      title: '执行时间',
      dataIndex: 'execution_result',
      key: 'execution_time',
      width: 100,
      render: (result: any) => result ? `${result.execution_time}s` : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_: any, record: any) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedLog(record);
              setDetailVisible(true);
            }}
          >
            详情
          </Button>
          <Tooltip title="查看链路">
            <Button
              size="small"
              icon={<LinkOutlined />}
              onClick={() => message.info('链路追踪功能开发中')}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 趋势图配置
  const trendConfig = {
    data: statistics?.by_day || [],
    xField: 'date',
    yField: 'count',
    seriesField: 'type',
    smooth: true,
    point: {
      size: 4,
      shape: 'circle',
    },
    lineStyle: {
      lineWidth: 2,
    },
    tooltip: {
      showMarkers: true,
    },
    legend: {
      position: 'top',
    },
  };

  // 类型分布图配置
  const typePieConfig = {
    data: statistics ? Object.entries(statistics.by_type).map(([type, data]: [string, any]) => ({
      type: DECISION_TYPES.find(t => t.value === type)?.label || type,
      value: data.count,
    })) : [],
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    legend: {
      position: 'right',
    },
  };

  return (
    <div style={{ padding: 24 }}>
      <Title level={2}>AI决策日志</Title>
      <Text type="secondary">全链路追溯AI决策过程，支持决策分析和审计</Text>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginTop: 24, marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="总决策数"
              value={statistics?.total_count || 0}
              prefix={<BarChartOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="成功数"
              value={statistics?.success_count || 0}
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="失败数"
              value={statistics?.failed_count || 0}
              valueStyle={{ color: '#cf1322' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="拒绝数"
              value={statistics?.rejected_count || 0}
              valueStyle={{ color: '#faad14' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="成功率"
              value={statistics?.success_rate || 0}
              suffix="%"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="平均执行时间"
              value={statistics?.avg_execution_time || 0}
              suffix="s"
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={16}>
          <Card title="决策趋势" extra={<LineChartOutlined />}>
            {statistics ? (
              <Line {...trendConfig} />
            ) : (
              <Spin />
            )}
          </Card>
        </Col>
        <Col span={8}>
          <Card title="决策类型分布">
            {statistics ? (
              <Pie {...typePieConfig} />
            ) : (
              <Spin />
            )}
          </Card>
        </Col>
      </Row>

      {/* 筛选区域 */}
      <Card style={{ marginBottom: 24 }}>
        <Space wrap>
          <Select
            placeholder="决策类型"
            style={{ width: 150 }}
            allowClear
            value={filters.decision_type}
            onChange={value => setFilters(prev => ({ ...prev, decision_type: value }))}
          >
            {DECISION_TYPES.map(type => (
              <Option key={type.value} value={type.value}>{type.label}</Option>
            ))}
          </Select>
          <Select
            placeholder="状态"
            style={{ width: 120 }}
            allowClear
            value={filters.status}
            onChange={value => setFilters(prev => ({ ...prev, status: value }))}
          >
            {Object.entries(DECISION_STATUS).map(([key, config]) => (
              <Option key={key} value={key}>{config.label}</Option>
            ))}
          </Select>
          <RangePicker
            value={filters.date_range}
            onChange={dates => setFilters(prev => ({ ...prev, date_range: dates }))}
          />
          <Search
            placeholder="搜索决策ID/TraceID"
            style={{ width: 250 }}
            value={filters.search}
            onChange={e => setFilters(prev => ({ ...prev, search: e.target.value }))}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchData}>
            查询
          </Button>
          <Button icon={<ReloadOutlined />} onClick={fetchData}>
            刷新
          </Button>
        </Space>
      </Card>

      {/* 表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`,
          }}
          onChange={setPagination}
          scroll={{ x: 1500 }}
        />
      </Card>

      {/* 详情抽屉 */}
      <Drawer
        title="决策详情"
        width={800}
        visible={detailVisible}
        onClose={() => setDetailVisible(false)}
      >
        {selectedLog && (
          <Tabs defaultActiveKey="basic">
            <TabPane tab="基本信息" key="basic">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="决策ID">{selectedLog.id}</Descriptions.Item>
                <Descriptions.Item label="Trace ID">{selectedLog.trace_id}</Descriptions.Item>
                <Descriptions.Item label="决策类型">
                  {DECISION_TYPES.find(t => t.value === selectedLog.decision_type)?.label}
                </Descriptions.Item>
                <Descriptions.Item label="业务类型">
                  {selectedLog.business_type === 'TOC' ? 'B2C' : 'B2B'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={DECISION_STATUS[selectedLog.status as keyof typeof DECISION_STATUS].color}>
                    {DECISION_STATUS[selectedLog.status as keyof typeof DECISION_STATUS].label}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="置信度">
                  {Math.round(selectedLog.output_data?.confidence * 100)}%
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {moment(selectedLog.created_at).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="完成时间">
                  {selectedLog.completed_at 
                    ? moment(selectedLog.completed_at).format('YYYY-MM-DD HH:mm:ss')
                    : '-'}
                </Descriptions.Item>
              </Descriptions>

              <Title level={5} style={{ marginTop: 24 }}>决策结果</Title>
              <Card>
                <Text strong>{selectedLog.output_data?.decision}</Text>
                <br />
                <Text type="secondary">{selectedLog.output_data?.reasoning}</Text>
              </Card>
            </TabPane>

            <TabPane tab="输入参数" key="input">
              <Card title="上下文">
                <pre>{JSON.stringify(selectedLog.input_data?.context, null, 2)}</pre>
              </Card>
              <Card title="参数" style={{ marginTop: 16 }}>
                <pre>{JSON.stringify(selectedLog.input_data?.parameters, null, 2)}</pre>
              </Card>
              <Card title="约束条件" style={{ marginTop: 16 }}>
                <pre>{JSON.stringify(selectedLog.input_data?.constraints, null, 2)}</pre>
              </Card>
            </TabPane>

            <TabPane tab="决策选项" key="alternatives">
              <Timeline>
                {selectedLog.output_data?.alternatives?.map((alt: any, index: number) => (
                  <Timeline.Item key={index}>
                    <Text strong>{alt.option}</Text>
                    <br />
                    <Text type="secondary">评分: {Math.round(alt.score * 100)}%</Text>
                  </Timeline.Item>
                ))}
              </Timeline>
            </TabPane>

            <TabPane tab="执行结果" key="execution">
              {selectedLog.execution_result ? (
                <>
                  <Descriptions bordered column={1}>
                    <Descriptions.Item label="执行成功">
                      {selectedLog.execution_result.success ? (
                        <Tag color="success">是</Tag>
                      ) : (
                        <Tag color="error">否</Tag>
                      )}
                    </Descriptions.Item>
                    <Descriptions.Item label="执行时间">
                      {selectedLog.execution_result.execution_time}s
                    </Descriptions.Item>
                    <Descriptions.Item label="偏差">
                      {Math.round(selectedLog.execution_result.deviation * 100)}%
                    </Descriptions.Item>
                    {selectedLog.execution_result.error_message && (
                      <Descriptions.Item label="错误信息">
                        <Text type="danger">{selectedLog.execution_result.error_message}</Text>
                      </Descriptions.Item>
                    )}
                  </Descriptions>
                  <Card title="实际结果" style={{ marginTop: 16 }}>
                    <pre>{JSON.stringify(selectedLog.execution_result.actual_result, null, 2)}</pre>
                  </Card>
                </>
              ) : (
                <Text type="secondary">暂无执行结果</Text>
              )}
            </TabPane>

            {selectedLog.human_intervention && (
              <TabPane tab="人工干预" key="intervention">
                <Descriptions bordered column={1}>
                  <Descriptions.Item label="操作人">
                    {selectedLog.human_intervention.operator_name}
                  </Descriptions.Item>
                  <Descriptions.Item label="操作类型">
                    <Tag color="blue">{selectedLog.human_intervention.action}</Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="备注">
                    {selectedLog.human_intervention.comment}
                  </Descriptions.Item>
                  <Descriptions.Item label="操作时间">
                    {moment(selectedLog.human_intervention.timestamp).format('YYYY-MM-DD HH:mm:ss')}
                  </Descriptions.Item>
                </Descriptions>
              </TabPane>
            )}
          </Tabs>
        )}
      </Drawer>
    </div>
  );
};

export default AIDecisionLogPage;
