import { App, Button, Empty, Form, Input, Modal, Radio, Select, Space, Table } from 'antd';
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import FilterUser from '@/pages/weComTask/components/filterUser';
import { ColumnsType } from 'antd/es/table';

/**
 * 新增修改发送对象
 * @param param0 
 * @returns 
 */
const AddSendObject: React.FC<ROBOT_CHAT_CREATE.AddSendObjectProps> = ({ mpList, corpList, visible, onChange, onClose, initialValues }) => {

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

    const handleOk = () => {
        form.validateFields().then((values) => {
            if (initialValues?.id) {
                values.id = initialValues.id
            } else {
                values.id = Date.now();
            }
            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="AddSendObject"
            labelAlign='left'
            labelCol={{ span: 7 }}
            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' }}
            preserve={true}
        >
            <Form.Item label={<strong>发送群对象名称</strong>} name={'sendGroupName'} rules={[{ required: true, message: '请输入发送群对象名称!' }]}>
                <Input placeholder="请输入发送群对象名称" style={{ width: 358 }} allowClear />
            </Form.Item>
            <Form.Item
                label={<strong>群聊关联公众号</strong>}
                name={'weChatAppid'}
            >
                <Select
                    showSearch
                    allowClear
                    placeholder="选择公众号"
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    style={{ width: 358 }}
                    options={mpList}
                />
            </Form.Item>
            <Form.Item
                label={<strong>群聊主体</strong>}
                name={'corpId'}
                rules={[{ required: true, message: '请选择群聊主体!' }]}
            >
                <Select
                    showSearch
                    allowClear
                    placeholder="选择群聊主体"
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    style={{ width: 358 }}
                    options={corpList}
                />
            </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={'GROUP_GROUP'} />
                        </Form.Item>
                    </div>}
                </div>
            </Form.Item>
        </Form>
    </Modal>
}

const ShowSendObjectTable: React.FC<ROBOT_CHAT_CREATE.ShowSendObjectTable> = ({ mpList, corpList, data, handleDelete, handleEdit, isPreview }) => {

    const columns: ColumnsType<any> = [
        {
            title: '发送群对象名称',
            dataIndex: 'sendGroupName',
            key: 'sendGroupName',
            width: 120,
            ellipsis: true,
            fixed: 'left'
        },
        {
            title: '群聊关联公众号',
            dataIndex: 'weChatAppid',
            key: 'weChatAppid',
            width: 100,
            align: 'center',
            ellipsis: true,
            render(value) {
                return mpList?.find(item => item.value === value)?.label || '--'
            },
        },
        {
            title: '群聊主体',
            dataIndex: 'corpId',
            key: 'corpId',
            width: 100,
            align: 'center',
            ellipsis: true,
            render(value) {
                return corpList?.find(item => item.value === value)?.label || '--'
            },
        },
        {
            title: '操作',
            dataIndex: 'cz',
            key: 'cz',
            width: 100,
            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={data}
        scroll={{ y: 1000 }}
        columns={columns}
    />
}


const SettingsSendObject: React.FC<ROBOT_CHAT_CREATE.SettingsSendObjectProps> = ({ mpList, corpList, value, onChange }) => {

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

    return <>
        {value?.length > 0 ? <ShowSendObjectTable
            mpList={mpList}
            corpList={corpList}
            data={value}
            handleDelete={(id) => {
                onChange?.(value.filter(item => item.id !== 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 && <AddSendObject
            mpList={mpList}
            corpList={corpList}
            visible={visible}
            initialValues={initialValues}
            onChange={(values) => {
                console.log(values)
                const 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)
                // }
                newValue.push({a: 1})
                console.log(newValue)
                // onChange?.(newValue)
                // setVisible(false)
                // setInitialValues(undefined)
            }}
            onClose={() => {
                setVisible(false)
                setInitialValues(undefined)
            }}
        />}
    </>;
};

export default React.memo(SettingsSendObject);