import { App, Badge, Button, Card, Empty, Form, Input, InputNumber, Modal, Popover, Radio, Select, Space, Table, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import { PlusOutlined, QuestionCircleFilled } from '@ant-design/icons';
import FilterUser from '@/pages/weComTask/components/filterUser';
import MindTags from '@/pages/weComTask/components/mindTags';
import { getBindMpListApi } from '@/pages/weComTask/API/corpUserAssign';
import { useAjax } from '@/Hook/useAjax';
import FilterUserTooltip from '@/pages/weComTask/components/filterUser/filterUserTooltip';
import { businessPlanData } from '@/pages/weComTask/page/businessPlan/create/const';
import { ColumnsType } from 'antd/es/table';
const { Text, Paragraph } = Typography;

/**
 * 进群对象新建组件
 * @param param0 
 * @returns 
 */
const AddGroupObject: React.FC<GROUP_CHAT_CREATE.AddGroupObjectProps> = ({ value = [], onChange, onCopy, bookPlatForm, index, strategyList, bookList }) => {

    /******************************************/
    const { message } = App.useApp();
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>()
    const [copyData, setCopyData] = useState<{ visible?: boolean, data?: any }>()
    const [copyIndex, setCopyIndex] = useState<number>()
    /******************************************/

    return <>

        {value?.length > 0 ? <ShowGroupUserTable
            value={value}
            bookList={bookList}
            bookPlatForm={bookPlatForm}
            handleDelete={(id) => {
                onChange?.(value.filter(item => item.id !== id))
            }}
            handleEdit={(record) => {
                setInitialValues(record)
                setVisible(true)
            }}
            handleCopy={(record) => {
                const newValue = { ...record, id: Date.now(), groupObjectName: `copy策略${index + 1}_` + record.groupObjectName }
                setCopyData({ visible: true, data: newValue })
            }}
        /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无群配置' />}
        <Button type="dashed" style={{ width: '100%' }} block icon={<PlusOutlined />} onClick={() => setVisible(true)}>新建群配置</Button>
        {visible && <AddGroupObjectModal
            visible={visible}
            initialValues={initialValues}
            onChange={(values) => {
                let newValue = JSON.parse(JSON.stringify(value))
                if (initialValues?.id) {
                    newValue = newValue.map(item => {
                        if (item.id === initialValues.id)
                            return values
                        return item
                    })
                } else {
                    newValue.push(values)
                }
                onChange?.(newValue)
                setVisible(false)
                setInitialValues(undefined)
            }}
            onClose={() => {
                setVisible(false)
                setInitialValues(undefined)
            }}
        />}
        {copyData?.visible && <Modal
            title={<strong>复制至</strong>}
            open={copyData?.visible}
            onCancel={() => setCopyData(undefined)}
            onOk={() => {
                if (copyIndex) {
                    onCopy?.(copyData.data, copyIndex)
                    setCopyData(undefined)
                    setCopyIndex(undefined)
                    setVisible(false)
                } else {
                    message.error('清选择复制到哪')
                }
            }}
        >
            <Select
                style={{ width: '100%' }}
                onChange={(e) => {
                    setCopyIndex(e)
                }}
                placeholder="请选择复制到哪"
                value={copyIndex}
                options={strategyList.map((item, index) => ({ value: index + 1, label: item.strategyName }))}
            />
        </Modal>}
    </>
};

export const ShowGroupUserTable: React.FC<GROUP_CHAT_CREATE.ShowGroupUserTableProps> = React.memo(({ bookList, bookPlatForm, value, handleEdit, handleDelete, handleCopy, isPreview }) => {

    const columns: ColumnsType<any> = [
        {
            title: '群名称',
            dataIndex: 'groupObjectName',
            key: 'groupObjectName',
            width: 120,
            ellipsis: true,
            fixed: 'left'
        },
        {
            title: '是否开启已有旧群聊补缺',
            dataIndex: 'isRepair',
            key: 'isRepair',
            width: 150,
            ellipsis: true,
            render(value, record, index) {
                return value ? <Space>
                    <Badge status="success" text="开启" />
                    <span>近{record.repairTimes}天</span>
                </Space> : <Badge status="error" text="关闭" />
            },
        },
        {
            title: '进群对象',
            dataIndex: 'externalUserFilter',
            key: 'externalUserFilter',
            width: 90,
            align: 'center',
            render(value) {
                return value ? <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ flex: '1 0', overflow: 'hidden' }}>
                        <Text ellipsis>指定</Text>
                    </div>
                    <Popover
                        placement="right"
                        styles={{ body: { maxWidth: 350, maxHeight: 350, overflow: 'hidden', overflowY: 'auto' } }}
                        mouseEnterDelay={0.5}
                        content={<FilterUserTooltip
                            bookCityList={bookPlatForm?.map(item => ({ label: item.platformName, value: item.platformKey }))}
                            configName={value?.configName}
                            data={value?.configContent}
                        />}
                    >
                        <a style={{ color: '#000' }}><QuestionCircleFilled /></a>
                    </Popover>
                </div> : '全部'
            },
        },
        {
            title: '群递增起始编号',
            dataIndex: 'groupIndex',
            key: 'groupIndex',
            width: 60,
            align: 'center'
        },
        {
            title: '群固定人数',
            dataIndex: 'groupUserCount',
            key: 'groupUserCount',
            width: 50,
            align: 'center'
        },
        {
            title: '邀请客户进群完毕后客服号是否退群',
            dataIndex: 'autoOutGroup',
            key: 'autoOutGroup',
            width: 85,
            align: 'center',
            render(value) {
                return value ? <span style={{ color: '#1890ff' }}>是</span> : <span style={{ color: 'red' }}>否</span>
            },
        },
        {
            title: '是否排除已在群的客户',
            dataIndex: 'excludeInGroup',
            key: 'excludeInGroup',
            width: 60,
            align: 'center',
            render(value) {
                return value ? <span style={{ color: '#1890ff' }}>是</span> : <span style={{ color: 'red' }}>否</span>
            },
        },
        {
            title: '拉群完成后自动删除拉群标签',
            dataIndex: 'excludeInGroup',
            key: 'excludeInGroup',
            width: 70,
            align: 'center',
            render(value) {
                return value ? <span style={{ color: '#1890ff' }}>是</span> : <span style={{ color: 'red' }}>否</span>
            },
        },
        {
            title: '是否开启失败人群重试',
            dataIndex: 'isRetry',
            key: 'isRetry',
            width: 70,
            align: 'center',
            render(value) {
                return value ? <span style={{ color: '#1890ff' }}>是</span> : <span style={{ color: 'red' }}>否</span>
            },
        },
        {
            title: '群聊关联公众号',
            dataIndex: 'weChatAppid',
            key: 'weChatAppid',
            width: 100,
            align: 'center',
            ellipsis: true,
            render(value) {
                return value || '--'
            },
        },
        {
            title: '建群模板名称',
            dataIndex: 'templateName',
            key: 'templateName',
            width: 100,
            ellipsis: true,
            render(value) {
                return value || '--'
            },
        },
        {
            title: '拉群完成后群聊备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 140,
            ellipsis: true,
            render(value) {
                return value || '--'
            },
        },
        {
            title: '拉群完成后群聊智能标签',
            dataIndex: 'tagDTO',
            key: 'tagDTO',
            width: 200,
            ellipsis: true,
            render(value) {
                return value && Object.keys(value)?.length > 0 ?
                    <Paragraph ellipsis style={{ margin: 0 }}>{Object.keys(value).map(key => {
                        if (key === 'business' && value[key]) {
                            return `业务（来源渠道）：${businessPlanData.find(i => i.value === value.business)?.label || '<空>'}`
                        } else if (key === 'bookCity' && value[key]) {
                            return `书城（来源渠道）：${bookPlatForm.find(i => i.id === value.bookCity)?.platformName || '<空>'}`
                        } else if (key === 'product' && value[key]) {
                            return `产品（来源渠道）：${bookList.find(i => i.id === value.product)?.bookName || '<空>'}`
                        }
                        return ''
                    }).join('、')}</Paragraph> : '--'
            },
        },
        {
            title: '客服消息',
            dataIndex: 'groupSendMsg',
            key: 'groupSendMsg',
            width: 140,
            ellipsis: true,
            render(value) {
                return value ? value : '--'
            }
        },
        {
            title: '操作',
            dataIndex: 'cz',
            key: 'cz',
            width: 100,
            fixed: 'right',
            align: 'center',
            render(_, record) {
                return <Space>
                    <a onClick={() => {
                        handleCopy?.(record)
                    }}>复制</a>
                    <a onClick={() => {
                        handleEdit?.(record)
                    }}>修改</a>
                    <a style={{ color: 'red' }} onClick={() => {
                        handleDelete?.(record.id)
                    }}>删除</a>
                </Space>
            },
        }
    ]
    if (isPreview) {
        columns.pop()
    }

    return <Table
        size='small'
        bordered
        rowKey={'id'}
        dataSource={value}
        scroll={{ y: 1000 }}
        columns={columns}
    />
})

