import { useAjax } from "@/Hook/useAjax";
import { App, Button, Card, Form, Input, Modal, Select } from "antd"
import React from "react"
import { DeleteOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { createKeywordApi, updateKeywordApi } from "@/pages/weComTask/API/chatRecordManage";

interface Props {
    corpList: any[]
    initialValues?: any
    visible?: boolean,
    onClose?: () => void
    onChange?: () => void
}
const AddModify: React.FC<Props> = ({ corpList, initialValues, visible, onClose, onChange }) => {

    /*******************************/
    const { message } = App.useApp();
    const [form] = Form.useForm();
    const corpUserDTOList = Form.useWatch('corpUserDTOList', form)
    const addKeywordNews = useAjax((params) => createKeywordApi(params))
    const updataKeywordNews = useAjax((params) => updateKeywordApi(params))
    /*******************************/


    const handleOk = () => {
        form.validateFields().then(valid => {
            let newValue = JSON.parse(JSON.stringify(valid))
            if (newValue.replyJson) {
                newValue.replyJson = newValue.replyJson.flat().map((item: { mediaType: any; textContent: any; imageUrl: any; videoUrl: any; }) => {
                    let msgContent = null
                    switch (item.mediaType) {
                        case 'text':
                            msgContent = item.textContent
                            break
                        case 'image':
                            msgContent = item.imageUrl
                            break;
                        case 'video':
                            msgContent = item.videoUrl
                            break;
                    }
                    return { msgType: item.mediaType, msgContent }
                })
            }
            console.log(newValue)
            if (initialValues?.id) {
                updataKeywordNews.run({ ...newValue, id: initialValues?.id }).then(res => {
                    if (res?.data) {
                        message.success('修改成功')
                        onChange?.()
                    }
                })
            } else {
                addKeywordNews.run({ ...newValue }).then(res => {
                    if (res?.data) {
                        message.success('新增成功')
                        onChange?.()
                    }
                })
            }
        })
    }

    return <Modal
        title={`${initialValues?.id ? '修改' : (initialValues && Object.keys(initialValues).length > 0) ? '复制' : '新增'}风险词`}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addKeywordNews.loading || updataKeywordNews.loading}
    >
        <Form
            form={form}
            name="keyword-hooks"
            labelAlign='left'
            labelCol={{ span: 4 }}
            colon={false}
            initialValues={initialValues}
        >
            {initialValues?.id ? <>
                <Form.Item
                    label={<strong>企业</strong>}
                    name={'corpId'}
                    rules={[{ required: true, message: '请选择企业!' }]}
                >
                    <Select
                        placeholder="选择企业"
                        showSearch
                        allowClear
                        disabled
                        filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                        options={corpList?.map((item: { t1: any }) => ({ label: item.t1?.corpName, value: item.t1?.corpId, data: item }))}
                    />
                </Form.Item>
                <Form.Item label={<strong>企微号</strong>} name='corpUserId' rules={[{ required: true, message: '请选择企微号' }]}>
                    <Select
                        placeholder="选择企微号"
                        showSearch
                        allowClear
                        mode="multiple"
                        filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                        options={corpList?.find(item => item?.t1?.corpId === initialValues?.corpId)?.t2?.map((item: any) => ({ label: item.name, value: item.corpUserId }))}
                    />
                </Form.Item>
            </> : <Form.List name="corpUserDTOList">
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name, ...restField }, index) => {
                            const corpId = corpUserDTOList?.[index]?.corpId
                            const corpUserList = corpList?.find(item => item?.t1?.corpId === corpId)?.t2
                            return <Card
                                key={key}
                                title={<strong>企业{index + 1}</strong>}
                                style={{ background: '#fff', marginBottom: 10 }}
                                hoverable
                                id={`strategy_${index}`}
                                extra={corpUserDTOList?.length > 1 ? <Button icon={<DeleteOutlined />} type='link' style={{ color: 'red' }} onClick={() => remove(name)}></Button> : null}
                            >
                                <Form.Item
                                    {...restField}
                                    label={<strong>企业</strong>}
                                    name={[name, 'corpId']}
                                    rules={[{ required: true, message: '请选择企业!' }]}
                                >
                                    <Select
                                        placeholder="选择企业"
                                        showSearch
                                        allowClear
                                        filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                        options={corpList?.map((item: { t1: any }) => ({ label: item.t1?.corpName, value: item.t1?.corpId, data: item }))}
                                    />
                                </Form.Item>
                                {corpId && <Form.Item
                                    {...restField}
                                    label={<strong>企微号</strong>}
                                    name={[name, 'corpUserId']}
                                    rules={[{ required: true, message: '请选择企微号!' }]}
                                >
                                    <Select
                                        placeholder="选择企微号"
                                        showSearch
                                        allowClear
                                        mode="multiple"
                                        filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                        options={corpUserList?.map((item: any) => ({ label: item.name, value: item.corpUserId }))}
                                    />
                                </Form.Item>}
                            </Card>
                        })}
                        <Form.Item>
                            <Button type="primary" onClick={() => add()} block icon={<PlusOutlined />}>
                                新增企业组
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>}

            <Form.Item name="riskLevel" label={<strong>风险等级</strong>} rules={[{ required: true, message: '请选择风险等级' }]}>
                <Select
                    placeholder='风险等级'
                    allowClear
                    autoClearSearchValue={false}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                    }
                    options={[
                        {
                            label: '低',
                            value: 1
                        },
                        {
                            label: '中',
                            value: 2
                        },
                        {
                            label: '高',
                            value: 3
                        }
                    ]}
                />
            </Form.Item>
            <Form.List name="keywordJson">
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name, ...restField }, index) => (
                            <Form.Item
                                key={key}
                                label={<strong>风险词{index + 1}</strong>}
                                {...restField}
                                name={[name]}
                                labelCol={{ span: 4 }}
                                rules={[{ required: true, message: '请输入风险词' }]}
                            >
                                <Input placeholder="请输入风险词" addonAfter={fields.length > 1 ? <MinusCircleOutlined onClick={() => remove(name)} /> : null} />
                            </Form.Item>
                        ))}
                        <Form.Item labelCol={{ span: 4 }}>
                            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                添加风险词
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
        </Form>
    </Modal>
}

export default React.memo(AddModify)