import { useRef, useState, useEffect } from 'react';
import { connect, history } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, ProForm, ProFormSelect
} from '@ant-design/pro-components';
import { Button, Image, ConfigProvider, Popconfirm, message, Modal , Space} from 'antd';
import { listArticle, listSection, delArticle, updateArticle } from '@/apis/api';
import { Imageprefix } from '@/constants';
const selectfieldNames = { label: 'name', value: 'id', children: 'childs' };
import UploadModel from '@/components/Common/upload';

const PagesMainInformationArticleTable: 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: 6, 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 delArticle({ 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: 'section_name',
                        search: false,
                        width: 200,
                    },
                    {
                        title: '所属栏目',
                        dataIndex: 'section_id',
                        hidden: true,
                        valueType: 'select',
                        renderFormItem: () => {
                            return (
                                <ProFormSelect
                                    width='lg'
                                    fieldProps={{
                                        fieldNames: selectfieldNames,
                                    }}
                                    request={async (keyword) =>
                                        listSection({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                            return res.data.sections;
                                        })
                                    }
                                    placeholder="请选择所属栏目"
                                />
                            )
                        }
                    },
                    {
                        title: '封面图',
                        dataIndex: 'cover_img',
                        search: false,
                        width: 200,
                        render: (_, record) => (<>
                            <Image src={`${Imageprefix}${record.cover_img}`} width={60} height={60} />
                        </>
                        )
                    },
                    {
                        title: '置顶',
                        dataIndex: 'stick_top',
                        width: 200,
                        valueEnum: {
                            0: { text: '全部' },
                            1: {
                                text: '置顶',
                                status: 'Processing'
                            },
                            2: {
                                text: '未置顶',
                                status: 'Error'
                            },
                        },
                    },
                    {
                        title: '热门',
                        dataIndex: 'hot',
                        search: false,
                        width: 200,
                        valueEnum: {
                            0: { text: '全部' },
                            1: {
                                text: '热门推荐',
                                status: 'Processing'
                            },
                            2: {
                                text: '普通',
                                status: 'Error'
                            },
                        },
                    },

                    {
                        title: '作者',
                        dataIndex: 'author',
                        search: false,
                        width: 200,

                    },
                    {
                        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="cover_img" image_length={1} uploadTxt="更换图片" image_type={3} imageUrl={record.cover_img} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                        </ProForm>
                                    </>),
                                    async onOk() {
                                        let res = await updateArticle({ ...record, cover_img: uploadedFilephotoNameRef.current });
                                        setUploadedFilephotoName('');
                                        actionRef.current?.reload();
                                    },
                                    onCancel() {
                                        console.log('Cancel');
                                    },
                                    okText: '保存',
                                    cancelText: '取消',
                                    centered: true,
                                });
                            }}>更换图片</Button>,
                            <Popconfirm
                                title="是否删除"
                                onConfirm={(e) => {
                                    delArticle({ 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>) =>
                        listArticle({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,
                            section_id: params.section_id
                        }).then(res => {
                            setList(res.data.articles)
                            setTotal(res.data.total)
                        })
                    }
                    headerTitle="文章列表"
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            添加文章
                        </Button>
                    ]}
                />
            </ConfigProvider>
        </>
    );
};


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