import { useRef, useState, useEffect } from 'react';
import { connect, history } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, ProFormSelect, ProForm
} from '@ant-design/pro-components';
import { Button, Popconfirm, ConfigProvider, Modal, message , Space ,Image} from 'antd';
import { GetAdvertscheduleList, getCompanyList, GetAdvertareaList, PostAdvertscheduleDel, PostAdvertscheduleUpdate } from '@/apis/api';
import { Imageprefix } from '@/constants';

const selectfieldNames = { label: 'full_name', value: 'id' };
const selectfieldAreaNames = { label: 'name', value: 'id' };
import UploadModel from '@/components/Common/upload';

const PagesMainAdvertisementPutinTable: React.FC = ({ dispatch, openModel, getId }: 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 [ids, setIds] = useState<number[]>([])

    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])

    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 danger type="primary" onClick={() => {
                                    Modal.confirm({
                                        title: '批量删除',
                                        content: '确定要删除所选的数据吗',
                                        onOk() {
                                            const promises = ids.map(item => {
                                                return PostAdvertscheduleDel({ 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'
                    }}
                    columns={[{
                        title: 'ID',
                        dataIndex: 'id',
                        width: 200,
                        search: false,
                    },
                    {
                        title: '投放标题',
                        dataIndex: 'title',
                        width: 200
                    },
                    {
                        title: '投放位置',
                        dataIndex: 'area_name',
                        width: 200,

                        search: false
                    },
                    {
                        title: '封面图',
                        dataIndex: 'image_url',
                        search: false,
                        width: 200,
                        render: (_, record) => (<>
                            <Image src={`${Imageprefix}${record.image_url}`} width={40} height={40} />
                        </>
                        )
                    },
                    {
                        title: '投放位置',
                        dataIndex: 'area_id',
                        hidden: true,
                        valueType: 'select',
                        renderFormItem: () => {
                            return (
                                <ProFormSelect
                                    width='lg'
                                    fieldProps={{
                                        fieldNames: selectfieldAreaNames,
                                    }}
                                    request={async (keyword) =>
                                        GetAdvertareaList({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                            return res.data.advertareas;
                                        })
                                    }
                                    placeholder="请选择投放位置"
                                />
                            )
                        }
                    },
                    {
                        title: '投放描述',
                        dataIndex: 'ad_description',
                        width: 200,

                        search: false
                    },
                    {
                        title: '企业',
                        dataIndex: 'company_name',
                        width: 200,

                        search: false
                    },
                    {
                        title: '企业',
                        dataIndex: 'company_id',
                        hidden: true,
                        valueType: 'select',
                        renderFormItem: () => {
                            return (
                                <ProFormSelect
                                    showSearch
                                    fieldProps={{
                                        fieldNames: selectfieldNames,
                                    }}
                                    request={async (keyword) =>
                                        getCompanyList({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                            return res.data.list;
                                        })
                                    }
                                    placeholder="请选择企业"
                                />
                            )
                        }
                    },
                 
                    {
                        title: '投放状态',
                        dataIndex: 'hide_ad',
                        width: 200,
                        valueType: 'select',
                        valueEnum: {
                            0: { text: '全部' ,
                                status: 'Errorr'},
                            1: {
                                text: '隐藏',
                                status: 'Errorr'
                            },
                            2: {
                                text: '显示',
                                status: 'Processing'
                            }
                        },
                    },
                    {
                        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 size='small' type='link' onClick={() => {
                                Modal.confirm({
                                    title: '更换图片',
                                    content: (<>
                                        <ProForm submitter={{ render: false }}>
                                            <UploadModel multiple={false} form_name="image_url" image_length={1} uploadTxt="更换图片" image_type={3} imageUrl={record.image_url} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                        </ProForm>
                                    </>),
                                    async onOk() {
                                        let res = await PostAdvertscheduleUpdate({ ...record, image_url: uploadedFilephotoNameRef.current });
                                        setUploadedFilephotoName('');
                                        actionRef.current?.reload();
                                    },
                                    onCancel() {
                                        console.log('Cancel');
                                    },
                                    okText: '保存',
                                    cancelText: '取消',
                                    centered: true,
                                });
                            }}>更换图片</Button>,
                            <Popconfirm
                                title="是否删除"
                                onConfirm={(e) => {
                                    PostAdvertscheduleDel({ 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>) =>
                        GetAdvertscheduleList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.title,
                            hide_ad: params.hide_ad ? params.hide_ad : 0,
                            company_id: params.company_id,
                            area_id: params.area_id
                        }).then(res => {
                            setList(res.data.advertschedules)
                            setTotal(res.data.total)
                        })
                    }
                    headerTitle="广告位置列表"
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            投放广告
                        </Button>
                    ]}
                />
            </ConfigProvider>
        </>
    );
};


export default connect(({ openModel }: any) => ({
    openModel
}))(PagesMainAdvertisementPutinTable);
