import { Button, Input, Select, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../../../../tencentAdPutIn/index.less'
import { useAjax } from '@/Hook/useAjax';
import { getCorpWechatAllApi, getCustomerServiceGroupListApi, GetCustomerServiceGroupListProps, getLocalCorpCsgroupListAllApi, getUserRotatePolicyAllListApi } from '@/services/adqV3/global';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import columns from './tableConfig';
import AddCsGroup from './addCsGroup';

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

    /**********************************/
    const [queryParamsNew, setQueryParamsNew] = useState<GetCustomerServiceGroupListProps>({ pageNum: 1, pageSize: 20 })

    const [visible, setVisible] = useState<boolean>(false);
    const [corpWechatList, setCorpWechatList] = useState<{ label: string, value: string }[]>([]);
    const [userRotatePolicy, setUserRotatePolicy] = useState<{ label: string, value: string }[]>([]);
    const [localCorpCsgroupList, setLocalCorpCsgroupList] = useState<{ label: string, value: string }[]>([]);
    const [initialValues, setInitialValues] = useState<any>();

    const getCustomerServiceGroupList = useAjax((params) => getCustomerServiceGroupListApi(params))
    const getCorpWechatAll = useAjax((params) => getCorpWechatAllApi(params))
    const getUserRotatePolicyAllList = useAjax((params) => getUserRotatePolicyAllListApi(params))
    const getLocalCorpCsgroupListAll = useAjax((params) => getLocalCorpCsgroupListAllApi(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 })));
            }
        })
        getUserRotatePolicyAllList.run({}).then((res) => {
            if (res && res.length > 0) {
                setUserRotatePolicy(res.map((item: { policyName: string; id: string; }) => ({ label: item.policyName, value: item.id })));
            }
        })
    }, [])

    useEffect(() => {
        getList()
    }, [])

    const getList = () => {
        getLocalCorpCsgroupListAll.run({ type: 0 }).then((res) => {
            if (res && res.length > 0) {
                setLocalCorpCsgroupList(res.map((item: { csgroupName: string; id: string; }) => ({ label: item.csgroupName, value: item.id })));
            }
        })
    }

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

    const handleEdit = (data: any) => {
        setInitialValues({
            ...data,
            assignUserIdList: data?.assignUserList?.map((item: { userId: number }) => item.userId) || [],
            callUserIdList: data?.callUserList?.map((item: { userId: number }) => item.userId) || []
        })
        setVisible(true);
    }

    return <>
        <div className="flexStart" style={{ gap: 8, marginBottom: 16 }}>
            <Input.Search style={{ width: 200 }} enterButton placeholder='请输入客服组名称' onSearch={(e) => setQueryParamsNew({ ...queryParamsNew, csgroupName: e, pageNum: 1 })} allowClear />
            <Input.Search style={{ width: 190 }} enterButton placeholder='请输入媒体账户' onSearch={(e) => setQueryParamsNew({ ...queryParamsNew, accountId: e, pageNum: 1 })} allowClear />
            <Select
                showSearch
                placeholder="请选择企业"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 140 }}
                allowClear
                value={queryParamsNew?.tencentCorpId}
                loading={getCorpWechatAll.loading}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, tencentCorpId: e, pageNum: 1 })
                }}
                options={corpWechatList}
            />
            <Select
                showSearch
                placeholder="请选择轮换策略"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 140 }}
                allowClear
                value={queryParamsNew?.policyId}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, policyId: e, pageNum: 1 })
                }}
                options={userRotatePolicy}
            />
            <Select
                showSearch
                placeholder="请选择归属集"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 140 }}
                allowClear
                value={queryParamsNew?.parentId}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, parentId: e, pageNum: 1 })
                }}
                options={localCorpCsgroupList}
            />
            <Select
                showSearch
                placeholder="是否组集"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 100 }}
                allowClear
                value={queryParamsNew?.type}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, type: e, pageNum: 1 })
                }}
                options={[{ label: '是', value: 0 }, { label: '否', value: 1 }]}
            />
            <Select
                showSearch
                placeholder="关闭状态开关"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                }
                style={{ width: 130 }}
                allowClear
                value={queryParamsNew?.closeSwitch}
                onChange={(e) => {
                    setQueryParamsNew({ ...queryParamsNew, closeSwitch: e, pageNum: 1 })
                }}
                options={[{ label: '开启', value: false }, { label: '关闭', value: true }]}
            />
            <Button type="primary" icon={<SearchOutlined />} loading={getCustomerServiceGroupList.loading} onClick={() => getCustomerServiceGroupList.refresh()}>刷新</Button>
            <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                    setVisible(true)
                }}
            >新增</Button>
        </div>
        <Table
            columns={columns(handleEdit, () => getCustomerServiceGroupList.refresh())}
            dataSource={getCustomerServiceGroupList.data?.records}
            size="small"
            loading={getCustomerServiceGroupList?.loading}
            scroll={{ y: 600, x: 1000 }}
            rowKey={'id'}
            pagination={{
                total: getCustomerServiceGroupList.data?.total,
                defaultPageSize: 20,
                current: getCustomerServiceGroupList.data?.current,
                pageSize: getCustomerServiceGroupList.data?.size
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryParamsNew({ ...queryParamsNew, pageNum: current as number, pageSize: pageSize as number || 20 })
            }}
        />

        {/* 新增客服组 */}
        {visible && <AddCsGroup
            visible={visible}
            accountId={adAccountId as number}
            initialValues={initialValues}
            corpWechatList={corpWechatList}
            userRotatePolicy={userRotatePolicy}
            localCorpCsgroupList={localCorpCsgroupList}
            onChange={() => {
                getCustomerServiceGroupList.refresh();
                getList()
                setInitialValues(undefined);
                setVisible(false);
            }}
            onClose={() => {
                setInitialValues(undefined);
                setVisible(false);
            }}
        />}
    </>
};

export default React.memo(Group);