import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable
} from '@ant-design/pro-components';
import { Button, Image, ConfigProvider, Input, Descriptions, Space, Modal, Radio, Row, Col, InputNumber, message, Flex } from 'antd';
import { PostCompanyViplist, PostCompanyFeechange, PostCompanyMultiopenvip } from '@/apis/api';
import { Imageprefix } from '@/constants';




const CompanyListPage: 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 [fullname, setFullname] = useState<any>(sessionStorage.getItem('vip_company_info') ? JSON.parse(sessionStorage.getItem('vip_company_info')).full_name : '')
    const [openMultieditPreview, setOpenMultieditPreview] = useState(false);
    const [ids, setIds] = useState<number[]>([])
    const [memberType, setMemberType] = 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();

        }

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

        };
    }, [openModel.openModal])

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

    const handleTimeChange = (value) => {
        const today = new Date();
        let start_date = today;
        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 formattedStartDate = formatDate(start_date);
        const formattedEndDate = formatDate(end_date);

        setStartDate(formattedStartDate);
        setEndDate(formattedEndDate);

        console.log(formattedStartDate);
        console.log(formattedEndDate);

    };

    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.probation_text}</Descriptions.Item>
                        <Descriptions.Item label="知名企业">{record.famous_text}</Descriptions.Item>
                        <Descriptions.Item label="业务员">{record.sales}</Descriptions.Item>

                    </Descriptions>
                </Space >

            </>
        );
    };




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

                    },
                    components: {
                        Modal: {
                            colorPrimary: '#4FBE70',

                        }
                    }
                }}
            >
                <ProTable
                    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={() => {
                        return (
                            <Space size={16}>
                                <Button onClick={() => {
                                    if (ids.length === 0) {
                                        message.error('请选择要操作的数据')
                                    } else {
                                        setOpenMultieditPreview(true)
                                    }
                                }}>
                                    批量开通会员
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    expandable={{
                        expandedRowRender
                    }}
                    columns={[
                        {
                            title: '筛选日期',
                            dataIndex: 'date_range',
                            hidden: true,
                            valueType: 'dateRange',
                        },
                        {
                            title: 'ID',
                            dataIndex: 'id',
                            width: 200,
                        },
                        {
                            title: '企业名称',
                            dataIndex: 'full_name',
                            width: 200,
                            valueType: 'input',
                            renderFormItem: () => {
                                return (
                                    <><Input placeholder="请输入企业名称" value={fullname} onChange={(e) => {
                                        setFullname(e.target.value)
                                    }} /></>
                                )
                            }
                        },
                        {
                            title: '会员类型',
                            dataIndex: 'member_type_text',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '会员状态',
                            dataIndex: 'member_status',
                            width: 200,
                            search: false,
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '待审',
                                    status: 'Error'
                                },
                                2: {
                                    text: '正常',
                                    status: 'Processing'
                                },
                                3: {
                                    text: '到期',
                                    status: 'Error'
                                },
                                4: {
                                    text: '推荐',
                                    status: 'Error'
                                },
                            },
                        },
                        {
                            title: '开始时间',
                            dataIndex: 'start_date',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '到期时间',
                            dataIndex: 'end_date',
                            width: 200,
                            search: false,

                        }, {
                            title: '剩余点数',
                            dataIndex: 'balance_fee',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            render: (_, record, action) => [

                                <Button key='1' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>编辑</Button>,
                                <Button key='2' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenFeeModal', payload: true })
                                }}>变更点数</Button>
                            ],
                        },
                    ]}
                    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>) =>
                        PostCompanyViplist({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: fullname,
                            start_date: params.date_range ? params.date_range[0] : '',
                            end_date: params.date_range ? params.date_range[1] : '',
                        }).then(res => {
                            setList(res.data.list)
                            setTotal(res.data.total)
                        })
                    }
                    onReset={() => {
                        if (sessionStorage.getItem('vip_company_info')) {
                            sessionStorage.removeItem('vip_company_info')
                        }
                        setFullname('')
                        actionRef.current?.reload();
                    }}
                    headerTitle="VIP企业列表"
                />


                <Modal
                    open={openMultieditPreview}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview(false)
                    }}
                    onOk={() => {
                        if (memberType && startDate && endDate) {
                            PostCompanyMultiopenvip({ ids: ids, member_type: memberType, start_date: startDate, end_date: endDate }).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={memberType} onChange={(e) => {
                                setMemberType(e.target.value)
                            }}>
                                <Radio value={1}>试用申请中</Radio>
                                <Radio value={2}>试用正式</Radio>
                                <Radio value={3}>普通申请中</Radio>
                                <Radio value={4}>普通正式</Radio>
                                <Radio value={5}>VIP申请中</Radio>
                                <Radio value={6}>VIP正式</Radio>
                            </Radio.Group>
                            <h4 style={{ fontWeight: 'bold' }}>时长：</h4>
                            <InputNumber min={1} placeholder='请输入时长' onChange={(value) => {
                                handleTimeChange(value)
                            }} style={{ width: '100%' }} />
                        </Space>
                    </Flex>
                </Modal >
            </ConfigProvider>
        </>
    );
};



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