import { useAjax } from "@/Hook/useAjax"
import React, { useEffect, useState } from "react"
import { AreaChartOutlined, SearchOutlined } from "@ant-design/icons"

import { GetExternalUserRepeatByCorpListApiProps, getSelectQcUuidStatisticPageListApi } from "../../../API/home"
import { Button, Card, Checkbox, Divider, Input, InputNumber, Select, Space, Table, Typography, Image } from "antd";
import SearchBox from "../../../components/searchBox";
import CorpDetails from "./corpDetails";
import CorpUserDetails from "./corpUserDetails";
const { Title, Text } = Typography;

const UuidTem: React.FC<{ getCorpAllList: { label: string, value: string }[] }> = ({ getCorpAllList }) => {

    /*****************************************/
    const [queryParmas, setQueryParmas] = useState<GetExternalUserRepeatByCorpListApiProps>({ pageNum: 1, pageSize: 20 })
    const [queryParmasNew, setQueryParmasNew] = useState<GetExternalUserRepeatByCorpListApiProps>({ pageNum: 1, pageSize: 20 })
    const [filtered, setFiltered] = useState<{ label: string, value: string }[]>(getCorpAllList);

    const getSelectQcUuidStatisticPageList = useAjax((params) => getSelectQcUuidStatisticPageListApi(params))
    /*****************************************/

    useEffect(() => {
        setFiltered(getCorpAllList);
    }, [getCorpAllList])

    useEffect(() => {
        getSelectQcUuidStatisticPageList.run(queryParmas)
    }, [queryParmas])

    const handleSearch = (val) => {
        const f = getCorpAllList.filter((item) => {
            const inputStr = val.replace(/[,，\s]/g, ',');
            if (inputStr && inputStr.includes(',')) {
                const inputList = inputStr.split(',').filter((it) => it).map(i => i.toLowerCase());
                return inputList.includes(((item?.label ?? '') as string).toLowerCase())
            }
            return ((item?.label ?? '') as string).toLowerCase().includes(val.toLowerCase())
        });
        setFiltered(f);
    };

    return <>
        <Title level={3}><AreaChartOutlined style={{ color: '#ff85c0' }} /> Uuid维度统计列表</Title>
        <SearchBox
            bodyPadding={`16px 0 12px`}
            buttons={<>
                <Button onClick={() => {
                    setQueryParmas({ pageNum: 1, pageSize: queryParmas.pageSize })
                    setQueryParmasNew({ pageNum: 1, pageSize: queryParmas.pageSize })
                }}>重置</Button>
                <Button type="primary" onClick={() => {
                    setQueryParmas({ ...queryParmasNew, pageNum: 1, pageSize: queryParmas.pageSize })
                }} loading={getSelectQcUuidStatisticPageList.loading} icon={<SearchOutlined />}>搜索</Button>
            </>}
        >
            <>
                <Select
                    value={queryParmasNew?.corpIdList}
                    onChange={(e) => setQueryParmasNew({ ...queryParmasNew, corpIdList: e })}
                    showSearch
                    style={{ minWidth: 150 }}
                    maxTagCount={1}
                    mode='multiple'
                    placeholder="选择企业"
                    filterOption={false}
                    onSearch={handleSearch}
                    allowClear
                    options={filtered}
                    popupRender={(menu) => (
                        <>
                            {menu}
                            <Divider style={{ margin: '8px 0' }} />
                            <Space style={{ padding: '0 8px 4px' }}>
                                <Checkbox onChange={(e) => {
                                    if (e.target.checked) {
                                        setQueryParmasNew({ ...queryParmasNew, corpIdList: filtered.map(item => item.value) })
                                    } else {
                                        setQueryParmasNew({ ...queryParmasNew, corpIdList: [] })
                                    }
                                }}>全选</Checkbox>
                            </Space>
                        </>
                    )}
                />
                <Input onChange={(e) => setQueryParmasNew({ ...queryParmasNew, corpName: e.target.value })} value={queryParmasNew?.corpName} placeholder="企微名称" allowClear />
                <Input onChange={(e) => setQueryParmasNew({ ...queryParmasNew, name: e.target.value })} value={queryParmasNew?.name} placeholder="客户昵称" allowClear />
                <InputNumber placeholder="最小企业id个数" style={{ width: 125 }} value={queryParmasNew?.minCorpIdCount} onChange={(e) => setQueryParmasNew({ ...queryParmasNew, minCorpIdCount: e })} />
                <InputNumber placeholder="最大企业id个数" style={{ width: 125 }} value={queryParmasNew?.maxCorpIdCount} onChange={(e) => setQueryParmasNew({ ...queryParmasNew, maxCorpIdCount: e })} />
                <InputNumber placeholder="最小客服号id个数" style={{ width: 125 }} value={queryParmasNew?.minCorpUserIdCount} onChange={(e) => setQueryParmasNew({ ...queryParmasNew, minCorpUserIdCount: e })} />
                <InputNumber placeholder="最大客服号id个数" style={{ width: 125 }} value={queryParmasNew?.maxCorpUserIdCount} onChange={(e) => setQueryParmasNew({ ...queryParmasNew, maxCorpUserIdCount: e })} />
            </>
        </SearchBox>
        <Card>
            <Table
                columns={[
                    {
                        title: '客户名称',
                        dataIndex: 'name',
                        key: 'name',
                        width: 180,
                        render: (text: any, record: any) => {
                            return <Space>
                                <Image src={record?.avatar} style={{ width: 20, borderRadius: 4 }} />
                                <Text>{text}</Text>
                            </Space>
                        }
                    },
                    {
                        title: '企业ID个数',
                        dataIndex: 'corpIdCount',
                        key: 'corpIdCount',
                        width: 120,
                        align: 'center',
                        sorter: true,
                        render: (text: number, record: any) => {
                            return <CorpDetails name={record?.name} avatar={record?.avatar} corpIdCount={text} qcUuid={record?.qcUuid} />
                        }
                    },
                    {
                        title: '客服号ID个数',
                        dataIndex: 'corpUserIdCount',
                        key: 'corpUserIdCount',
                        width: 120,
                        align: 'center',
                        sorter: true,
                        render: (text: number, record: any) => {
                            return <CorpUserDetails name={record?.name} avatar={record?.avatar} corpUserIdCount={text} qcUuid={record?.qcUuid} />
                        }
                    },
                    {
                        title: 'qcUUID',
                        dataIndex: 'qcUuid',
                        key: 'qcUuid',
                        ellipsis: true,
                        render: (text: string) => {
                            return <Text copyable>{text}</Text>
                        }
                    }
                ]}
                scroll={{ y: 300, x: 1000 }}
                bordered
                dataSource={getSelectQcUuidStatisticPageList.data?.data?.records}
                loading={getSelectQcUuidStatisticPageList.loading}
                rowKey="qcUuid"
                pagination={{
                    total: getSelectQcUuidStatisticPageList.data?.data?.total,
                    current: getSelectQcUuidStatisticPageList?.data?.data?.current || 1,
                    pageSize: getSelectQcUuidStatisticPageList?.data?.data?.size || 20,
                }}
                onChange={(pagination: any, _: any, sortData: any) => {
                    let { current, pageSize } = pagination
                    let newQueryForm = JSON.parse(JSON.stringify(queryParmas))
                    if (sortData && sortData?.order) {
                        newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'ASC' : 'DESC'
                        newQueryForm['orderByField'] = sortData?.field
                    } else {
                        delete newQueryForm['sortType']
                        delete newQueryForm['orderByField']
                    }
                    newQueryForm.pageNum = current || newQueryForm.pageNum
                    newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                    setQueryParmas({ ...newQueryForm })
                }}
            />
        </Card>
    </>
}

export default React.memo(UuidTem)