import { useRef, useState, useEffect } from 'react';
import { connect, history } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, ProForm
} from '@ant-design/pro-components';
import { Button, ConfigProvider, Flex, Modal, Radio, message, DatePicker, Descriptions, Space, Image, Popconfirm } from 'antd';
import { Imageprefix } from '@/constants';
import { listRecruitment, GetRecruitmentDetail, PostRecruitmentUpdate, PostRecruitmentDel } from '@/apis/api';

import UploadModel from '@/components/Common/upload';


const MainFairListPage: React.FC = ({ dispatch, getId, openModel }: any) => {
    const actionRef = useRef<ActionType>();
    const [list, setList] = useState<object[]>([])
    const [total, setTotal] = useState<number>(0)
    const [page, setPage] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(10)
    const [openMultieditPreview, setOpenMultieditPreview] = useState(false);
    const [ids, setIds] = useState<number[]>([])
    const [status, setStatus] = useState<number>(1)
    const [startDate, setStartDate] = useState<Date | String | null>(null);
    const [endDate, setEndDate] = useState<Date | String | null>(null);
    const setId = (id: number) => {
        getId(id)
    }

    useEffect(() => {
        if (!openModel.openModal) {
            actionRef.current?.reload();
        }
    }, [openModel.openModal])

    const [uploadedFilephotoName, setUploadedFilephotoName] = useState<string>('');
    const uploadedFilephotoNameRef = useRef<string>('');
    const handleFileUploadedphoto = (filename: string) => {
        setUploadedFilephotoName(filename);
    };

    useEffect(() => {
        uploadedFilephotoNameRef.current = uploadedFilephotoName;
    }, [uploadedFilephotoName])

    const expandedRowRender = (record) => {
        return (
            <>
                <Space direction='vertical' style={{ width: '100%' }}>
                    <Descriptions title="参会信息" bordered column={3} contentStyle={{ fontWeight: 'bold' }} labelStyle={{ width: 180 }}>
                        <Descriptions.Item label="参与的企业总数">{record.join_count}</Descriptions.Item>
                        <Descriptions.Item label="已审核企业总数">{record.job_count}</Descriptions.Item>
                        <Descriptions.Item label="参与职位数">{record.job_count}</Descriptions.Item>
                        <Descriptions.Item label="需求人数">{record.recruiting_num}</Descriptions.Item>
                    </Descriptions>
                </Space >

            </>
        );
    };

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                        colorLink: '#4FBE70',

                    }
                }}
            >

                <ProTable
                    scroll={{ y: 480, x: 'auto' }}
                    bordered={true}
                    actionRef={actionRef}
                    dataSource={list}
                    search={{ span: 8, labelWidth: 'auto' }}
                    tableAlertRender={({
                        selectedRowKeys,
                        selectedRows,
                        onCleanSelected,
                    }) => {
                        setIds(selectedRows)
                        return (
                            <Space size={24}>
                                <span>
                                    已选 {selectedRows.length} 项
                                    <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                        取消选择
                                    </a>
                                </span>
                            </Space>
                        );
                    }}
                    tableAlertOptionRender={() => {
                        return (
                            <Space>
                                <Button onClick={() => {
                                    if (ids.length === 0) {
                                        message.error('请选择要操作的数据')
                                    } else {
                                        setOpenMultieditPreview(true)
                                    }
                                }}>
                                    批量管理招聘会
                                </Button>,
                                <Button danger type="primary" onClick={() => {
                                    Modal.confirm({
                                        title: '批量删除',
                                        content: '确定要删除所选的数据吗',
                                        onOk() {
                                            const promises = ids.map(item => {
                                                return PostRecruitmentDel({ id: item.id });
                                            });

                                            // 等待所有请求完成
                                            Promise.all(promises)
                                                .then(() => {
                                                    message.success('批量删除成功');
                                                    actionRef.current?.clearSelected();
                                                    actionRef.current?.reload();
                                                })
                                                .catch(error => {
                                                    console.error('批量删除成功:', error);
                                                    message.error('批量删除成功');
                                                });

                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '确定',
                                        cancelText: '取消',
                                        centered: true
                                    });
                                }}>
                                    批量删除
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    expandable={{
                        expandedRowRender
                    }}
                    columns={[{
                        title: 'ID',
                        dataIndex: 'id',
                        width: 200,
                    },
                    {
                        title: '招聘会名称',
                        dataIndex: 'title',
                        width: 400,
                    }, {
                        title: '地点',
                        dataIndex: 'address',
                        width: 200,
                        search: false
                    }, {
                        title: '开始时间',
                        dataIndex: 'open_date',
                        width: 200,
                        search: false
                    }, {
                        title: '结束时间',
                        dataIndex: 'close_date',
                        width: 200,
                        search: false
                    }, {
                        title: '开启状态',
                        dataIndex: 'status',
                        width: 200,
                        valueType: 'select',
                        valueEnum: {
                            0: { text: '全部' },
                            1: {
                                text: '已开启',
                                status: 'Processing'

                            },
                            2: {
                                text: '已关闭',
                                status: 'Error'

                            }
                        },
                    }, {
                        title: '封面图',
                        dataIndex: 'photo',
                        width: 200,
                        search: false,
                        render: (_, record) => (<>
                            <Image src={`${Imageprefix}${record.photo}`} width={60} height={60} />
                        </>
                        )
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record, action) => [
                            <Button key='1' type='link' onClick={() => {
                                setId(record)
                                dispatch({ type: 'openModel/getOpenModal', payload: true })
                            }}>编辑</Button>,
                            <Button size='small' type='link' onClick={() => {
                                Modal.confirm({
                                    title: '更换图片',
                                    content: (<>
                                        <ProForm submitter={{ render: false }}>
                                            <UploadModel multiple={false} form_name="photo" image_length={1} uploadTxt="更换图片" image_type={3} imageUrl={record.photo} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                        </ProForm>
                                    </>),
                                    async onOk() {
                                        let res = await PostRecruitmentUpdate({ ...record, photo: uploadedFilephotoNameRef.current });
                                        setUploadedFilephotoName('');
                                        actionRef.current?.reload();
                                    },
                                    onCancel() {
                                        console.log('Cancel');
                                    },
                                    okText: '保存',
                                    cancelText: '取消',
                                    centered: true,
                                });
                            }}>更换图片</Button>,
                            <Button key='2' type='link' onClick={() => {
                                setId(record)
                                dispatch({ type: 'openModel/getOpenFairDetailModal', payload: true })

                            }}>详情</Button>,
                            <Button key='3' type='link' onClick={() => {
                                setId(record)
                                dispatch({ type: 'openModel/getOpenFairDetailModal', payload: true })

                            }}>参与企业</Button>,
                            <Popconfirm
                                title="是否删除"
                                onConfirm={(e) => {
                                    PostRecruitmentDel({ id: record.id }).then(res => {
                                        message.success('删除成功')
                                        actionRef.current?.reload();
                                    })
                                }}
                                okText="删除"
                                cancelText="取消"
                            >
                                <Button danger type='link'>删除</Button>
                            </Popconfirm>,
                        ],
                    },
                    ]}
                    rowKey="id"
                    pagination={{
                        current: page,
                        pageSize: pageSize,
                        showSizeChanger: true,
                        total: total,
                        pageSizeOptions: [9, 18, 27, 99],
                        onChange(page, pageSize) {
                            setPage(page)
                            setPageSize(pageSize)
                        },
                        onShowSizeChange(current, size) {
                            setPage(current)
                            setPageSize(size)
                        }
                    }}
                    request={async (params = {} as Record<string, any>) =>
                        listRecruitment({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.title,
                            status: params.status ? params.status : 0
                        }).then(res => {
                            setList(res.data.recruitments)
                            setTotal(res.data.total)
                        })
                    }
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            添加招聘会
                        </Button>
                    ]}
                    headerTitle="招聘会列表"
                />


                <Modal
                    open={openMultieditPreview}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview(false)
                    }}
                    onOk={() => {
                        if (status) {
                            const promises = ids.map(item => {
                                return PostRecruitmentUpdate({ ...item, status: status, open_date: startDate ? startDate : '', close_date: endDate ? endDate : '' });
                            });

                            // 等待所有请求完成
                            Promise.all(promises)
                                .then(() => {
                                    setOpenMultieditPreview(false);
                                    message.success('批量操作成功');
                                    actionRef.current?.clearSelected();
                                    actionRef.current?.reload();
                                })
                                .catch(error => {
                                    console.error('批量操作失败:', error);
                                    message.error('批量操作失败');
                                });
                        } else {
                            message.error('请完成表单')
                            return false
                        }
                    }
                    }
                >
                    <Flex vertical justify='center' style={{ minHeight: 100 }}>
                        <Space direction='vertical'>
                            <h4 style={{ fontWeight: 'bold' }}>类型：</h4>
                            <Radio.Group size='small' value={status} onChange={(e) => {
                                setStatus(e.target.value)
                            }}>
                                <Radio value={1}>开启</Radio>
                                <Radio value={2}>关闭</Radio>
                            </Radio.Group>
                            {
                                status === 1 && (
                                    <>
                                        <h4 style={{ fontWeight: 'bold' }}>活动时间：</h4>
                                        <DatePicker.RangePicker showTime format='YYYY-MM-DD HH:mm:ss' onChange={(date, dateString) => {
                                            setStartDate(dateString[0]);
                                            setEndDate(dateString[1]);
                                        }} />
                                    </>
                                )
                            }


                        </Space>
                    </Flex>
                </Modal >
            </ConfigProvider>
        </>
    );
};




export default connect(({ dictModel, openModel }: any) => ({
    dictModel,
    openModel
}))(MainFairListPage);