import { useAjax } from "@/Hook/useAjax"
import { addOrUpdateEmailApi } from "@/services/gameData/roleOperate"
import { DatePicker, Form, Modal, message } from "antd"
import React, { useEffect } from "react"
import moment from "moment"

interface Props {
    data: any[]
    ids?: any[];
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
/**
 * 发送Email
 * @returns 
 */
const SendMail: React.FC<Props> = ({ data = [], ids, visible, onClose, onChange }) => {


    /************************************/
    const [form] = Form.useForm()
    const addOrUpdateEmail = useAjax((params) => addOrUpdateEmailApi(params))
    /************************************/

    useEffect(() => {
        if (ids?.length === 1) {
            const { sendTime } = ids?.[0]
            form.setFieldsValue({ sendTime: sendTime ? moment(sendTime) : undefined })
        }
    }, [ids])

    const handleOk = async () => {
        let validate = await form.validateFields()
        const { sendTime, giftId } = validate
        let params: any = { giftId, sendTime: moment(sendTime).format('YYYY-MM-DD HH:mm:ss') }
        if (ids) {
            params.ids = ids.map(item => item.id)
        }
        let roleInfoList = data.map(item => {
            return {
                gameId: item.role_reg_game_id,
                roleId: item.role_id,
                serverId: item.server_id,
                userId: item.association_user_id,
            }
        })
        params.roleInfoList = roleInfoList
        addOrUpdateEmail.run(params).then(res => {
            if (res) {
                message.success('成功')
                onChange?.()
            }
        })
    }

    return <Modal
        title={`${ids && ids?.length > 0 ? '修改' : '发送'}邮件记录`}
        visible={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={addOrUpdateEmail.loading}
    >
        <Form
            name="basicExportEmail"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            autoComplete="off"
        >
            <Form.Item
                label="发送时间"
                name="sendTime"
                rules={[{ required: true, message: '请选择发送时间' }]}
            >
                <DatePicker style={{ width: '100%' }} showTime/>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(SendMail)