/**
 * @name 两级运营数据展示页
 *
 */
import React, { useState, useEffect, useMemo } from 'react';
import {
  Layout,
  Card,
  Radio,
  DatePicker,
  Select,
  Tabs,
  Table,
  Typography,
  Space,
  ConfigProvider,
  Tag,
} from 'antd';
import type { TableProps } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import 'dayjs/locale/zh-cn';
import locale from 'antd/locale/zh_CN';
import { ColumnType } from 'antd/es/table';
import './style.css';

// 设置 dayjs 语言
dayjs.locale('zh-cn');

const { Content } = Layout;
const { Title } = Typography;
const { Option } = Select;

// --- Mock Data & Constants ---

const CITIES = [
  '哈尔滨',
  '齐齐哈尔',
  '牡丹江',
  '佳木斯',
  '大庆',
  '鸡西',
  '双鸭山',
  '伊春',
  '七台河',
  '鹤岗',
  '黑河',
  '绥化',
  '大兴安岭',
];

const TASK_TYPES = ['朋友圈', '1V1群发'];

// Mock Data Types
interface SummaryData {
  key: string;
  city: string;
  momentsCount: number;
  groupMsgCount: number;
  momentsInteraction: number;
  groupMsgInteraction: number;
  isTotal?: boolean;
}

interface DetailData {
  key: string;
  city: string;
  taskType: string;
  sendDate: string;
  interactionDate: string;
  interactionCount: number;
}

// --- Helper Functions ---

const generateSummaryData = (cities: string[]): SummaryData[] => {
  const data = cities.map((city) => ({
    key: city,
    city,
    momentsCount: Math.floor(Math.random() * 10),
    groupMsgCount: Math.floor(Math.random() * 10),
    momentsInteraction: Math.floor(Math.random() * 50),
    groupMsgInteraction: Math.floor(Math.random() * 30),
  }));

  // Calculate Total
  const total = data.reduce(
    (acc, curr) => ({
      momentsCount: acc.momentsCount + curr.momentsCount,
      groupMsgCount: acc.groupMsgCount + curr.groupMsgCount,
      momentsInteraction: acc.momentsInteraction + curr.momentsInteraction,
      groupMsgInteraction: acc.groupMsgInteraction + curr.groupMsgInteraction,
    }),
    {
      momentsCount: 0,
      groupMsgCount: 0,
      momentsInteraction: 0,
      groupMsgInteraction: 0,
    }
  );

  return [
    ...data,
    {
      key: 'total',
      city: '全省合计',
      ...total,
      isTotal: true,
    },
  ];
};

const generateDetailData = (cities: string[], date: Dayjs, timeLevel: string): DetailData[] => {
  const data: DetailData[] = [];
  const count = 20 + Math.floor(Math.random() * 30); // Random number of rows

  for (let i = 0; i < count; i++) {
    const city = cities[Math.floor(Math.random() * cities.length)];
    const taskType = TASK_TYPES[Math.floor(Math.random() * TASK_TYPES.length)];
    const sendDate = date.format('YYYY-MM-DD'); // Simplified for demo
    const interactionDate = Math.random() > 0.3 ? date.add(Math.floor(Math.random() * 3), 'day').format('YYYY-MM-DD') : '-';
    
    data.push({
      key: `detail-${i}`,
      city,
      taskType,
      sendDate,
      interactionDate,
      interactionCount: Math.floor(Math.random() * 20),
    });
  }
  return data;
};

// --- Main Component ---

