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

/**
 * 文案库
 * @returns 
 */
const CopyWriting: React.FC = () => {

    /*************************************/
    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 [visible, setVisible] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])

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

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

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

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

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

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <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={() => { setVisible(true) }}>新增文案</Button>
            <Popconfirm
                title="确定删除?"
                onConfirm={() => {
                    delsCopyWriting.run(selectedRows.map(item => item.id)).then(res => {
                        if (res) {
                            message.success('删除成功')
                            getCopyWritingList.refresh()
                        }
                    })
                }}
                disabled={selectedRows.length === 0}
            >
                <Button type="primary" loading={delsCopyWriting.loading} icon={<DeleteOutlined />} danger disabled={selectedRows.length === 0}>删除</Button>
            </Popconfirm>
        </div>}
    >

        <Table
            columns={columns(del, update)}
            dataSource={getCopyWritingList.data?.records}
            size="small"
            loading={getCopyWritingList?.loading}
            scroll={{ y: 600, x: 1100 }}
            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])
                    }
                }
            }}
        />


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

export default CopyWriting