import { Button, message, Modal, Select, Space, Table, Tag, Typography } from "antd";
import React, { useState } from "react";
import style from '../../../../../../components/selectExternalAccount/index.less'
import { CheckOutlined, CloseOutlined } from '@ant-design/icons'
import { DefaultOptionType } from "antd/es/select";
import SelectGroupLeaderModal from "@/pages/weComTask/page/groupLeaderManage/selectGroupLeaderModal";
const { Text, Title } = Typography;

interface Props {
    corpList: DefaultOptionType[]
    mpList: DefaultOptionType[]
    group?: OFFICIAL_CHAT_CREATE.GroupsProps[];
    visible?: boolean;
    onClose?: () => void;
    onChange?: (value: OFFICIAL_CHAT_CREATE.GroupsProps[]) => void;
    isOwnerUser?: boolean;  // 是否可选择群主
    disabled?: boolean;
}
/**
 * 高级群发外部客户选择
 * @param param0 
 * @returns 
 */
const SelectMpCorp: React.FC<Props> = ({ corpList, mpList, group, visible, onClose, onChange, isOwnerUser, disabled }) => {

    /***************************************/
    const [data, setData] = useState<OFFICIAL_CHAT_CREATE.GroupsProps[]>(group && group?.length > 0 ? group : [{}]);
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [queryForm, setQueryForm] = useState<any>({})

    const [ownerUserVisible, setOwnerUserVisible] = useState<boolean>(false) // 选择群主弹窗
    /***************************************/

    const handleOk = () => {
        if (data?.every(item => item?.corp?.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={1200}
        className={`${style.SelectPackage}`}
        okButtonProps={{ disabled }}
        styles={{
            body: {
                padding: '0 10px 0 10px'
            }
        }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <div className={style.leftTitle}>
                    <h4 className={style.title}>群发组</h4>
                    <a onClick={() => {
                        setData(d => ([...d, {}]))
                    }}>新增组</a>
                </div>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => {
                        const corp = data[index]?.corp || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            <div><Text ellipsis={{ tooltip: true }}>群发组{index + 1}</Text></div>
                            {corp?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right} style={{ width: 300, flex: 'none', borderRight: '1px solid #e8e8e8' }}>
                <Space style={{ marginBottom: 10 }} align="center" size={10}>
                    <Title level={5} style={{ margin: 0 }}>公众号（选填）</Title>
                    <Select
                        showSearch
                        style={{ width: 120 }}
                        placeholder="请选择公众号"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        value={queryForm?.mpAccountId}
                        onChange={(e) => {
                            setQueryForm({ ...queryForm, mpAccountId: e, pageNum: 1 })
                        }}
                        allowClear
                        options={mpList}
                    />
                    {data[selectAdz - 1]?.mpAccount?.value && <a
                        style={{ color: 'red' }}
                        onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.mpAccount || {}
                            dataIten = undefined
                            newData[selectAdz - 1].mpAccount = dataIten
                            setData(newData)
                        }}
                    >删除</a>}

                </Space>
                <Table
                    tableLayout='fixed'
                    dataSource={queryForm?.mpAccountId ? mpList.filter(item => item.value === queryForm.mpAccountId) : mpList}
                    columns={[
                        {
                            title: '公众号名称',
                            dataIndex: 'label',
                            key: 'label'
                        }
                    ]}
                    scroll={{ y: 400 }}
                    rowKey={'value'}
                    size='small'
                    rowSelection={{
                        selectedRowKeys: data[selectAdz - 1]?.mpAccount?.value ? [data[selectAdz - 1]?.mpAccount?.value] : [],
                        type: 'radio',
                        getCheckboxProps: (record: any) => ({
                            name: record.name,
                        }),
                        onSelect: (record: { value: string }, selected: boolean) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.mpAccount || {}
                            if (selected) {
                                dataIten = { ...record }
                            } else {
                                dataIten = undefined
                            }
                            newData[selectAdz - 1].mpAccount = dataIten
                            setData(newData)
                        }
                    }}
                />
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="center" size={10}>
                    <Title level={5} style={{ margin: 0 }}>群聊的主体</Title>
                    <Select
                        showSearch
                        style={{ width: 200 }}
                        placeholder="请选择企业"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        value={queryForm?.corpId}
                        onChange={(e) => {
                            setQueryForm({ ...queryForm, corpId: e, pageNum: 1 })
                        }}
                        allowClear
                        options={corpList}
                    />
                </Space>

                <Table
                    tableLayout='fixed'
                    dataSource={queryForm?.corpId ? corpList.filter(item => item.value === queryForm.corpId) : corpList}
                    columns={[
                        {
                            title: '主体名称',
                            dataIndex: 'label',
                            key: 'label'
                        }
                    ]}
                    scroll={{ y: 400 }}
                    rowKey={'value'}
                    size='small'
                    rowSelection={{
                        selectedRowKeys: data[selectAdz - 1]?.corp?.map((item: any) => item?.value),
                        getCheckboxProps: (record: any) => ({
                            name: record.name,
                        }),
                        onSelect: (record: { value: string }, selected: boolean) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.corp || []
                            if (selected) {
                                dataIten.push({ ...record })
                            } else {
                                dataIten = dataIten.filter((item: { value: string }) => item.value !== record.value)
                            }
                            newData[selectAdz - 1].corp = dataIten
                            delete newData[selectAdz - 1]?.ownerUsers
                            setData(newData)
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { value: string }[], changeRows: { value: string }[]) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let dataIten = newData[selectAdz - 1]?.corp || []
                            if (selected) {
                                let newSelectAccData = [...dataIten]
                                changeRows.forEach((item: { value: string }) => {
                                    let index = newSelectAccData.findIndex((ite: { value: string }) => ite.value === item.value)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                newData[selectAdz - 1].corp = newSelectAccData
                                delete newData[selectAdz - 1].ownerUsers
                            } else {
                                let newSelectAccData = dataIten.filter((item: { value: string }) => {
                                    let index = changeRows.findIndex((ite: { value: string }) => ite.value === item.value)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                newData[selectAdz - 1].corp = newSelectAccData
                                delete newData[selectAdz - 1].ownerUsers
                            }
                            setData(newData)
                        }
                    }}
                />
            </div>
            <div className={style.center}>
                <div style={{ margin: '0 0 5px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Title level={5} style={{ margin: 0 }}>已选主体：{data[selectAdz - 1]?.corp?.length || 0}</Title>
                    {data.length > 1 && <a style={{ color: 'red' }} onClick={() => {
                        if (selectAdz === data.length) {
                            handleSelectAdz(selectAdz - 1)
                        } else {
                            handleSelectAdz(selectAdz)
                        }
                        const newData = data.filter((_, index) => index !== selectAdz - 1)
                        setData(newData)
                    }}>删除组</a>}
                </div>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.corp?.map(item => <div key={item.value}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.label}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].corp = newData[selectAdz - 1]?.corp?.filter((i: any) => i?.value !== item.value)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
            {(isOwnerUser && data[selectAdz - 1]?.corp?.length === 1) && <div className={style.center} style={{ width: 200 }}>
                <div style={{ margin: '0 0 5px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Title level={5} style={{ margin: 0 }}>已选群主：{data[selectAdz - 1]?.ownerUsers?.length || 0}</Title>
                    {data[selectAdz - 1]?.ownerUsers?.length > 0 && <a style={{ color: 'red' }} onClick={() => {
                        let newData = JSON.parse(JSON.stringify(data))
                        delete newData[selectAdz - 1].ownerUsers
                        setData(newData)
                    }}>清空</a>}
                    <a onClick={() => { setOwnerUserVisible(true) }}>选择</a>
                </div>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.ownerUsers?.map(item => <div key={item.corpUserId}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.name}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].ownerUsers = newData[selectAdz - 1]?.ownerUsers?.filter((i: any) => i?.corpUserId !== item.corpUserId)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>}
        </div>

        {/* 选择群主 */}
        {ownerUserVisible && <SelectGroupLeaderModal
            corpIds={data[selectAdz - 1]?.corp?.map(i => i.value) || []}
            visible={ownerUserVisible}
            value={data[selectAdz - 1]?.ownerUsers || []}
            onClose={() => {
                setOwnerUserVisible(false)
            }}
            onChange={(value) => {
                let newData = JSON.parse(JSON.stringify(data))
                newData[selectAdz - 1].ownerUsers = value
                setData(newData)
                setOwnerUserVisible(false)
            }}
        />}
    </Modal>
}

export default React.memo(SelectMpCorp);