const TwoLevelOpsStats: React.FC = () => {
  // State
  const [timeLevel, setTimeLevel] = useState<'date' | 'week' | 'month'>('date');
  const [selectedDate, setSelectedDate] = useState<Dayjs>(dayjs('2026-03-13'));
  const [selectedCities, setSelectedCities] = useState<string[]>(['全省']);
  const [activeTab, setActiveTab] = useState<string>('summary');
  const [loading, setLoading] = useState<boolean>(false);
  
  // Data State
  const [summaryData, setSummaryData] = useState<SummaryData[]>([]);
  const [detailData, setDetailData] = useState<DetailData[]>([]);

  // Effect to load data
  useEffect(() => {
    setLoading(true);
    // Simulate API call
    setTimeout(() => {
      const citiesToUse = selectedCities.includes('全省') ? CITIES : selectedCities;
      
      setSummaryData(generateSummaryData(citiesToUse));
      setDetailData(generateDetailData(citiesToUse, selectedDate, timeLevel));
      
      setLoading(false);
    }, 600);
  }, [timeLevel, selectedDate, selectedCities]);

  // Handlers
  const handleTimeLevelChange = (e: any) => {
    setTimeLevel(e.target.value);
  };

  const handleCityChange = (values: string[]) => {
    if (values.includes('全省')) {
      if (selectedCities.includes('全省') && values.length > 1) {
        // Deselecting specific cities while "All" was selected, or selecting "All" again?
        // Logic: If "All" is selected, it clears others. If others selected, clear "All".
        // But the requirement says: Select "All" = Select All Cities. 
        // Let's simplify: "全省" is a special option that acts as a reset/select-all.
        // If user clicks "全省", set to ['全省'].
        // If user clicks others while "全省" is active, remove "全省".
        if (values[values.length - 1] === '全省') {
            setSelectedCities(['全省']);
        } else {
            setSelectedCities(values.filter(v => v !== '全省'));
        }
      } else {
         // If "All" was not selected and now it is (or it's the only one), set to "All"
         if (values.includes('全省')) {
            setSelectedCities(['全省']);
         } else {
            // Normal selection
            setSelectedCities(values);
         }
      }
    } else {
        // "All" not involved
        if (values.length === 0) {
             setSelectedCities(['全省']); // Default to all if empty
        } else {
             setSelectedCities(values);
        }
    }
  };

  // Columns Configuration
  const summaryColumns: TableProps<SummaryData>['columns'] = [
    {
      title: '地市',
      dataIndex: 'city',
      key: 'city',
      sorter: (a, b) => {
        if (a.isTotal) return 0;
        if (b.isTotal) return 0;
        return a.city.localeCompare(b.city, 'zh-Hans-CN', { sensitivity: 'accent' });
      },
      render: (text, record) => record.isTotal ? <strong>{text}</strong> : text,
    },
    {
      title: '朋友圈发布次数',
      dataIndex: 'momentsCount',
      key: 'momentsCount',
      sorter: (a, b) => a.momentsCount - b.momentsCount,
      align: 'right',
      render: (val, record) => record.isTotal ? <strong>{val}</strong> : val,
    },
    {
      title: '1V1群发次数',
      dataIndex: 'groupMsgCount',
      key: 'groupMsgCount',
      sorter: (a, b) => a.groupMsgCount - b.groupMsgCount,
      align: 'right',
      render: (val, record) => record.isTotal ? <strong>{val}</strong> : val,
    },
    {
      title: '朋友圈互动量',
      dataIndex: 'momentsInteraction',
      key: 'momentsInteraction',
      sorter: (a, b) => a.momentsInteraction - b.momentsInteraction,
      align: 'right',
      render: (val, record) => record.isTotal ? <strong>{val}</strong> : val,
    },
    {
      title: '1V1群发互动量',
      dataIndex: 'groupMsgInteraction',
      key: 'groupMsgInteraction',
      sorter: (a, b) => a.groupMsgInteraction - b.groupMsgInteraction,
      align: 'right',
      render: (val, record) => record.isTotal ? <strong>{val}</strong> : val,
    },
  ];

  const detailColumns: TableProps<DetailData>['columns'] = [
    {
      title: '地市',
      dataIndex: 'city',
      key: 'city',
      width: 120,
    },
    {
      title: '任务类型',
      dataIndex: 'taskType',
      key: 'taskType',
      width: 120,
      render: (text) => (
        <Tag color={text === '朋友圈' ? 'blue' : 'green'}>{text}</Tag>
      ),
    },
    {
      title: '发送日期',
      dataIndex: 'sendDate',
      key: 'sendDate',
      width: 150,
    },
    {
      title: '互动发生日期',
      dataIndex: 'interactionDate',
      key: 'interactionDate',
      width: 150,
    },
    {
      title: '互动量',
      dataIndex: 'interactionCount',
      key: 'interactionCount',
      align: 'right',
    },
  ];

  // Render
  return (
    <ConfigProvider locale={locale}>
      <Layout style={{ minHeight: '100vh', padding: '24px', background: '#f0f2f5' }}>
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          
          {/* 顶部筛选区 */}
          <Card bordered={false} bodyStyle={{ padding: '24px' }}>
            <Space size="large" wrap>
              <Space>
                <span style={{ fontWeight: 500 }}>时间粒度：</span>
                <Radio.Group value={timeLevel} onChange={handleTimeLevelChange} buttonStyle="solid">
                  <Radio.Button value="date">日</Radio.Button>
                  <Radio.Button value="week">周</Radio.Button>
                  <Radio.Button value="month">月</Radio.Button>
                </Radio.Group>
              </Space>

              <Space>
                <span style={{ fontWeight: 500 }}>时间选择：</span>
                <DatePicker 
                  picker={timeLevel} 
                  value={selectedDate} 
                  onChange={(date) => date && setSelectedDate(date)}
                  allowClear={false}
                  style={{ width: 200 }}
                />
              </Space>

              <Space>
                <span style={{ fontWeight: 500 }}>地市：</span>
                <Select
                  mode="multiple"
                  style={{ minWidth: 200, maxWidth: 400 }}
                  placeholder="选择地市"
                  value={selectedCities}
                  onChange={handleCityChange}
                  maxTagCount="responsive"
                >
                  <Option key="全省" value="全省">全省</Option>
                  {CITIES.map(city => (
                    <Option key={city} value={city}>{city}</Option>
                  ))}
                </Select>
              </Space>
            </Space>
          </Card>

          {/* 内容展示区 */}
          <Card bordered={false} bodyStyle={{ padding: '0 24px 24px' }}>
            <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              items={[
                {
                  key: 'summary',
                  label: '地市汇总表',
                  children: (
                    <Table 
                      columns={summaryColumns} 
                      dataSource={summaryData} 
                      loading={loading}
                      pagination={false}
                      rowKey="key"
                      rowClassName={(record) => record.isTotal ? 'bg-gray-50' : ''}
                      summary={() => null} // We use a custom row for total
                    />
                  ),
                },
                {
                  key: 'detail',
                  label: '明细表',
                  children: (
                    <Table 
                      columns={detailColumns} 
                      dataSource={detailData} 
                      loading={loading}
                      rowKey="key"
                      pagination={{ pageSize: 10, showTotal: (total) => `共 ${total} 条` }}
                    />
                  ),
                },
              ]}
            />
          </Card>
        </Space>
      </Layout>
    </ConfigProvider>
  );
};

export default TwoLevelOpsStats;
