import { Badge, Button, Checkbox, Input, Select, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../../../../tencentAdPutIn/index.less'
import { getAdqLandingPageOfficialListApi, getWXDownPageAuthInfoListApi } from '@/services/adqV3/global';
import { useAjax } from '@/Hook/useAjax';
import { SyncOutlined } from '@ant-design/icons';
import { PageStatusEnum } from '@/services/launchAdq/enum';

/**
 * 选择落地页
 * @returns 
 */
const SelectPage: React.FC<{ accountId: number, value?: any, onChange?: (e: any) => void }> = ({ accountId, value, onChange }) => {

    /***********************************/
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [queryForm, setQueryForm] = useState<{ accountId?: number, pageName?: string, ownerUid?: number, pageSize: number, pageNum: number, isSqDownPage: boolean }>({ pageNum: 1, pageSize: 20, isSqDownPage: false })
    const [wXDownPageAuthInfo, setWXDownPageAuthInfo] = useState<any[]>([])
    const [tableData, setTableData] = useState<any>({})

    const listAjax = useAjax((params) => getAdqLandingPageOfficialListApi(params))
    const getWXDownPageAuthInfoList = useAjax((params) => getWXDownPageAuthInfoListApi(params))
    /***********************************/

    useEffect(() => {
        getWXDownPageAuthInfoList.run(accountId).then(res => {
            if (res && res.length > 0) {
                setWXDownPageAuthInfo(res)
            }
        })
    }, [accountId])

    useEffect(() => {
        if (value && JSON.stringify(value) !== JSON.stringify(selectedRowKeys)) {
            setSelectedRowKeys(value)
        }
    }, [value])

    useEffect(() => {
        if (accountId) {
            const params: any = {
                ...queryForm,
                pageStatus: 'NORMAL',
                pageType: 'PAGE_TYPE_OFFICIAL',
                accountId,
                // marketingTargetType: "MARKETING_TARGET_TYPE_WECHAT_WORK"
            }
            if (params.isSqDownPage) {
                if (!params?.ownerUid) {
                    setTableData({ total: 0, records: [] })
                    return
                }
            } else {
                delete params?.ownerUid
            }
            delete params.isSqDownPage
            listAjax.run(params).then(res => {
                setTableData(res || {})
            })
        }
    }, [accountId, queryForm])

    return <div>
        <Space style={{ marginBottom: 10 }}>
            <Checkbox
                onChange={(e) => {
                    if (e.target.checked && wXDownPageAuthInfo && Object.keys(wXDownPageAuthInfo).length) {
                        setQueryForm({ ...queryForm, pageNum: 1, ownerUid: wXDownPageAuthInfo?.[0]?.accountId, isSqDownPage: true })
                    } else {
                        setQueryForm({ ...queryForm, pageNum: 1, ownerUid: undefined, isSqDownPage: false })
                    }
                }}
                checked={queryForm.isSqDownPage}
            ><span style={{ fontSize: 12 }}>被授权落地页</span></Checkbox>
            {queryForm.isSqDownPage && <Select
                placeholder='选择原生页授权方信息'
                style={{ width: 200 }}
                showSearch
                filterOption={(input: any, option: any) =>
                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                }
                allowClear
                onChange={(value) => {
                    setQueryForm({ ...queryForm, pageNum: 1, ownerUid: value })
                }}
                value={queryForm?.ownerUid}
                dropdownMatchSelectWidth={false}
            >
                {wXDownPageAuthInfo?.map((item: { accountId: number; accountName: string }) => {
                    return <Select.Option value={item.accountId} key={item.accountId}>{item.accountName}({item.accountId})</Select.Option>
                })}
            </Select>}
            <Input value={queryForm?.pageName} style={{ width: 180 }} allowClear placeholder='请输入官方落地页名称' onChange={(e) => setQueryForm({ ...queryForm, pageNum: 1, pageName: e.target.value })} />
            <Button style={{ padding: 0, margin: 0 }} icon={<SyncOutlined />} type='link' loading={listAjax?.loading} onClick={() => { listAjax?.refresh() }}><span style={{ fontSize: 12 }}>刷新</span></Button>
        </Space>

        <Table
            columns={[
                {
                    title: '官方落地页ID',
                    dataIndex: 'pageId',
                    key: 'pageId',
                    align: 'center',
                    width: 85
                },
                {
                    title: '官方落地页名称',
                    dataIndex: 'pageName',
                    key: 'pageName',
                    ellipsis: true,
                    width: 300
                },
                {
                    title: '官方落地页状态',
                    dataIndex: 'pageStatus',
                    key: 'pageStatus',
                    align: 'center',
                    width: 90,
                    render: (a: string | number) => {
                        return <Badge status={a === 'NORMAL' ? "success" : a === 'DELETED' ? "error" : 'processing'} text={PageStatusEnum[a as keyof typeof PageStatusEnum]} />
                    }
                },
            ]}
            dataSource={tableData?.records}
            size="small"
            loading={listAjax?.loading}
            scroll={{ y: 280 }}
            bordered
            rowKey={'pageId'}
            pagination={{
                total: tableData?.total,
                defaultPageSize: 20,
                current: tableData?.current,
                pageSize: tableData?.size
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryForm({ ...queryForm, pageNum: current as number, pageSize: pageSize as number || 20 })
            }}
            rowSelection={{
                selectedRowKeys: selectedRowKeys?.map((item: any) => item?.pageId),
                onChange(_, selectedRows) {
                    setSelectedRowKeys(selectedRows)
                    onChange?.(selectedRows)
                },
            }}
        />
    </div>;
};

export default SelectPage;