import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Card, Collapse, Space, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { useRef } from 'react';
import MeetingReservation from '@/components/ElecBidEvaluation/MeetingReservation';
import { getRecordData, getSiteList } from './service';
import { isEmpty } from '@/utils/CommonUtils';

const orange_bg = { background: '#ffbc83', color: '#333333', cursor: 'pointer', width: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
const light_orange_bg = { background: '#faf7e5' };
const align_middle = { display: 'flex', alignItems: 'center' };
const tag_size = { height: '20px', width: '20px' };
const panel_title = { fontWeight: 500 };
const panel_sub_title = { ...panel_title, color: '#999999' };
const { Panel } = Collapse;

const ScreenTable = (props: { record: any, onCellClick: (id: any) => void, refresh: number }) => {
    const { record, onCellClick, refresh } = props;
    const actionRef = useRef<ActionType>();
    //表格列
    const [tableColumns, setTableColumns] = useState<ProColumns<any>[]>([]);
    //表格数据
    const [tableData, setTableData] = useState<any[]>([]);
    //星期偏移量
    const offset = useRef<number>(0);

    //表格列拼接
    const columnsSplice = (weeksData: any[]) => {
        const columns: ProColumns<any>[] = [
            {
                title: '时段场次',
                dataIndex: "time",
                align: 'center',
            },
        ];
        for (const ite of weeksData) {
            columns.push({
                title: <span>{ite.week}<br />{ite.date}</span>,
                dataIndex: ite.id,
                align: 'center',
                ellipsis: true,
                onCell: (record) => {
                    return {
                        style: record[ite.id]?.iskssj ? orange_bg : light_orange_bg,
                        onClick: record[ite.id]?.iskssj ? () => onCellClick(record[ite.id]?.id) : void 0,
                    }
                },
                render: (_: any, record: any) => {
                    return {
                        children: record[ite.id]?.hymc,
                        props: {
                            rowSpan: record[ite.id]?.iskssj ? record[ite.id]?.hour : record[ite.id]?.hour ? 0 : 1,
                        }
                    }
                }
            })
        }
        setTableColumns(columns);
    }

    const getTableData = () => {
        getRecordData({ areaId: record?.id, offset: offset.current }).then(res => {
            if (res?.code == 200) {
                const data = res?.data;
                columnsSplice(data.week);
                setTableData(data.data);
            }
        })
    }
    const weekChange = (param: string) => {
        if (param == "1") {
            offset.current += 1;
        } else if (param == "0") {
            offset.current -= 1;
        }
        getTableData();
    }
    useEffect(() => {
        //获取预约记录
        getTableData();
    }, [refresh]);
    return (
        <div>
            {tableData.length > 0 && (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 16 }}>
                    <Space>
                        <Button key="last-week" size='small' type="primary" onClick={() => weekChange("0")}>
                            上一周
                        </Button>
                        <Button key="after-week" size='small' type="primary" onClick={() => weekChange("1")}>
                            下一周
                        </Button>
                    </Space>
                    <Space size="middle">
                        <div style={align_middle}><Tag color="#faf7e5" style={tag_size}></Tag>可预约电子评标室</div>
                        <div style={align_middle}><Tag color="#ffbc83" style={tag_size}></Tag>已预约电子评标室</div>
                    </Space>
                </div>
            )}
            <ProTable<any>
                columns={tableColumns}
                actionRef={actionRef}
                bordered
                size='small'
                dataSource={tableData}
                className="screen-reserve-table"
                rowKey="time"
                search={false}
                pagination={false}
                options={false}
                dateFormatter="string"
            />
        </div>
    )
}

export default () => {
    //预约弹窗
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    //评标场所列表数据
    const [siteListData, setSiteListData] = useState<any[]>([]);
    //评标场所列表展开
    const [expandedRowKeys, setExpandedRowKeys] = useState<any[]>([]);
    //预约状态
    const [meetStatus, setMeetStatus] = useState<string>("2");
    //预约id
    const [meetId, setMeetId] = useState<string>("");
    //刷新参数
    const [refresh, setRefresh] = useState<number>(0);

    //获取评标场所
    const getSiteListData = (key: any) => {
        getSiteList().then(res => {
            if (res?.code == 200) {
                const data = res?.data;
                setSiteListData(data);
                if (key == "0" && data?.length > 0) {
                    setExpandedRowKeys([data[0].id]);
                }
            }
        })
    }
    //新建预约
    const createMeet = () => {
        setMeetStatus("0");
        setMeetId("");
        setModalVisible(true);
    }
    //查看预约
    const viewMeet = (id: any) => {
        setMeetStatus("2");
        setMeetId(id);
        setModalVisible(true);
    }
    //查看预约详情跳转
    const viewMeetContent = () => {
        window.open("/ElecEvaluation/ElecEvalReserve");
    }

    useEffect(() => {
        getSiteListData("0");
    }, [])

    return (
        <Card title="评标室预约情况" bodyStyle={{ padding: '16px 0px', height: window.innerHeight - 120, overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 36px 16px' }}>
                <Space>
                    <Button key="yuyue" type="primary" onClick={() => createMeet()}>
                        预约
                    </Button>
                    <Button key="yuyueconfirm" onClick={() => viewMeetContent()}>
                        查看预约详情
                    </Button>
                </Space>
            </div>
            <Collapse activeKey={expandedRowKeys} onChange={(value) => setExpandedRowKeys(value as any[])} className="screen-reserve-collapse" style={{ margin: '0 36px' }}>
                {siteListData.map(item => (
                    <Panel
                        header={<>
                            <span style={panel_title}>{item.areaName}</span>
                            <span style={panel_sub_title}>（可容纳{isEmpty(item.areaNumber) ? '' : item.areaNumber}人）</span>
                        </>}
                        extra={
                            <>
                                <span style={panel_title}>时间：07:00 ~ 18:00</span>
                            </>
                        }
                        key={item.id}
                    >
                        <ScreenTable record={item} onCellClick={viewMeet} refresh={refresh} />
                    </Panel>
                ))}
            </Collapse>
            {modalVisible && <MeetingReservation modalVisible={modalVisible} onCancel={() => { setModalVisible(false); getSiteListData("1") }} roomList={siteListData} status={meetStatus} meetId={meetId} onSubmit={() => { setModalVisible(false); setRefresh(refresh => refresh + 1) }} />}
        </Card >
    );
};