import { Button, Card, Input, message, Popconfirm, Select, Table } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { delPageApi, getAdqLandingPageListApi, getWXDownPageAuthInfoListApi } from "@/services/adqV3/global";
import { useAjax } from "@/Hook/useAjax";
import { useModel } from "umi";
import { SearchOutlined } from "@ant-design/icons";
import columns from "./tableConfig";
import CopyPage from "./copyPage";

interface AjaxProps {
    pageNum: number;
    pageSize: number;
    accountId?: number;
    pageName?: string;
    pageType?: string;
    pageStatus?: string;
    ownerUid?: number;
}
/**
 * 原生推广页
 * @returns 
 */
const WechatCanvasPage: React.FC = () => {

    /********************************/
    const { getAllUserAccount } = useModel('useLaunchAdq.useAdAuthorize')
    const [queryParamsNew, setQueryParamsNew] = useState<AjaxProps>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)
    const [pageData, setPageData] = useState<any>()
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getAdqLandingPageList = useAjax((params) => getAdqLandingPageListApi(params))
    const getWXDownPageAuthInfoList = useAjax((params) => getWXDownPageAuthInfoListApi(params))
    const delPage = useAjax((params) => delPageApi(params))
    /********************************/

    useEffect(() => {
        // 获取账户列表
        getAllUserAccount.run().then(res => {
            setQueryParamsNew({ ...queryParamsNew, accountId: res?.data?.[0]?.accountId })
        })
    }, [])

    // 落地页列表
    useEffect(() => {
        if (queryParamsNew?.accountId) {
            getAdqLandingPageList.run(queryParamsNew)
        }
    }, [queryParamsNew])

    // 授权落地页
    useEffect(() => {
        if (queryParamsNew?.accountId) {
            getWXDownPageAuthInfoList.run(queryParamsNew.accountId)
        }
    }, [queryParamsNew.accountId])

    // 批量复制
    const handleCopy = (data: any) => {
        setVisible(true)
        setPageData(data)
    }

    const handleDel = () => {
        delPage.run({ accountId: queryParamsNew.accountId, pageIds: selectedRows.map(item => item.pageId) }).then(res => {
            if (res?.length === 0) {
                message.success('删除成功，结果可能会延迟几分钟返回')
                getAdqLandingPageList.refresh()
                setSelectedRows([])
            }
        })
    }

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Select
                placeholder="请先选择媒体账户"
                maxTagCount={1}
                style={{ width: 250 }}
                autoClearSearchValue={false}
                filterOption={(input: any, option: any) => {
                    let newInput: string[] = input ? input?.split(/[,，\n\s]+/ig).filter((item: any) => item) : []
                    return newInput?.some(val => option!.children?.toString().toLowerCase()?.includes(val))
                }}
                value={queryParamsNew.accountId}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, accountId: e, ownerUid: undefined })
                }}
                showSearch
            >
                {getAllUserAccount?.data?.data?.map((item: any) => <Select.Option value={item.accountId} key={item.id}>{item.remark ? item.accountId + '_' + item.remark : item.accountId}</Select.Option>)}
            </Select>
            {queryParamsNew?.accountId && <>
                <Select
                    placeholder='选择原生页授权方信息'
                    style={{ width: 210 }}
                    showSearch
                    filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    onChange={(value) => {
                        setQueryParamsNew({ ...queryParamsNew, pageNum: 1, ownerUid: value })
                    }}
                    loading={getWXDownPageAuthInfoList.loading}
                    value={queryParamsNew?.ownerUid}
                    dropdownMatchSelectWidth={false}
                >
                    {getWXDownPageAuthInfoList.data?.map((item: { accountId: number; accountName: string }) => {
                        return <Select.Option value={item.accountId} key={item.accountId}>{item.accountName}({item.accountId})</Select.Option>
                    })}
                </Select>
                <Input value={queryParamsNew?.pageName} style={{ width: 180 }} allowClear placeholder='请输入落地页名称' onChange={(e) => setQueryParamsNew({ ...queryParamsNew, pageNum: 1, pageName: e.target.value })} />
            </>}

            <Button type="primary" icon={<SearchOutlined />} loading={getAdqLandingPageList.loading} onClick={() => getAdqLandingPageList.refresh()}>刷新</Button>
            <Popconfirm
                title="确定删除?"
                onConfirm={() => handleDel?.()}
            >
                <Button danger loading={delPage.loading} disabled={selectedRows.length === 0 || !!queryParamsNew?.ownerUid}>删除</Button>
            </Popconfirm>
        </div>}
    >
        <Table
            columns={columns(handleCopy, () => getAdqLandingPageList.refresh(), queryParamsNew.accountId)}
            dataSource={getAdqLandingPageList.data?.records}
            size="small"
            loading={getAdqLandingPageList?.loading || getAllUserAccount.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'pageId'}
            pagination={{
                total: getAdqLandingPageList.data?.total,
                defaultPageSize: 20,
                current: getAdqLandingPageList.data?.current,
                pageSize: getAdqLandingPageList.data?.size
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryParamsNew({ ...queryParamsNew, pageNum: current as number, pageSize: pageSize as number || 20 })
            }}
            rowSelection={{
                selectedRowKeys: selectedRows.map(item => item.pageId),
                getCheckboxProps: (record: any) => {
                    return {
                        disabled: !!queryParamsNew?.ownerUid || record?.canvasType === 'COMMON_PAGE'
                    }
                },
                onSelect: (record: { pageId: number }, selected: boolean) => {
                    if (selected) {
                        selectedRows.push({ ...record })
                        setSelectedRows([...selectedRows])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { pageId: number }) => item.pageId !== record.pageId)
                        setSelectedRows([...newSelectAccData])
                    }
                },
                onSelectAll: (selected: boolean, selectedRowss: { pageId: number }[], changeRows: { pageId: number }[]) => {
                    if (selected) {
                        let newSelectAccData = [...selectedRows]
                        changeRows.forEach((item: { pageId: number }) => {
                            let index = newSelectAccData.findIndex((ite: { pageId: number }) => ite.pageId === item.pageId)
                            if (index === -1) {
                                let data: any = { ...item }
                                newSelectAccData.push(data)
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    } else {
                        let newSelectAccData = selectedRows.filter((item: { pageId: number }) => {
                            let index = changeRows.findIndex((ite: { pageId: number }) => ite.pageId === item.pageId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        setSelectedRows([...newSelectAccData])
                    }
                }
            }}
        />

        {visible && <CopyPage
            accountId={queryParamsNew.accountId as number}
            pageData={pageData}
            visible={visible}
            onClose={() => {
                setVisible(false)
                setPageData(undefined)
            }}
            onChange={() => {
                setVisible(false)
                setPageData(undefined)
                getAdqLandingPageList.refresh()
            }}
        />}
    </Card>
}

export default WechatCanvasPage