const AddGroupObjectModal: React.FC<GROUP_CHAT_CREATE.AddGroupObjectModalProps> = React.memo(({ visible, onChange, onClose, initialValues }) => {

    /******************************************/
    const { message } = App.useApp();
    const [form] = Form.useForm();
    const externalUserType = Form.useWatch('externalUserType', form);
    const isRepair = Form.useWatch('isRepair', form);

    const getBindMpList = useAjax(() => getBindMpListApi())
    /******************************************/

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

    const handleOk = () => {
        form.validateFields().then((values) => {
            if (initialValues?.id) {
                values.id = initialValues.id
            } else {
                values.id = Date.now();
            }
            console.log(values)
            onChange?.(values)
        }).catch(() => {
            form.submit()
        });
    }

    return <Modal
        title={<strong>{(initialValues && Object.keys(initialValues).length > 0) ? '修改' : '新建'}群配置</strong>}
        open={visible}
        onCancel={onClose}
        width={600}
        onOk={handleOk}
        styles={{ body: { maxHeight: 550, overflowY: 'auto' } }}
    >
        <Form
            form={form}
            name="addGroupUser"
            labelAlign='left'
            labelCol={{ span: 9 }}
            colon={false}
            labelWrap
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={(initialValues && Object.keys(initialValues).length > 0) ? initialValues : { externalUserType: 'specify', isRepair: false, groupIndex: 1, groupUserCount: 37, autoOutGroup: false, excludeInGroup: true, deleteGroupTag: true, isRetry: false }}
            preserve={true}
        >
            <Form.Item
                name={'groupObjectName'}
                label={<strong>群名称</strong>}
                rules={[{ required: true, message: '请输入群名称!' }]}
            >
                <Input placeholder='请输入群名称' allowClear />
            </Form.Item>
            <Form.Item
                name={'isRepair'}
                label={<strong>是否开启已有旧群聊补缺</strong>}
                tooltip={{ title: '优先将客户补充进已有旧群聊的空缺位置，待旧群满员后再创建新群容纳剩余客户。', placement: 'top' }}
                rules={[{ required: true, message: '请选择是否开启群补人!' }]}
            >
                <Radio.Group options={[{ label: '开启', value: true }, { label: '关闭', value: false }]} />
            </Form.Item>
            {isRepair && <>
                <Form.Item
                    name={'repairTimes'}
                    label={<strong>补缺群聊范围</strong>}
                    rules={[{ required: true, message: '请选择补缺群聊范围!' }]}
                    tooltip={{ title: '可补缺的群聊范围：在本建群策略内创建的群聊', placement: 'top' }}
                >
                    <Select
                        showSearch
                        allowClear
                        placeholder="请选择补缺群聊范围"
                        filterOption={(input, option) =>
                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        options={Array(30).fill('').map((_, index) => ({ label: `近${index + 1}天`, value: index + 1 }))}
                    />
                </Form.Item>
                <Form.Item
                    name={'groupSendMsg'}
                    label={<strong>客服消息</strong>}
                >
                    <Input.TextArea placeholder="请输入建群成功发送内容" />
                </Form.Item>
            </>}
            <Form.Item
                label={<strong>进群对象配置</strong>}
                required
            >
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
                    <Form.Item
                        name={'externalUserType'}
                        rules={[{ required: true, message: '请选择转移对象!' }]}
                        noStyle
                    >
                        <Radio.Group options={[{ label: '全部', value: 'all' }, { label: '指定', value: 'specify' }]} />
                    </Form.Item>
                    {externalUserType === 'specify' && <div style={{ marginTop: 8, width: '100%' }}>
                        <Form.Item
                            name={'externalUserFilter'}
                            rules={[{ required: true, message: '请选择人群包!' }]}
                            noStyle
                        >
                            <FilterUser configType={'USER_GROUP'} />
                        </Form.Item>
                    </div>}
                </div>
            </Form.Item>
            <Form.Item
                name={'groupIndex'}
                tooltip={{ title: `例如:起始编号为'1'群名为'测试群',再建群后群名为'测试群1'超出群人数的用户将分配到'测试群2'依次递增`, placement: 'top' }}
                label={<strong>群递增起始编号</strong>}
                rules={[{ required: true, message: '请输入群递增起始编号!' }]}
            >
                <InputNumber placeholder='请输入群递增起始编号' min={1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
                name={'groupUserCount'}
                tooltip={{ title: `不包括建群人和固定企微号，最大上限数量38`, placement: 'top' }}
                label={<strong>群固定人数</strong>}
                rules={[{ required: true, message: '请输入群固定人数!' }]}
            >
                <InputNumber placeholder='请输入群固定人数' max={38} min={1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
                name={'autoOutGroup'}
                label={<strong>邀请客户进群完毕后客服号是否退群</strong>}
                rules={[{ required: true, message: '请选择是否退群!' }]}
            >
                <Radio.Group>
                    <Radio value={true}>是</Radio>
                    <Radio value={false}>否</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name={'excludeInGroup'}
                label={<strong>是否排除已在群的客户</strong>}
                rules={[{ required: true, message: '请选择是否排除已在群的客户!' }]}
            >
                <Radio.Group>
                    <Radio value={true}>是</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name={'deleteGroupTag'}
                label={<strong>拉群完成后自动删除拉群标签</strong>}
                rules={[{ required: true, message: '请选择拉群完成后自动删除拉群标签!' }]}
            >
                <Radio.Group>
                    <Radio value={true}>是</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name={'isRetry'}
                label={<strong>是否开启失败人群重试</strong>}
                rules={[{ required: true, message: '请选择是否开启失败人群重试!' }]}
            >
                <Radio.Group>
                    <Radio value={true}>是</Radio>
                    <Radio value={false}>否</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item
                name={'weChatAppid'}
                label={<strong>群聊关联公众号</strong>}
            >
                <Select
                    showSearch
                    allowClear
                    placeholder="选择公众号"
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    options={getBindMpList?.data?.data?.map(item => ({ label: item.name, value: item.name + '_' + item.id }))}
                />
            </Form.Item>
            <Form.Item
                name={'templateName'}
                label={<strong>建群模板名称</strong>}
            >
                <Input placeholder="请输入建群模板名称" />
            </Form.Item>
            <Form.Item
                name={'remark'}
                label={<strong>拉群完成后群聊备注</strong>}
            >
                <Input.TextArea placeholder="请输入群聊备注" />
            </Form.Item>

            <Card title={<strong>拉群完成后群聊智能标签</strong>} style={{ background: '#fff', marginBottom: 10 }} styles={{ body: { padding: '6px 0 6px 16px' } }}>
                <Form.Item
                    name={'tagDTO'}
                    style={{ marginBottom: 0 }}
                >
                    <MindTags />
                </Form.Item>
            </Card>
        </Form>
    </Modal>
})

export default React.memo(AddGroupObject);