import { Button, Input, message, Select, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../../../../tencentAdPutIn/index.less'
import { useAjax } from '@/Hook/useAjax';
import { getCorpWechatAllApi, getTencentCorpCsgroupListApi, GetTencentCorpCsgroupListProps, syncencentCorpCsgroupApi } from '@/services/adqV3/global';
import { PlusOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons';
import columns from './tableConfig';
import AddTencentGroup from './addTencentGroup';
import BandLocal from './bandLocal';

const TencentGroup: React.FC<{ adAccountId?: number }> = ({ adAccountId }) => {

    /**********************************/
    const [queryParamsNew, setQueryParamsNew] = useState<GetTencentCorpCsgroupListProps>({ pageNum: 1, pageSize: 20 })
    const [corpWechatList, setCorpWechatList] = useState<{ label: string, value: string }[]>([]);
    const [addData, setAddData] = useState<{ visible: boolean, initialValues: any }>({ visible: false, initialValues: undefined });
    const [bandData, setBandData] = useState<{ visible: boolean, data: any }>({ visible: false, data: undefined });

    const getTencentCorpCsgroupList = useAjax((params) => getTencentCorpCsgroupListApi(params))
    const getCorpWechatAll = useAjax((params) => getCorpWechatAllApi(params))
    const syncencentCorpCsgroup = useAjax((params) => syncencentCorpCsgroupApi(params))
    /**********************************/

    useEffect(() => {
        getCorpWechatAll.run({}).then((res) => {
            if (res && res.length > 0) {
                setCorpWechatList(res.map((item: { corpName: string; tencentCorpId: string; }) => ({ label: item.corpName, value: item.tencentCorpId })));
            }
        })
    }, [])

    useEffect(() => {
        if (adAccountId) {
            getTencentCorpCsgroupList.run({ ...queryParamsNew, accountId: adAccountId })
        }
    }, [queryParamsNew, adAccountId])

    const handleBand = (record: any) => {
        setBandData({ visible: true, data: record })
        // setAddData({ visible: true, initialValues: record })
    };


    const syncGroup = (value?: any) => {
        const hide = message.loading('同步中...', 0);
        let params: { [x: string]: any } = { accountId: adAccountId }
        if (value?.groupId) {
            params.tencentCorpId = value.tencentCorpId
            params.groupId = value.groupId
        } else {
            params.tencentCorpId = queryParamsNew.tencentCorpId
        }
        syncencentCorpCsgroup.run(params).then(() => {
            hide()
            getTencentCorpCsgroupList.refresh()
        }).catch(() => hide())
    }


    return <>
        <div className="flexStart" style={{ gap: 8, marginBottom: 16 }}>
            <Input.Search
                style={{ width: 220 }}
                enterButton
                placeholder='请输入客服组名称'
                onSearch={(e) => setQueryParamsNew({ ...queryParamsNew, groupName: e, pageNum: 1 })}
                allowClear
            />
            <Select
                showSearch
                placeholder="请选择企业"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 150 }}
                value={queryParamsNew?.tencentCorpId}
                onChange={(e) => setQueryParamsNew({ ...queryParamsNew, tencentCorpId: e, pageNum: 1 })}
                allowClear
                options={corpWechatList}
            />
            <Button type="primary" icon={<SearchOutlined />} loading={getTencentCorpCsgroupList.loading} onClick={() => getTencentCorpCsgroupList.refresh()}>刷新</Button>
            <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                    setAddData({ visible: true, initialValues: undefined })
                }}
            >新增</Button>
            <Button
                type="primary"
                style={{ backgroundColor: '#FAAD14', borderColor: '#FAAD14' }}
                icon={<SyncOutlined />}
                disabled={queryParamsNew?.tencentCorpId === undefined}
                onClick={syncGroup}
                loading={syncencentCorpCsgroup.loading}
            >同步</Button>
        </div>
        <Table
            columns={columns(handleBand, syncGroup)}
            dataSource={getTencentCorpCsgroupList.data?.records}
            size="small"
            loading={getTencentCorpCsgroupList?.loading}
            scroll={{ y: 600, x: 1000 }}
            rowKey={'groupId'}
            pagination={{
                total: getTencentCorpCsgroupList.data?.total,
                defaultPageSize: 20,
                current: getTencentCorpCsgroupList.data?.current,
                pageSize: getTencentCorpCsgroupList.data?.size
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryParamsNew({ ...queryParamsNew, pageNum: current as number, pageSize: pageSize as number || 20 })
            }}
        />

        {/* 设置修改腾讯组 */}
        {addData?.visible && <AddTencentGroup
            {...addData}
            adAccountId={adAccountId as number}
            corpWechatList={corpWechatList}
            onClose={() => {
                setAddData({ visible: false, initialValues: undefined })
            }}
            onChange={() => {
                getTencentCorpCsgroupList.refresh();
                setAddData({ visible: false, initialValues: undefined });
            }}
        />}

        {/* 绑定本地客服组 */}
        {bandData?.visible && <BandLocal
            {...bandData}
            accountId={adAccountId as number}
            onClose={() => {
                setBandData({ visible: false, data: undefined })
            }}
            onChange={() => {
                getTencentCorpCsgroupList.refresh();
                setBandData({ visible: false, data: undefined });
            }}
        />}
    </>
};

export default React.memo(TencentGroup);