import { useEffect, useRef, useState } from 'react';
import { connect } from '@umijs/max';
import type { ActionType } from '@ant-design/pro-components';
import {
    ProTable, ProFormSelect
} from '@ant-design/pro-components';
import { Button, ConfigProvider, message, Space, Descriptions, Radio, Row, Popconfirm, Modal, Flex, InputNumber } from 'antd';
import { GetCompanyJobList, getCompanyList, GetCompanyInfo, PostJobExport, PostcompanymMultieditPulishJob, PostcompanymMultieditstatusjob, PostcompanyJobDel } from '@/apis/api';
import { Imageprefix } from '@/constants';
const selectfieldNames = { label: 'full_name', value: 'id' };
const PagesMainCompanyPostTable: 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 [companyId, setCompanyId] = useState<number>(0);
    const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([])
    const [openMultieditPreview, setOpenMultieditPreview] = useState(false);
    const [openMultieditPreview2, setOpenMultieditPreview2] = useState(false);
    const [ids, setIds] = useState<number[]>([])
    const [status, setStatus] = useState<number>(1)
    const [usefuLife, setUsefuLife] = useState<number>(1)
    const [disabledDate, setDisabledDate] = useState<Date | String | null>(null);
    const setId = (id: number) => {
        getId(id)
    }

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

        return () => {
            sessionStorage.removeItem('company_info')
            sessionStorage.removeItem('post_company_info')
            sessionStorage.removeItem('vip_company_info')

        };
    }, [openModel.openModal])

    const handleTimeChange = (value) => {
        setUsefuLife(value)
        const today = new Date();
        let end_date = new Date(today);

        end_date.setDate(today.getDate() + value);
        // 格式化日期为 YYYY-MM-DD
        const formatDate = (date: Date): string => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        const formattedEndDate = formatDate(end_date);
        setDisabledDate(formattedEndDate);
        console.log(formattedEndDate);

    };

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

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

                                            // 等待所有请求完成
                                            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'
                    }}
                    columns={[
                        {
                            title: '筛选日期',
                            dataIndex: 'date_range',
                            hidden: true,
                            valueType: 'dateRange',
                        },
                        {
                            title: 'ID',
                            dataIndex: 'id',
                            width: 200
                        },

                        {
                            title: '所属企业',
                            dataIndex: 'full_name',
                            width: 200,
                            valueType: 'select',
                            renderFormItem: () => {
                                return (
                                    <ProFormSelect
                                        fieldProps={{
                                            fieldNames: selectfieldNames,
                                            defaultValue: sessionStorage.getItem('post_company_info') ? JSON.parse(sessionStorage.getItem('post_company_info')).full_name : null,
                                        }}
                                        request={async (keyword) =>
                                            getCompanyList({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                                return res.data.list;
                                            })
                                        }
                                        placeholder="请选择所属企业"
                                        onChange={(value) => {
                                            setCompanyId(value)
                                            GetCompanyInfo({ id: value }).then(res => {
                                                sessionStorage.setItem('post_company_info', JSON.stringify(res.data))
                                            })
                                        }}
                                    />
                                )
                            }
                        },
                        {
                            title: '职位名称',
                            dataIndex: 'name',
                            width: 200
                        },
                        {
                            title: '点击次数',
                            dataIndex: 'click_count',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '职位状态',
                            dataIndex: 'status',
                            width: 200,
                            colSize: 16,
                            valueType: 'radio',
                            initialValue: '0',
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '发布中',
                                    status: 'Processing'
                                },
                                2: {
                                    text: '未发布',
                                    status: 'Error'
                                },
                                3: {
                                    text: '暂停',
                                    status: 'Error'
                                },
                                4: {
                                    text: '已锁定',
                                    status: 'Error'
                                },
                                5: {
                                    text: '回收站',
                                    status: 'Error'
                                },
                                6: {
                                    text: '已过期',
                                    status: 'Error'
                                }
                            },
                        },

                        {
                            title: '有效期（天）',
                            dataIndex: 'useful_life',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '发布时间',
                            dataIndex: 'publish_date',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '到期时间',
                            dataIndex: 'disabled_date',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            width: 200,
                            render: (_, record, action) => [
                                <Button key='1' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>编辑</Button>,
                                <Popconfirm
                                    title="是否删除"
                                    onConfirm={(e) => {
                                        PostcompanyJobDel({ 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>) =>
                        GetCompanyJobList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,
                            expired: params.expired,
                            status: params.status ? params.status : 0,
                            company_id: sessionStorage.getItem('post_company_info') ? JSON.parse(sessionStorage.getItem('post_company_info')).id : companyId,
                            start_date: params.date_range ? params.date_range[0] : '',
                            end_date: params.date_range ? params.date_range[1] : '',
                        }).then(res => {
                            setList(res.data.rows)
                            setTotal(res.data.total)
                        })
                    }
                    onReset={() => {
                        if (sessionStorage.getItem('post_company_info')) {
                            sessionStorage.removeItem('post_company_info')
                        }
                        setCompanyId(0)
                        actionRef.current?.reload();

                    }}
                    headerTitle="职位列表"
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            message.info('数据导出需要时间，请耐心等待')
                            PostJobExport().then(res => {
                                let url = Imageprefix + res.data.excel_url;
                                window.open(url);
                                message.info('数据导出完毕')
                            })
                        }}>
                            导出数据
                        </Button>,
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            添加职位
                        </Button>
                    ]}
                />
                <Modal
                    open={openMultieditPreview}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview(false)
                    }}
                    onOk={() => {
                        if (usefuLife && disabledDate && status) {
                            PostcompanymMultieditPulishJob({ id: ids, useful_life: usefuLife, disabled_date: disabledDate, status: status }).then(res => {
                                setOpenMultieditPreview(false)
                                actionRef.current?.clearSelected();
                                actionRef.current?.reload();
                            })

                        } 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 value={3}>暂停</Radio>
                                <Radio value={4}>已锁定</Radio>
                                <Radio value={5}>回收站</Radio>
                                <Radio value={6}>已过期</Radio>
                            </Radio.Group>
                            <h4 style={{ fontWeight: 'bold' }}>职位有效天数：</h4>
                            <InputNumber min={1} placeholder='请输入职位有效天数' onChange={(value) => {
                                handleTimeChange(value)
                            }} style={{ width: '100%' }} />
                        </Space>
                    </Flex>
                </Modal >

                <Modal
                    open={openMultieditPreview2}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview2(false)
                    }}
                    onOk={() => {
                        if (status) {
                            PostcompanymMultieditstatusjob({ id: ids, status: status }).then(res => {
                                setOpenMultieditPreview2(false)
                                actionRef.current?.clearSelected();
                                actionRef.current?.reload();
                            })
                        } 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 value={3}>暂停</Radio>
                                <Radio value={4}>已锁定</Radio>
                                <Radio value={5}>回收站</Radio>
                                <Radio value={6}>已过期</Radio>
                            </Radio.Group>

                        </Space>
                    </Flex>
                </Modal >
            </ConfigProvider>

        </>



    );
};


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