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, Image, ConfigProvider, Popconfirm, message, Modal,Radio, Row, Col} from 'antd';
import { listSection, delSection } from '@/apis/api';
import { Imageprefix } from '@/constants';
import UploadModel from '@/components/Common/upload';

const PagesMainInformationSectionTable: 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 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' }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    columns={[
                        {
                            title: 'ID',
                            dataIndex: 'id',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '栏目名称',
                            dataIndex: 'name',
                            width: 200,
                        },
                        {
                            title: '栏目编码',
                            dataIndex: 'code',
                            width: 200,
                        },
                        {
                            title: '可见',
                            dataIndex: 'display',
                            width: 200,
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '可见',
                                    status: 'Processing'
                                },
                                2: {
                                    text: '不可见',
                                    status: 'Error'
                                },
                            },
                        },
                        {
                            title: '封面图',
                            dataIndex: 'cover_img',
                            search: false,
                            width: 200,
                            render: (_, record) => (<>
                                <Image src={`${Imageprefix}${record.cover_img}`} width={40} height={40} />
                            </>
                            )
                        },
                        {
                            title: '描述',
                            dataIndex: 'description',
                            width: 200,

                            search: false
                        },
                        {
                            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 info = await GetCompanyInfo({ id: record.id });
                                            // let res = await updateCompany({ ...info.data, license_path: uploadedFilelicenseNameRef.current });
                                            // setUploadedFilelicenseName('');
                                            actionRef.current?.reload();
                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '保存',
                                        cancelText: '取消',
                                        centered: true,
                                    });
                                }}>更换图片</Button>,
                                <Button key='1' type='link' onClick={() => {
                                    record.nextlevel = record.id // 添加下级栏目，把id赋值给nextlevel
                                    setId(record)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>添加下级栏目</Button>,
                                <Popconfirm
                                    title="是否删除"
                                    onConfirm={(e) => {
                                        delSection({ id: record.id }).then(res => {
                                            message.success('删除成功')
                                            actionRef.current.reload();
                                        })
                                    }}
                                    okText="删除"
                                    cancelText="取消"
                                >
                                    <Button
                                        danger
                                        type='link'
                                        key="delete"
                                    >
                                        删除
                                    </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>) =>
                        listSection({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,

                        }).then(res => {
                            setList(res.data.sections)
                            setTotal(res.data.total)
                        })
                    }
                    headerTitle="栏目/频道"
                    toolBarRender={() => [<Button type="primary" onClick={() => {
                        Modal.confirm({
                            title: '请选择对批量数据进行何种操作',
                            content: (<>
                                <div>参数：id, display</div>

                                <Radio.Group size='small' onChange={async (e) => {

                                    actionRef.current?.reload();
                                }}>
                                      <Radio value={1}>可见</Radio>
                                      <Radio value={1}>不可见</Radio>
                                </Radio.Group>
                            </>),
                            onOk() {

                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                            okText: '保存',
                            cancelText: '取消',
                            centered: true
                        });
                    }}>
                        批量管理可见状态
                    </Button>,
                    <Button type="primary" onClick={() => {
                        dispatch({ type: 'openModel/getOpenModal', payload: true })
                    }}>
                        添加栏目/频道
                    </Button>
                    ]}
                    expandable={{
                        childrenColumnName: 'childs', // 指定子节点数据的字段名
                    }}
                />
            </ConfigProvider>
        </>
    );
};


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