import { useAjax } from '@/Hook/useAjax';
import { delPageCustomerGroupApi, getAdqLandingPageOfficialListApi, getCorpRelationAllApi, getCustomerServiceGroupListApi, getPageCustomerGroupListApi, GetPageCustomerGroupListProps } from '@/services/adqV3/global';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, Input, message, Popconfirm, Select, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import AddPageTieUp from './addPageTieUp';
import { useDebounce } from 'ahooks';

/**
 * 落地页与客服组关系
 * @returns 
 */
const PageTieUp: React.FC<{ adAccountId?: number }> = ({ adAccountId }) => {

    /*******************************/
    const [queryParamsNew, setQueryParamsNew] = useState<GetPageCustomerGroupListProps>({ pageNum: 1, pageSize: 50, adAccountId: 0 })
    const [visible, setVisible] = useState<boolean>(false)
    const [corpList, setCorpList] = useState<{ label: string, value: string }[]>([])
    const [groupList, setGroupList] = useState<{ label: string, value: number }[]>([])
    const [queryForm, setQueryForm] = useState<{ accountId?: number, pageName?: string, ownerUid?: number, pageSize: number, pageNum: number, isSqDownPage: boolean }>({ pageNum: 1, pageSize: 20, isSqDownPage: false })
    const [pageName, setPageName] = useState<string>();
    const debouncedValue = useDebounce(pageName, { wait: 500 });

    const getPageCustomerGroupList = useAjax((params) => getPageCustomerGroupListApi(params))
    const delPageCustomerGroup = useAjax((params) => delPageCustomerGroupApi(params))
    const getCorpRelationAll = useAjax((params) => getCorpRelationAllApi(params))
    const getCustomerServiceGroupList = useAjax((params) => getCustomerServiceGroupListApi(params))
    const listAjax = useAjax((params) => getAdqLandingPageOfficialListApi(params))
    /*******************************/

    // 落地页
    useEffect(() => {
        if (adAccountId) {
            const params: any = {
                ...queryForm,
                // pageStatus: 'NORMAL',
                pageType: 'PAGE_TYPE_OFFICIAL',
                accountId: adAccountId,
                pageName: debouncedValue
            }
            delete params.isSqDownPage
            listAjax.run(params)
        }
    }, [adAccountId, queryForm, debouncedValue])

    /** 客服组 */
    useEffect(() => {
        if (adAccountId) {
            getCustomerServiceGroupList.run({ adAccountId, pageNum: 1, pageSize: 100, tencentCorpId: queryParamsNew?.tencentCorpId }).then(res => {
                setGroupList(res?.records?.map((item: { groupName: string; groupId: number; }) => ({ label: item.groupName, value: item.groupId })))
            }).catch(() => setGroupList([]))
        }
    }, [adAccountId, queryParamsNew?.tencentCorpId])

    /** 企业列表 */
    useEffect(() => {
        if (adAccountId) {
            getCorpRelationAll.run({ adAccountId }).then(res => {
                setCorpList(res?.map((item: { corpName: string; tencentCorpId: string; }) => ({ label: item.corpName, value: item.tencentCorpId })))
            }).catch(() => setCorpList([]))
        }
    }, [adAccountId])

    /** 获取关系列表 */
    useEffect(() => {
        if (adAccountId) {
            getPageCustomerGroupList.run({ ...queryParamsNew, adAccountId })
        }
    }, [adAccountId, queryParamsNew])


    /**
     * 删除
     * @param id 
     */
    const handleDel = (id: number) => {
        delPageCustomerGroup.run(id).then((res) => {
            if (res) {
                message.success('删除成功')
                getPageCustomerGroupList.refresh()
            }
        })
    }


    return <>
        <div className="flexStart" style={{ gap: 8, marginBottom: 16 }}>
            <Select
                showSearch
                placeholder="请选择企业"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 200 }}
                allowClear
                value={queryParamsNew?.tencentCorpId}
                loading={getCorpRelationAll.loading}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, tencentCorpId: e, pageNum: 1 })
                }}
                options={corpList}
            />
            <Select
                showSearch
                placeholder="请选择客服组"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 200 }}
                allowClear
                value={queryParamsNew?.customerGroupId}
                loading={getCustomerServiceGroupList.loading}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, customerGroupId: e, pageNum: 1 })
                }}
                options={groupList}
            />
            <Input style={{ width: 140 }} value={queryParamsNew?.customerGroupName} onChange={(e) => setQueryParamsNew({ ...queryParamsNew, pageNum: 1, customerGroupName: e.target.value })} placeholder='客服组名称' />
            <Select
                showSearch
                placeholder="请选择落地页"
                filterOption={false}
                style={{ width: 200 }}
                allowClear
                value={queryParamsNew?.pageId}
                loading={listAjax.loading}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, pageId: e, pageNum: 1 })
                }}
                defaultActiveFirstOption={false}
                showArrow={false}
                onSearch={(newValue: string) => {
                    setPageName(newValue)
                }}
                options={listAjax?.data?.records?.map((item: { pageId: number; pageName: string; }) => ({ label: item.pageName, value: item.pageId }))}
            />
            <Button type="primary" icon={<SearchOutlined />} loading={getPageCustomerGroupList.loading} onClick={() => getPageCustomerGroupList.refresh()}>刷新</Button>
            <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                    setVisible(true)
                }}
            >新增</Button>
        </div>

        <Table
            columns={[
                {
                    title: '广告账号',
                    dataIndex: 'adAccountId',
                    key: 'adAccountId',
                    width: 90,
                    ellipsis: true,
                    align: 'center',
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '落地页名称',
                    dataIndex: 'pageName',
                    key: 'pageName',
                    width: 120,
                    ellipsis: true,
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '落地页ID',
                    dataIndex: 'pageId',
                    key: 'pageId',
                    width: 100,
                    ellipsis: true,
                    align: 'center',
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '客服组名称',
                    dataIndex: 'customerGroupName',
                    key: 'customerGroupName',
                    width: 120,
                    ellipsis: true,
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '客服组ID',
                    dataIndex: 'customerGroupId',
                    key: 'customerGroupId',
                    align: 'center',
                    width: 100,
                    ellipsis: true,
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '投放端企业ID',
                    dataIndex: 'tencentCorpId',
                    key: 'tencentCorpId',
                    width: 300,
                    ellipsis: true,
                    render(value) {
                        return <span style={{ fontSize: 12 }}>{value}</span>
                    },
                },
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    width: 300,
                    render(_, record) {
                        return <Popconfirm
                            title="确定删除?"
                            onConfirm={() => handleDel(record.id)}
                        >
                            <a style={{ color: 'red', fontSize: 12 }}>删除</a>
                        </Popconfirm>
                    },
                },
            ]}
            dataSource={getPageCustomerGroupList.data?.records || []}
            loading={getPageCustomerGroupList.loading}
            scroll={{ x: 1000 }}
            pagination={{
                current: queryParamsNew.pageNum,
                pageSize: queryParamsNew.pageSize,
                total: getPageCustomerGroupList.data?.total,
                onChange: (pageNum, pageSize) => setQueryParamsNew({ ...queryParamsNew, pageNum, pageSize }),
            }}
            size="small"
            bordered
            rowKey="id"
        />

        {/* 新增 */}
        {visible && <AddPageTieUp
            adAccountId={adAccountId as number}
            corpList={corpList}
            visible={visible}
            onChange={() => {
                getPageCustomerGroupList.refresh()
                setVisible(false)
            }}
            onClose={() => {
                setVisible(false)
            }}
        />}
    </>;
};

export default React.memo(PageTieUp);