import { Avatar, Button, Input, message, Modal, Select, Space, Table, Tag, Typography } from "antd";
import React, { useEffect, useState } from "react";
import style from './index.less'
import { CheckOutlined, UserOutlined, CloseOutlined } from '@ant-design/icons'
import { useAjax } from "@/Hook/useAjax";
import { getCorpAllListApi, getCorpExternalUserListApi } from "@/API/global";
import { copy } from "@/utils/utils";
const { Text, Title } = Typography;


/**
 * 高级群发外部客户选择
 * @param param0 
 * @returns 
 */
const SelectExternalAccount: React.FC<EXTERNAL_ACCOUNT_PROPS.SelectExternalAccountProps> = ({ corpUsers, visible, onClose, onChange }) => {

    /***************************************/
    const [data, setData] = useState<TASK_CREATE.corpUsersProps[]>(corpUsers)
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [queryForm, setQueryForm] = useState<any>({ pageNum: 1, pageSize: 20, corpId: '', deleted: false })

    const getCorpAllList = useAjax((params) => getCorpAllListApi(params))
    const getCorpExternalUserList = useAjax((params) => getCorpExternalUserListApi(params))
    /***************************************/

    useEffect(() => {
        getCorpAllList.run({}).then(res => {
            if (res?.data?.length) {
                setQueryForm(data => ({ ...data, corpId: res.data[0].corpId }))
            }
        })
    }, [])

    useEffect(() => {
        if (queryForm?.corpId) {
            getCorpExternalUserList.run(queryForm)
        }
    }, [queryForm])

    const handleOk = () => {
        if (data?.every(item => item?.externalUserList?.length)) {
            onChange?.(data)
        } else {
            message.error('请选择外部联系人')
        }
    }

    const handleSelectAdz = (value: number) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
    }

    return <Modal
        title={<strong>高级群发外部客户选择</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={1000}
        className={`${style.SelectPackage}`}
        styles={{
            body: {
                padding: '0 10px 0 10px'
            }
        }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>客服号</h4>
                <div className={style.accountIdList}>
                    {corpUsers?.map((item, index) => {
                        const externalUserList = data[index]?.externalUserList || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            <div><Text ellipsis={{ tooltip: true }}>{item?.name}（{item.corpName}）</Text></div>
                            {externalUserList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={5}>
                    <Space.Compact>
                        <Button>外部企业</Button>
                        <Select
                            showSearch
                            style={{ width: 150 }}
                            placeholder="请选择外部企业"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            value={queryForm?.corpId}
                            onChange={(e) => {
                                setQueryForm({ ...queryForm, corpId: e, pageNum: 1 })
                            }}
                            options={getCorpAllList?.data?.data?.map(item => ({ label: item.corpName, value: item.corpId }))}
                        />
                    </Space.Compact>
                    <Input placeholder="客户名称" style={{ width: 125 }} allowClear value={queryForm?.name} onChange={(e) => setQueryForm({ ...queryForm, name: e.target.value, pageNum: 1 })} />
                    <Input placeholder="客户ID" style={{ width: 125 }} allowClear value={queryForm?.externalUserId} onChange={(e) => setQueryForm({ ...queryForm, externalUserId: e.target.value, pageNum: 1 })} />
                </Space>

                <Table
                    tableLayout='fixed'
                    dataSource={getCorpExternalUserList.data?.data?.records?.map((item: any, index: number) => ({ ...item, id: item.externalUserId + '_' + item.corpUserId }))}
                    columns={[
                        {
                            title: '客户ID',
                            dataIndex: 'externalUserId',
                            key: 'externalUserId',
                            align: 'center',
                            width: 140,
                            ellipsis: true,
                            render: (a: string) => {
                                return <a onClick={() => copy(a)}>{a}</a>
                            },
                        },
                        {
                            title: '客户',
                            dataIndex: 'name',
                            key: 'name',
                            width: 80,
                            ellipsis: true,
                            render: (a: string, b: any) => {
                                return <Space style={{ width: '100%' }}>
                                    <Avatar shape="square" size="small" icon={<UserOutlined />} src={b?.avatar} />
                                    <Typography.Paragraph style={{ marginBottom: 0, width: 250 }} ellipsis={{ rows: 1, tooltip: true }}>{a}</Typography.Paragraph>
                                </Space>
                            }
                        },
                        {
                            title: '通讯录成员名称',
                            dataIndex: 'corpUserName',
                            key: 'corpUserName',
                            align: 'center',
                            width: 80,
                            ellipsis: true
                        },
                    ]}
                    loading={getCorpExternalUserList.loading}
                    scroll={{ y: 400 }}
                    rowKey={'externalUserId'}
                    size='small'
                    rowSelection={{
                        selectedRowKeys: data[selectAdz - 1]?.externalUserList?.map((item: any) => item?.externalUserId),
                        getCheckboxProps: (record: any) => ({
                            name: record.name,
                        }),
                        onSelect: (record: { externalUserId: string }, selected: boolean) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.externalUserList || []
                            if (selected) {
                                dataIten.push({ ...record })
                            } else {
                                dataIten = dataIten.filter((item: { externalUserId: string }) => item.externalUserId !== record.externalUserId)
                            }
                            newData[selectAdz - 1].externalUserList = dataIten
                            setData(newData)
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { externalUserId: string }[], changeRows: { externalUserId: string }[]) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.externalUserList || []
                            if (selected) {
                                let newSelectAccData = [...dataIten]
                                changeRows.forEach((item: { externalUserId: string }) => {
                                    let index = newSelectAccData.findIndex((ite: { externalUserId: string }) => ite.externalUserId === item.externalUserId)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                newData[selectAdz - 1].externalUserList = newSelectAccData
                            } else {
                                let newSelectAccData = dataIten.filter((item: { externalUserId: string }) => {
                                    let index = changeRows.findIndex((ite: { externalUserId: string }) => ite.externalUserId === item.externalUserId)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                newData[selectAdz - 1].externalUserList = newSelectAccData
                            }
                            setData(newData)
                        }
                    }}
                    pagination={{
                        total: getCorpExternalUserList.data?.data?.total,
                        showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                        showSizeChanger: true,
                        showLessItems: true,
                        defaultCurrent: 1,
                        defaultPageSize: 20,//默认初始的每页条数
                        current: getCorpExternalUserList?.data?.data?.current || 1,
                        pageSize: getCorpExternalUserList?.data?.data?.size || 20,
                        onChange: (page, pageSize) => {
                            setQueryForm({ ...queryForm, pageNum: page, pageSize })
                        }
                    }}
                />
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.externalUserList?.length || 0}</Title>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.externalUserList?.map(item => <div key={item.externalUserId}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.name}（{item?.corpName}）</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].externalUserList = newData[selectAdz - 1]?.externalUserList?.filter((i: any) => i?.externalUserId !== item.externalUserId)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}

export default React.memo(SelectExternalAccount);