import { Button, Card, Col, Image, message, Modal, Pagination, Row, Tabs, Tag } from "antd"
import React, { useMemo, useRef } from "react"
import { useCallback, useEffect, useState } from "react"
import { useModel } from "umi"
import Tables from "../Tables";
const { TabPane } = Tabs;
import style from './index.less'
/**微信图片弹窗 */
/**
 * 微信图片素材弹窗组件 
 * 
 * 立即回复 图片 视频 音频
 * 
 * 立即回复 延迟回复 新建推送里 图片 视频 音频
 * 
 * 高级群发 新建 图片消息 语言消息 视频消息
 */
const type = {
    'mpnews': 5,
    'mpvideo': 3,
    'voice': 2,
    'image': 1,
    'text': 4
}
type Props = {
    mediaType: number,
    visible: boolean,
    onOk: (url: string, type?: number) => void,
    onCancel: () => void,
    title: string,
    action?: any,
}
const ModalPage = (props: Props) => {
    const [action, setAction] = useState<any>(null)
    const { mediaType, visible, onOk, onCancel, title } = props
    const [selectedRowKeys, setSelectedRowKeys] = useState<string[] | number[]>([0])
    let refNews: { current: any } = useRef()
    const { getData, update } = useModel('useOperating.useMaterialContent', model => ({
        getData: model.getWeData,
        update: model.update
    }))
    const [pageNum, setPageNum] = useState(1)
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX, }))
    let config: any = {
        '5': 'news',
        '3': 'video',
        '2': 'voice',
        '1': 'image'
    }
    let types = useMemo(() => {
        return config[mediaType]
    }, [mediaType])

    useEffect(() => {
        getData.run({ mediaType: types, mpId: actionWX.id, pageNum: 1, pageSize: 10 })
    }, [actionWX.id, types])
    //同步更新
    const sync = () => {
        update.run({ mpId: actionWX?.id, mediaType: types }).then((res: any) => {
            if(res) {
                getData.run({ mediaType: types, mpId: actionWX.id, pageNum: pageNum, pageSize: 10 })
            }
        })
    }
    //选中图片
    let handleClick = useCallback((data) => {
        setAction(data)
    }, [])
    /**
     * 获取当前类型
     */
    
    //翻页
    let pageSizeChange = useCallback((pageNum, pageSize) => {
        setPageNum(pageNum)
        getData.run({
            mediaType: types,
            pageNum: pageNum,
            pageSize: pageSize,
            mpId: actionWX.id
        })
    }, [actionWX.id, types])
    //Ok
    let ok = () => {
        if (!action) {
            message.error('请选择素材')
            return
        }
        onOk({ ...action }, mediaType)
    }
    //编辑时选中默认
    useEffect(() => {
        setSelectedRowKeys([0])
        setAction(null)
        if (props.action && type[props?.action?.mediaType] === props.mediaType) {
            if (props?.action?.msgType === 'image') {
                setAction(props.action)
            } else {
                getData?.data?.records?.forEach((item: { mediaId: any }, index: number) => {
                    if (item?.mediaId === props?.action?.mediaId) {
                        setSelectedRowKeys([index + 1])
                        setAction(item)
                    }
                })
            }

        }
    }, [props.action, getData?.data])
    //table单选事件
    const rowSelection = {
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            setSelectedRowKeys(selectedRowKeys)
            setAction(selectedRows[0])
        }
    };
    return <Modal
        title={title}
        width={750}
        visible={visible}
        onOk={ok}
        onCancel={onCancel}
        destroyOnClose
    >
        <Tabs type="card" tabBarExtraContent={<Button type='primary' onClick={sync} loading={update?.loading}>同步最新素材</Button>}>
            <TabPane tab="公众号素材" key="1" style={{ padding: 10 }}>
                {
                    mediaType === 1 && <>
                        <Row justify='start' gutter={[15, 15]} style={{ height: 400, overflowY: 'scroll' }}>
                            {
                                getData?.data?.records?.map((item: any, index: number) => {
                                    return <Col key={item?.mediaId + index || item?.wxMediaId + index} className={`${style.img} ${action?.mediaId === item?.mediaId ? style.action : undefined}`}>
                                        <Card bodyStyle={{ padding: 0, display: 'flex', flexFlow: 'column' }} bordered={false} hoverable >
                                            <Image src={item?.url} width={150} placeholder preview={false} onClick={() => handleClick(item)} />
                                        </Card >
                                    </Col>
                                })
                            }
                        </Row>
                        <Pagination
                            onChange={pageSizeChange}
                            size={'small'}
                            defaultCurrent={1}
                            total={getData?.data?.total}
                            style={{ float: 'right' }}
                            showTotal={(total) => <Tag color="cyan">总共{total}数据</Tag>}
                            pageSizeOptions={['10', '20']}
                        />
                    </>
                }
                {
                    mediaType !== 1 && <Tables
                        dataSource={getData?.data?.records?.map((item: any, index: number) => ({ ...item, id: index + 1 })) || []}
                        columns={columns}
                        rowSelection={{
                            type: 'radio',
                            selectedRowKeys,
                            ...rowSelection
                        }}
                    />
                }

            </TabPane>
        </Tabs>
    </Modal >
}

export default ModalPage

const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        align: 'center',
    },
    {
        title: '素材名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
    },
    {
        title: '创建日期',
        dataIndex: 'updateTime',
        key: 'updateTime',
        align: 'center',
    },
]