import React, { useEffect } from 'react';
import '../../../../../tencentAdPutIn/index.less'
import { Form, Input, InputNumber, message, Modal, Radio, Select } from 'antd';
import { useAjax } from '@/Hook/useAjax';
import { addLocalCorpCsgroupApi, modifyLocalCorpCsgroupApi } from '@/services/adqV3/global';
import { useWatch } from 'antd/lib/form/Form';
import { getAllUser } from '@/services/operating/account';

interface AddCsGroupProps {
    corpWechatList: { label: string; value: string }[];
    userRotatePolicy: { label: string; value: string }[];
    localCorpCsgroupList: { label: string; value: string }[];
    accountId: number;
    visible?: boolean;
    onClose?: () => void;
    onChange?: () => void;
    initialValues?: any; // 用于表单的初始值
}
const AddCsGroup: React.FC<AddCsGroupProps> = ({ corpWechatList, userRotatePolicy, localCorpCsgroupList, accountId, visible, onClose, onChange, initialValues }) => {

    /**************************************/
    const [form] = Form.useForm();
    const type = useWatch('type', form)
    const parentId = useWatch('parentId', form)

    const addLocalCorpCsgroup = useAjax((params) => addLocalCorpCsgroupApi(params))
    const modifyLocalCorpCsgroup = useAjax((params) => modifyLocalCorpCsgroupApi(params))
    const getAllUser1 = useAjax(() => getAllUser())
    /**************************************/

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

    const handleOk = () => {
        form.validateFields().then(values => {
            console.log(values)
            if (initialValues?.id) {
                modifyLocalCorpCsgroup.run({ ...values, accountId, id: initialValues?.id }).then(res => {
                    if (res) {
                        message.success('修改成功')
                        onChange?.()
                    }
                })
            } else {
                addLocalCorpCsgroup.run({ ...values, accountId }).then((res) => {
                    if (res) {
                        message.success('新增成功')
                        onChange?.()
                    }
                })
            }
        })
    }

    return <Modal
        title={<strong>{initialValues?.id ? '修改客服组' : '新增客服组'} （<span style={{ color: 'red' }}>{accountId}</span>）</strong>}
        open={visible}
        onOk={handleOk}
        onCancel={onClose}
        className='modalResetCss'
        confirmLoading={addLocalCorpCsgroup.loading || modifyLocalCorpCsgroup.loading}
        width={550}
    >
        <Form
            form={form}
            name='basicAddCsGroup'
            autoComplete="off"
            colon={false}
            labelCol={{ span: 5 }}
            labelAlign='left'
            initialValues={initialValues || { type: 1 }} // 默认类型为客服组
        >
            <Form.Item label={<strong>类型</strong>} name="type" rules={[{ required: true, message: '请选择类型!' }]}>
                <Radio.Group
                    buttonStyle="solid"
                    optionType='button'
                    options={[
                        { value: 1, label: '客服组' },
                        { value: 0, label: '客服组集' }
                    ]}
                    disabled={initialValues?.id}
                />
            </Form.Item>
            <Form.Item label={<strong>客服组{type == 1 ? '' : '集'}名称</strong>} name="csgroupName" rules={[{ required: true, message: `请输入客服组${type == 1 ? '' : '集'}名称!` }]}>
                <Input placeholder={`请输入客服组${type == 1 ? '' : '集'}名称`} />
            </Form.Item>

            {type == 1 && <>
                <Form.Item label={<strong>腾讯企业</strong>} name="tencentCorpId" rules={[{ required: true, message: '请选择腾讯企业!' }]}>
                    <Select
                        showSearch
                        placeholder="请选择企业"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        disabled={initialValues?.id}
                        options={corpWechatList}
                    />
                </Form.Item>
                <Form.Item label={<strong>客服组集</strong>} name="parentId">
                    <Select
                        showSearch
                        placeholder="请选择客服组集"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        options={localCorpCsgroupList}
                    />
                </Form.Item>
                <Form.Item label={<strong>指派用户</strong>} name="assignUserIdList">
                    <Select
                        showSearch
                        placeholder="请选择用户"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        mode='multiple'
                        options={getAllUser1.data?.map((user: { nickname: any; userId: any; }) => ({ label: user.nickname, value: user.userId }))}
                    />
                </Form.Item>
                <Form.Item label={<strong>通知用户</strong>} name="callUserIdList">
                    <Select
                        showSearch
                        placeholder="请选择用户"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        mode='multiple'
                        options={getAllUser1.data?.map((user: { nickname: any; userId: any; }) => ({ label: user.nickname, value: user.userId }))}
                    />
                </Form.Item>
                <Form.Item
                    label={<strong>在线通知人数</strong>}
                    name="callOnlineCount"
                    rules={[
                        {
                            validator: (_, value) =>
                                value === undefined || value === null || Number.isInteger(value)
                                    ? Promise.resolve()
                                    : Promise.reject('请输入整数')
                        }
                    ]}
                >
                    <InputNumber
                        placeholder='请输入在线通知人数'
                        style={{ width: '100%' }}
                    />
                </Form.Item>
            </>}
            {(initialValues?.id ? !initialValues?.parentId : !parentId) && <Form.Item label={<strong>切号策略</strong>} name="policyId">
                <Select
                    showSearch
                    placeholder="请选择切号策略"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                    }
                    allowClear
                    options={userRotatePolicy}
                />
            </Form.Item>}
        </Form>
    </Modal>
};

export default React.memo(AddCsGroup);