import React, { useState } from 'react';
import { Button, DatePicker, Select, InputNumber, Table, Tag, Avatar } from 'antd';
import { 
    CalendarOutlined, 
    TeamOutlined, 
    UserOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined
} from '@ant-design/icons';
import moment from 'moment';
import StandardTable from '@/components/StandardTable';
import styles from './DutySchedule.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

const DutySchedule = () => {
    // 当前周的起始日期
    const [currentWeekStart, setCurrentWeekStart] = useState(moment().startOf('week'));
    const [selectedRange, setSelectedRange] = useState([moment(), moment()]);
    const [shiftType, setShiftType] = useState('早班');
    const [personCount, setPersonCount] = useState(2);
    const [specialty, setSpecialty] = useState('无特殊要求');
    
    // 生成当前周的日期数组
    const getWeekDates = (startDate) => {
        const dates = [];
        for (let i = 0; i < 7; i++) {
            dates.push(moment(startDate).add(i, 'days'));
        }
        return dates;
    };
    
    const weekDates = getWeekDates(currentWeekStart);
    
    // 周导航
    const handlePrevWeek = () => {
        setCurrentWeekStart(moment(currentWeekStart).subtract(1, 'week'));
    };
    
    const handleNextWeek = () => {
        setCurrentWeekStart(moment(currentWeekStart).add(1, 'week'));
    };
    
    const handleThisWeek = () => {
        setCurrentWeekStart(moment().startOf('week'));
    };
    
    // 模拟排班数据
    const scheduleData = {
        '2023-10-16': {
            morning: [{ name: '何宇', status: 'onduty' }],
            middle: [],
            evening: [{ name: '何宇', status: 'leave' }]
        },
        '2023-10-17': {
            morning: [],
            middle: [{ name: '张三', status: 'onduty' }, { name: '李四', status: 'vacation' }],
            evening: []
        },
        '2023-10-18': {
            morning: [{ name: '王在在', status: 'onduty' }, { name: '李四', status: 'leave' }],
            middle: [],
            evening: [{ name: '王在在', status: 'onduty' }, { name: '李四', status: 'leave' }]
        },
        '2023-10-19': {
            morning: [],
            middle: [{ name: '何宇', status: 'onduty' }],
            evening: []
        },
        '2023-10-20': {
            morning: [],
            middle: [{ name: '何宇', status: 'onduty' }],
            evening: [{ name: '暂无', status: 'none' }, { name: '安排', status: 'none' }]
        },
        '2023-10-21': {
            morning: [{ name: '张三', status: 'onduty' }, { name: '李四', status: 'vacation' }],
            middle: [],
            evening: [{ name: '马婧', status: 'vacation' }, { name: '冯俊', status: 'leave' }]
        },
        '2023-10-22': {
            morning: [{ name: '暂无', status: 'none' }, { name: '安排', status: 'none' }],
            middle: [],
            evening: [{ name: '何宇', status: 'onduty' }]
        }
    };
    
    // 获取单元格数据
    const getCellData = (date, shift) => {
        const dateKey = date.format('YYYY-MM-DD');
        const data = scheduleData[dateKey];
        if (!data) return [];
        return data[shift] || [];
    };
    
    // 渲染单元格
    const renderCell = (date, shift) => {
        const cellData = getCellData(date, shift);
        
        if (cellData.length === 0) {
            return <div className={styles.emptyCell}></div>;
        }
        
        return (
            <div className={styles.cellContent}>
                {cellData.map((item, index) => (
                    <div key={index} className={styles.personItem}>
                        <div className={styles.personName}>{item.name}</div>
                        <div className={`${styles.statusTag} ${styles[item.status]}`}>
                            {item.status === 'onduty' && '在岗'}
                            {item.status === 'leave' && '休假'}
                            {item.status === 'vacation' && '请假'}
                            {item.status === 'none' && ''}
                        </div>
                    </div>
                ))}
            </div>
        );
    };
    
    // 获取单元格背景色类名
    const getCellClassName = (date, shift) => {
        const cellData = getCellData(date, shift);
        if (cellData.length === 0) return '';
        
        const status = cellData[0].status;
        const allSameStatus = cellData.every(item => item.status === status);
        
        if (allSameStatus) {
            return styles[`bg_${status}`];
        }
        
        return styles.bg_mixed;
    };
    
    // 底部表格数据
    const [tablePagination, setTablePagination] = useState({
        current: 1,
        currentPage: 1,
        pageSize: 10,
        total: 48,
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条`,
    });
    
    const tableColumns = [
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            width: 120,
        },
        {
            title: '班次',
            dataIndex: 'shift',
            key: 'shift',
            width: 150,
        },
        {
            title: '值班人员',
            dataIndex: 'person',
            key: 'person',
            width: 100,
        },
        {
            title: '职位',
            dataIndex: 'position',
            key: 'position',
            width: 150,
        },
        {
            title: '专业技能',
            dataIndex: 'skills',
            key: 'skills',
            width: 180,
        },
        {
            title: '岗位类型',
            dataIndex: 'type',
            key: 'type',
            width: 100,
        },
        {
            title: '联系方式',
            dataIndex: 'contact',
            key: 'contact',
            width: 130,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 80,
            align: 'center',
            render: (status) => {
                const colorMap = {
                    '请假': 'error',
                    '休假': 'warning',
                    '在岗': 'success'
                };
                return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            align: 'center',
            render: (_, record) => (
                <div className={styles.tableActions}>
                    <Button type="link" size="small" style={{ padding: 0 }}>编辑</Button>
                    <Button type="link" size="small" danger style={{ padding: 0 }}>删除</Button>
                </div>
            ),
        },
    ];
    
    const tableData = [
        {
            key: '1',
            date: '2025-10-13',
            shift: '早班 (08:00-16:00)',
            person: '钱洛西',
            position: '应急响应专家',
            skills: '网络安全、系统运维',
            type: '常规岗',
            contact: '15286758708',
            status: '请假'
        },
        {
            key: '2',
            date: '2025-10-12',
            shift: '中班 (16:00-24:00)',
            person: '冯俊',
            position: '数据分析师',
            skills: '数据分析、风险评估',
            type: '专业岗',
            contact: '15070108237',
            status: '休假'
        },
        {
            key: '3',
            date: '2025-10-10',
            shift: '晚班 (00:00-08:00)',
            person: '何余',
            position: '系统管理员',
            skills: '服务器管理、网络管理',
            type: '常规岗',
            contact: '13726421306',
            status: '在岗'
        },
    ];
    
    // 可用值班人员数据
    const availablePersons = [
        { id: 1, name: '李华', description: '电气专业、高级资质' },
        { id: 2, name: '王芳', description: '通讯专业、高级资质' },
        { id: 3, name: '孙琦', description: '电气专业、中级资质' },
    ];
    
    return (
        <div className={styles.pageContainer}>
            {/* 顶部区域 */}
            <div className={styles.topSection}>
                {/* 左侧：排班表 */}
                <div className={styles.scheduleSection}>
                    <div className={styles.sectionHeader}>
                        <div className={styles.titleBar}></div>
                        <h2 className={styles.sectionTitle}>值班排班表</h2>
                    </div>
                    
                    {/* 控制栏 */}
                    <div className={styles.toolbar}>
                        <div className={styles.toolbarLeft}>
                            <div className={styles.legend}>
                                <span className={styles.legendItem}>
                                    <span className={`${styles.legendDot} ${styles.onduty}`}></span>
                                    在岗
                                </span>
                                <span className={styles.legendItem}>
                                    <span className={`${styles.legendDot} ${styles.leave}`}></span>
                                    休假
                                </span>
                                <span className={styles.legendItem}>
                                    <span className={`${styles.legendDot} ${styles.vacation}`}></span>
                                    请假
                                </span>
                                <span className={styles.legendItem}>
                                    <span className={`${styles.legendDot} ${styles.none}`}></span>
                                    暂无安排
                                </span>
                            </div>
                        </div>
                        
                        <div className={styles.toolbarRight}>
                            <span className={styles.dateRange}>
                                {currentWeekStart.format('YYYY-M-D')} 至 {moment(currentWeekStart).add(6, 'days').format('YYYY-M-D')}
                            </span>
                            <div className={styles.weekNav}>
                                <Button onClick={handlePrevWeek} size="small" className={styles.navButton}>
                                    上周
                                </Button>
                                <Button onClick={handleThisWeek} size="small" className={styles.navButtonActive}>
                                    本周
                                </Button>
                                <Button onClick={handleNextWeek} size="small" className={styles.navButton}>
                                    下周
                                </Button>
                            </div>
                        </div>
                    </div>
                    
                    {/* 排班表格 */}
                    <div className={styles.scheduleTable}>
                        <table className={styles.table}>
                            <thead>
                                <tr>
                                    <th className={styles.shiftHeader}>日期/班次</th>
                                    {weekDates.map((date, index) => (
                                        <th key={index} className={styles.dayHeader}>
                                            <div className={styles.dayName}>
                                                {['周一', '周二', '周三', '周四', '周五', '周六', '周日'][index]}
                                            </div>
                                            <div className={styles.dayDate}>{date.format('M/D')}</div>
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {/* 早班 */}
                                <tr>
                                    <td className={styles.shiftCell}>
                                        <div className={styles.shiftName}>早班</div>
                                        <div className={styles.shiftTime}>08:00-16:00</div>
                                    </td>
                                    {weekDates.map((date, index) => (
                                        <td key={index} className={`${styles.scheduleCell} ${getCellClassName(date, 'morning')}`}>
                                            {renderCell(date, 'morning')}
                                        </td>
                                    ))}
                                </tr>
                                
                                {/* 中班 */}
                                <tr>
                                    <td className={styles.shiftCell}>
                                        <div className={styles.shiftName}>中班</div>
                                        <div className={styles.shiftTime}>16:00-24:00</div>
                                    </td>
                                    {weekDates.map((date, index) => (
                                        <td key={index} className={`${styles.scheduleCell} ${getCellClassName(date, 'middle')}`}>
                                            {renderCell(date, 'middle')}
                                        </td>
                                    ))}
                                </tr>
                                
                                {/* 晚班 */}
                                <tr>
                                    <td className={styles.shiftCell}>
                                        <div className={styles.shiftName}>晚班</div>
                                        <div className={styles.shiftTime}>00:00-08:00</div>
                                    </td>
                                    {weekDates.map((date, index) => (
                                        <td key={index} className={`${styles.scheduleCell} ${getCellClassName(date, 'evening')}`}>
                                            {renderCell(date, 'evening')}
                                        </td>
                                    ))}
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                {/* 中间区域：排班参数设置 */}
                <div className={styles.middleSection}>
                    <div className={styles.settingPanel}>
                        <div className={styles.panelHeader}>
                            <div className={styles.titleBar}></div>
                            <h3 className={styles.panelTitle}>排班参数设置</h3>
                        </div>
                        
                        <div className={styles.settingForm}>
                            <div className={styles.formItem}>
                                <label className={styles.formLabel}>值班周期</label>
                                <Select 
                                    className={styles.formInput}
                                    defaultValue="按周排班"
                                >
                                    <Option value="按周排班">按周排班</Option>
                                    <Option value="按月排班">按月排班</Option>
                                </Select>
                            </div>
                            
                            <div className={styles.formItem}>
                                <label className={styles.formLabel}>日期</label>
                                <RangePicker 
                                    className={styles.formInput}
                                    placeholder={['2025/10/16', '2025/10/16']}
                                    format="YYYY/MM/DD"
                                    suffixIcon={<CalendarOutlined />}
                                />
                            </div>
                            
                            <div className={styles.formItem}>
                                <label className={styles.formLabel}>每日班次</label>
                                <Select 
                                    className={styles.formInput}
                                    value={shiftType}
                                    onChange={setShiftType}
                                >
                                    <Option value="早班">早班 (8:00-16:00)</Option>
                                    <Option value="中班">中班 (16:00-24:00)</Option>
                                    <Option value="晚班">晚班 (00:00-08:00)</Option>
                                </Select>
                            </div>
                            
                            <div className={styles.formItem}>
                                <label className={styles.formLabel}>每日人数</label>
                                <InputNumber 
                                    className={styles.formInput}
                                    value={personCount}
                                    onChange={setPersonCount}
                                    min={1}
                                    max={10}
                                />
                            </div>
                            
                            <div className={styles.formItem}>
                                <label className={styles.formLabel}>专业要求</label>
                                <Select 
                                    className={styles.formInput}
                                    value={specialty}
                                    onChange={setSpecialty}
                                >
                                    <Option value="无特殊要求">无特殊要求</Option>
                                    <Option value="网络运维">网络运维</Option>
                                    <Option value="系统管理">系统管理</Option>
                                </Select>
                            </div>
                            
                            <div className={styles.formActions}>
                                <Button type="primary" icon={<CalendarOutlined />} block>
                                    生成排班计划
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>
                
                {/* 右侧区域：统计概览和可用人员 */}
                <div className={styles.rightSection}>
                    {/* 统计概览 */}
                    <div className={styles.statsOverview}>
                        <div className={styles.overviewHeader}>
                            <div className={styles.titleBar}></div>
                            <h3 className={styles.overviewTitle}>统计概览</h3>
                        </div>
                        <div className={styles.statsGrid}>
                            <div className={styles.statItem}>
                                <div className={styles.statValue}>24</div>
                                <div className={styles.statLabel}>值班人员</div>
                            </div>
                            <div className={styles.statItem}>
                                <div className={styles.statValue}>156</div>
                                <div className={styles.statLabel}>本月排班</div>
                            </div>
                            <div className={styles.statItem}>
                                <div className={styles.statValue}>12</div>
                                <div className={styles.statLabel}>待确认</div>
                            </div>
                            <div className={styles.statItem}>
                                <div className={styles.statValue}>11</div>
                                <div className={styles.statLabel}>调班申请</div>
                            </div>
                        </div>
                    </div>
                    
                    {/* 可用值班人员 */}
                    <div className={styles.availablePersons}>
                        <div className={styles.personsHeader}>
                            <div className={styles.titleBar}></div>
                            <h3 className={styles.personsTitle}>可用值班人员</h3>
                            <Button type="primary" size="small" icon={<PlusOutlined />}>
                                添加
                            </Button>
                        </div>
                        
                        <div className={styles.personsList}>
                            {availablePersons.map(person => (
                                <div key={person.id} className={styles.personCard}>
                                    <Avatar 
                                        size={40} 
                                        style={{ backgroundColor: '#87d068' }}
                                        icon={<UserOutlined />}
                                    />
                                    <div className={styles.personInfo}>
                                        <div className={styles.personName}>{person.name}</div>
                                        <div className={styles.personDescription}>{person.description}</div>
                                    </div>
                                    <Button 
                                        type="primary" 
                                        size="small" 
                                        icon={<PlusOutlined />}
                                        className={styles.addPersonButton}
                                        shape="default"
                                    />
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
            
            {/* 底部：近期值班信息人员列表 */}
            <div className={styles.bottomSection}>
                <div className={styles.sectionHeader}>
                    <div className={styles.titleBar}></div>
                    <h2 className={styles.sectionTitle}>近期值班信息人员列表</h2>
                    <div style={{ marginLeft: 'auto' }}>
                        <Button type="primary" icon={<PlusOutlined />}>
                            添加人员
                        </Button>
                    </div>
                </div>
                
                <StandardTable
                    rowKey="key"
                    data={{
                        list: tableData,
                        pagination: tablePagination,
                    }}
                    columns={tableColumns}
                    onChange={(pagination) => {
                        setTablePagination({
                            ...tablePagination,
                            current: pagination.current,
                            currentPage: pagination.current,
                            pageSize: pagination.pageSize,
                        });
                    }}
                    className={styles.personTable}
                    isshowAlert={false}
                />
            </div>
        </div>
    );
};

export default DutySchedule;
