import { App, 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 { getAllWxListApi } 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, bookPlatForm, bookList }) => {

    /******************************************/
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>(undefined)
    /******************************************/

    return <>

        {value?.length > 0 ? <ShowGroupUserTable
            value={value}
            bookList={bookList}
            bookPlatForm={bookPlatForm}
            handleDelete={(id) => {
                onChange?.(value.filter((_, index) => index + 1 !== id))
            }}
            handleEdit={(record) => {
                setInitialValues(record)
                setVisible(true)
            }}
        /> : <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) => {
                const newValue = JSON.parse(JSON.stringify(value))
                if (initialValues?.id) {
                    newValue[initialValues.id - 1] = values
                } else {
                    newValue.push(values)
                }
                onChange?.(newValue)
                setVisible(false)
                setInitialValues(undefined)
            }}
            onClose={() => {
                setVisible(false)
                setInitialValues(undefined)
            }}
        />}
    </>
};

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

    const columns: ColumnsType<any> = [
        {
            title: '群配置名称',
            dataIndex: 'groupObjectName',
            key: 'groupObjectName',
            width: 120,
            ellipsis: true,
            fixed: 'left'
        },
        {
            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: 'weChatAppid',
            key: 'weChatAppid',
            width: 100,
            align: 'center',
            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
        },
        {
            title: '操作',
            dataIndex: 'cz',
            key: 'cz',
            width: 75,
            fixed: 'right',
            align: 'center',
            render(_, record) {
                return <Space>
                    <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?.map((item, index) => ({ ...item, id: index + 1 }))}
        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 getAccountList = useAjax(() => getAllWxListApi())
    /******************************************/

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

    const handleOk = () => {
        form.validateFields().then((values) => {
            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: 6 }}
            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: 'all', groupIndex: 1, groupUserCount: 37, autoOutGroup: false, excludeInGroup: true, deleteGroupTag: true }}
            preserve={true}
        >
            <Form.Item
                name={'groupObjectName'}
                label={<strong>群配置名称</strong>}
                rules={[{ required: true, message: '请输入群配置名称!' }]}
            >
                <Input placeholder='请输入群配置名称' allowClear />
            </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={'weChatAppid'}
                label={<strong>群聊关联公众号</strong>}
            >
                <Select
                    showSearch
                    allowClear
                    placeholder="选择公众号"
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    options={getAccountList?.data?.data?.map(item => ({ label: item.name, value: item.name + '_' + item.appId }))}
                />
            </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.Item
                name={'groupSendMsg'}
                label={<strong>建群成功发送内容</strong>}
                rules={[{ required: true, message: '请输入建群成功发送内容!' }]}
            >
                <Input.TextArea placeholder="请输入建群成功发送内容" />
            </Form.Item>
        </Form>
    </Modal>
})

export default React.memo(AddGroupObject);