import { useAjax } from "@/Hook/useAjax"
import { delCopyWritingApi, getCopyWritingListApi } from "@/services/adqV3/global"
import { PlusOutlined, SearchOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Select, Space, Table } from "antd"
import React, { useEffect, useState } from "react"
import ModifyCopyWriting from "./modifyCopyWriting"
import columns from "./tableConfig"
import '../../tencentAdPutIn/index.less'
import { getErpUserAll } from "@/services/launchAdq/adq"

interface Props {
    onChange?: (value: string[]) => void
    onClick?: React.MouseEventHandler<HTMLElement>
}

const SelectCopyWriting: React.FC<Props> = ({ onChange, onClick }) => {

    /**********************************/
    const [visible, setVisible] = useState<boolean>(false)
    const [queryForm, setQueryForm] = useState<{ category?: string, content?: string, createBy?: number, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<{ category?: string, content?: string, createBy?: number, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [initialValues, setInitialValues] = useState<any>()
    const [mvisible, setMVisible] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getCopyWritingList = useAjax((params) => getCopyWritingListApi(params))
    const delCopyWriting = useAjax((params) => delCopyWritingApi(params))
    const allOfMember = useAjax(() => getErpUserAll())
    /**********************************/

    useEffect(() => {
        allOfMember.run()
    }, [])

    useEffect(() => {
        if (visible)
            getCopyWritingList.run(queryFormNew)
    }, [queryFormNew, visible])

    const del = (id: number) => {
        delCopyWriting.run(id).then(res => {
            if (res) {
                message.success('删除成功')
                getCopyWritingList.refresh()
            }
        })
    }

    const update = (data: any) => {
        setInitialValues(data)
        setMVisible(true)
    }

    const handleOk = () => {
        if (selectedRows.length > 0) {
            onChange?.(selectedRows.map(item => item.content))
            setSelectedRows([])
            setVisible(false)
        } else {
            message.error('请选择文案')
        }
    }

    return <>
        <Button type="link" style={{ padding: 0, fontSize: 12 }} onClick={(e) => {
            setVisible(true)
            onClick?.(e)
        }}>选择文案</Button>
        {visible && <Modal
            title={<strong>选择文案</strong>}
            open={visible}
            onCancel={() => {
                setVisible(false)
                setSelectedRows([])
            }}
            onOk={handleOk}
            className="modalResetCss"
            width={1000}
        >
            <Space style={{ width: '100%' }} direction="vertical">
                <Space>
                    <Select
                        showSearch
                        placeholder="请选择创建人"
                        onChange={(e) => setQueryForm({ ...queryForm, createBy: e, pageNum: 1 })}
                        filterOption={(input, option) =>
                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        allowClear
                        style={{ width: 140 }}
                        options={allOfMember?.data?.map((item: { userId: any; nickname: string }) => ({
                            value: item.userId,
                            label: item.nickname,
                        }))}
                    />
                    <Input style={{ width: 200 }} placeholder="文案分类" value={queryForm?.category} allowClear onChange={(e) => setQueryForm({ ...queryForm, category: e.target.value, pageNum: 1 })} />
                    <Input style={{ width: 200 }} placeholder="关键字" value={queryForm?.content} allowClear onChange={(e) => setQueryForm({ ...queryForm, content: e.target.value, pageNum: 1 })} />

                    <Button type="primary" icon={<SearchOutlined />} onClick={() => setQueryFormNew({ ...queryForm })}>搜索</Button>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => { setMVisible(true) }}>新增文案</Button>
                </Space>

                <Table
                    columns={columns(del, update)}
                    dataSource={getCopyWritingList.data?.records}
                    size="small"
                    loading={getCopyWritingList?.loading}
                    scroll={{ y: 600, x: 850 }}
                    bordered
                    rowKey={'id'}
                    pagination={{
                        defaultPageSize: 20,
                        current: getCopyWritingList.data?.current || 1,
                        pageSize: getCopyWritingList.data?.size || 10,
                        total: getCopyWritingList.data?.total || 0
                    }}
                    onChange={(pagination) => {
                        const { current, pageSize } = pagination
                        setQueryForm({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                        setQueryFormNew({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                    }}
                    rowSelection={{
                        selectedRowKeys: selectedRows.map(item => item.id.toString()),
                        onSelect: (record: { id: number, mpName: string }, selected: boolean) => {
                            if (selected) {
                                selectedRows.push({ ...record })
                                setSelectedRows([...selectedRows])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                                setSelectedRows([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            }
                        }
                    }}
                />

            </Space>
        </Modal>}

        {/* 新增文案修改文案 */}
        {mvisible && <ModifyCopyWriting
            visible={mvisible}
            initialValues={initialValues}
            onChange={() => {
                setInitialValues(undefined)
                setMVisible(false)
                getCopyWritingList.refresh()
            }}
            onClose={() => {
                setInitialValues(undefined)
                setMVisible(false)
            }}
        />}
    </>
}


export default React.memo(SelectCopyWriting)