import { useAjax } from "@/Hook/useAjax"
import { copyAdAdApi } from "@/services/launchAdq/adq"
import { Checkbox, DatePicker, Form, InputNumber, message, Modal, notification, Radio, Select, Space, Switch, TimePicker } from "antd"
import React, { useState } from "react"
import moment from "moment"
import { getTimeSeriesList } from "./const"
import TimeInSelect from "../../components/timeInSelect"
import { RangePickerProps } from "antd/lib/date-picker"
const { RangePicker } = DatePicker;
let DatePickers: any = DatePicker


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

    /**********************************/
    const { visible, onChange, onClose, selectedRows } = props
    const [form] = Form.useForm();
    let dateType = Form.useWatch('dateType', form)
    let bidAmountMin = Form.useWatch('bidAmountMin', form)
    let bidAmountMax = Form.useWatch('bidAmountMax', form)
    let amountModel = Form.useWatch('amountModel', form)
    const [state, setState] = useState<any>({ isShowTime: [] })
    const [timeSeriesType, setTimeSeriesType] = useState<'allDayLong' | 'timeInterValS'>('allDayLong')

    const copyAdAd = useAjax((params) => copyAdAdApi(params))
    /**********************************/

    const handleOk = () => {
        form.validateFields().then(values => {
            let newValues = JSON.parse(JSON.stringify(values))

            if (newValues?.amountModel == 2 && newValues?.bidAmountMin && newValues?.bidAmountMax && newValues?.bidAmountMin > newValues?.bidAmountMax) {
                message.error('随机出价最大值要大于最小值')
                return
            }

            if (newValues?.date) {
                if (newValues.dateType === '2') {
                    newValues['beginDate'] = moment(newValues.date).format('YYYY-MM-DD')
                    newValues['endDate'] = ''
                } else {
                    newValues['beginDate'] = moment(newValues.date[0]).format('YYYY-MM-DD')
                    newValues['endDate'] = moment(newValues.date[1]).format('YYYY-MM-DD')
                }
            }
            if (newValues?.timeSeries) {
                newValues['timeSeries'] = newValues.timeSeries.join('')
            }
            if (timeSeriesType === 'allDayLong') {
                newValues.timeSeries = getTimeSeriesList().join('')
            }
            if (newValues.firstDayBeginTime) {
                newValues['firstDayBeginTime'] = moment(newValues.firstDayBeginTime).format('HH:mm:ss')
            }

            delete newValues?.date
            delete newValues?.dateType
            // if (newValues?.bidAmount) {
            //     newValues.bidAmount = newValues.bidAmount * 100
            // }
            // if (newValues?.dailyBudget) {
            //     newValues.dailyBudget = newValues.dailyBudget * 100
            // }
            console.log(newValues);
            copyAdAd.run({ ...newValues, adgroupIds: selectedRows.map((item: { adgroupId: number }) => item.adgroupId) }).then(res => {
                if (res) {
                    message.success(`复制操作完成.结果请在操作记录查询！`)//成功: ${res.success},失败: ${res.fail}
                    if (res?.fail) {
                        notification.error({
                            message: `复制失败`,
                            description: `成功: ${res.success},复制失败${res.fail}条,失败的请到任务列表查看`,
                            duration: 0
                        });
                    }
                    onChange?.()
                }
            })
        })
    }

    /** 禁止选择以前时间 */
    const disabledDate: RangePickerProps['disabledDate'] = current => {
        // Can not select days before today and today
        return current && current < moment().startOf('day');
    };
    return <Modal
        title="复制广告"
        open={visible}
        onOk={handleOk}
        width={800}
        onCancel={() => onClose?.()}
        confirmLoading={copyAdAd.loading}
    >
        <Form
            form={form}
            labelCol={{ span: 4 }}
            className='ad_form_style'
            colon={false}
            initialValues={{
                amountModel: 1,
                dateType: '2',
                date: moment().startOf('day'),
                timeSeries: getTimeSeriesList(),
                firstDayBeginTime: moment('2023-02-24 00:00:00'),
                copyCount: 1,
                configuredStatus: null,
                isCopyAdcreative: true
            }}
        >
            <Form.Item label={<strong>投放日期</strong>} name='dateType'>
                <Radio.Group onChange={(e) => {
                    if (e.target.value === "1") {
                        form.setFieldsValue({ date: [moment().startOf('day'), moment().startOf('day').add(1, 'M')] })
                    }
                    if (e.target.value === "2") {
                        form.setFieldsValue({ date: moment().startOf('day') })
                    }
                }}>
                    <Radio.Button value="1">选择开始与结束日期</Radio.Button>
                    <Radio.Button value="2">长期投放</Radio.Button>
                </Radio.Group>
            </Form.Item>
            {/* 投放日期的不同展示不同的日期选择 */}
            {dateType === '1' ? <Form.Item name='date' rules={[{ required: true, message: '请选择日期' }]}>
                <RangePicker style={{ marginLeft: 125 }} disabledDate={disabledDate}></RangePicker>
            </Form.Item> : <Form.Item name='date' style={{ marginLeft: 125 }} rules={[{ required: true, message: '请选择日期' }]}>
                <DatePickers disabledDate={disabledDate} />
            </Form.Item>}

            <Form.Item label={<strong>投放时段</strong>} style={{ marginBottom: 0 }}>
                <Space direction='vertical' style={{ width: '100%' }}>
                    <Radio.Group
                        name='timeSeriesType'
                        value={timeSeriesType}
                        onChange={(value) => {
                            setTimeSeriesType(value.target.value)
                            if (value.target.value === 'timeInterValS') {
                                setState({ isShowTime: ['1'] })
                            }
                        }}>
                        <Radio.Button value={'allDayLong'}>全天投放</Radio.Button>
                        <Radio.Button value={'timeInterValS'}>指定多个时段</Radio.Button>
                    </Radio.Group>
                    {timeSeriesType === 'timeInterValS' && <Form.Item name='timeSeries' noStyle rules={[{ required: true, message: '请选择时段' }]}>
                        <TimeInSelect />
                    </Form.Item>}
                </Space>
            </Form.Item>
            <Form.Item label={<strong></strong>}>
                <Space>
                    <Checkbox.Group options={[{ label: '指定首日开始投放时间', value: '1' }]} disabled={timeSeriesType === 'timeInterValS'} value={state.isShowTime} onChange={(checkedValue) => { setState({ ...state, isShowTime: checkedValue }) }} />
                    {state?.isShowTime?.length > 0 && <Form.Item name='firstDayBeginTime' noStyle rules={[{ required: true, message: '请选择时间' }]}>
                        <TimePicker />
                    </Form.Item>}
                </Space>
            </Form.Item>
            <Form.Item label={<strong>出价模式</strong>} name='amountModel'>
                <Radio.Group>
                    <Radio.Button value={0}>固定价格</Radio.Button>
                    <Radio.Button value={1}>随机价格</Radio.Button>
                </Radio.Group>
            </Form.Item>
            {amountModel === 1 ? <>
                <Form.Item label={<strong>最小广告出价</strong>} name='bidAmountMin' rules={[
                    {
                        required: true, message: '请输入最小出价'
                    },
                    {
                        required: true, message: `需要小于最大出价`, validator(rule, value, callback) {
                            let regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
                            if (!bidAmountMax) {
                                return Promise.resolve()
                            } else {
                                if (!regPos.test(value)) {
                                    return Promise.reject()
                                }
                                if (value < bidAmountMax) {
                                    return Promise.resolve()
                                } else {
                                    return Promise.reject()
                                }
                            }
                        },
                    }
                ]}>
                    <InputNumber placeholder="输入最小出价" style={{ width: 150 }} />
                </Form.Item>
                <Form.Item label={<strong>最大广告出价</strong>} name='bidAmountMax' rules={[
                    {
                        required: true, message: '请输入最大出价'
                    },
                    {
                        required: true, message: `需要大于最小出价`, validator(rule, value, callback) {
                            let regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
                            if (!bidAmountMin) {
                                return Promise.resolve()
                            } else {
                                if (!regPos.test(value)) {
                                    return Promise.reject()
                                }
                                if (value > bidAmountMin) {
                                    return Promise.resolve()
                                } else {
                                    return Promise.reject()
                                }
                            }
                        },
                    }
                ]}>
                    <InputNumber placeholder={`输入最大出价`} style={{ width: 150 }} />
                </Form.Item>
            </> : <Form.Item label={<strong>广告出价</strong>} name={"bidAmount"}>
                <InputNumber min={0} placeholder="价格 元" style={{ width: 150 }} />
            </Form.Item>}
            <Form.Item label={<strong>广告预算</strong>} name={"dailyBudget"}>
                <InputNumber min={0} placeholder="价格 元" style={{ width: 150 }} />
            </Form.Item>
            <Form.Item label={<strong>广告启停</strong>} name={"configuredStatus"} tooltip="默认：沿用选择广告的启停状态，开启or关闭：复制的所有广告设置成开启or关闭">
                <Select style={{ width: 100 }}>
                    <Select.Option key={null} value={null}>默认</Select.Option>
                    <Select.Option key={"AD_STATUS_NORMAL"} value={"AD_STATUS_NORMAL"}>开启</Select.Option>
                    <Select.Option key={"AD_STATUS_SUSPEND"} value={"AD_STATUS_SUSPEND"}>关闭</Select.Option>
                </Select>
            </Form.Item>
            <Form.Item label={<strong>是否复制创意</strong>} name={"isCopyAdcreative"} valuePropName="checked" tooltip="选择“是”，新建创意，复制条数不限制；选择”否“沿用旧创意，复制条数限制26条。">
                <Switch checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>
            <Form.Item label={<strong>复制数量</strong>} name='copyCount' rules={[{ required: true, message: '请输入复制数量' }]}>
                <InputNumber min={1} />
            </Form.Item>

        </Form>
    </Modal>
}

export default React.memo(Copy)