import { Card, DatePicker, Form, Radio, Select, Space, Switch, Tooltip } from "antd"
import React, { useContext, useEffect } from "react"
import { DispatchAd } from "./newCreateAd";
import { RangePickerProps } from "antd/lib/date-picker";
import moment from "moment";
import style from '../index.less'
import TimeInSelect from "@/pages/launchSystemNew/components/timeInSelect";
import { QuestionCircleFilled } from "@ant-design/icons";
import { AD_STATUS_ENUM, MARKETING_TARGET_TYPE_ENUM, MARKETING_TARGET_TYPE_GAME_ENUM, SelectTimeList, marketingGoalList } from "../../const";
import New1Radio from "@/pages/launchSystemV3/components/New1Radio";
import { txtLength } from "@/utils/utils";
import InputName from "@/components/InputName";

/**
 * 广告设置
 * @returns 
 */
const AdgroupsAdSetting: React.FC<{ value?: any }> = ({ value }) => {

    /****************************************/
    const { form } = useContext(DispatchAd)!;
    const timeSeriesType = Form.useWatch('timeSeriesType', form)
    const isSetfirstDayBeginTime = Form.useWatch('isSetfirstDayBeginTime', form)
    const marketingGoal = Form.useWatch('marketingGoal', form)
    const marketingTargetType = Form.useWatch('marketingTargetType', form)
    const dateType = Form.useWatch('dateType', form)
    const deliveryMethod = Form.useWatch('deliveryMethod', form);
    /****************************************/

    useEffect(() => {
        if (!(value && Object.keys(value).length)) {
            form.setFieldsValue({
                adgroupName: marketingGoalList.find(item => item.value === marketingGoal)?.label + '_' + (MARKETING_TARGET_TYPE_ENUM[marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_ENUM] || MARKETING_TARGET_TYPE_GAME_ENUM[marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_GAME_ENUM]) + '_' + localStorage.getItem('userId')// + '_' + moment().format('MM_DD_HH:mm:ss')
            })
        }
    }, [marketingGoal, marketingTargetType])

    /** 禁止选择以前时间 */
    const disabledDate: RangePickerProps['disabledDate'] = current => {
        // Can not select days before today and today
        return current && current < moment().startOf('day');
    };

    return <Card
        title={<strong style={{ fontSize: 18 }}>广告设置</strong>}
        className="cardResetCss"
    >
        <Form.Item label={<strong>投放日期</strong>} required>
            <Space direction="vertical">
                <Form.Item name='dateType' noStyle>
                    <Radio.Group
                        onChange={e => {
                            if (e.target.value === '0') {
                                form.setFieldsValue({
                                    date: [moment().startOf('day').add(7, 'day'), moment().startOf('day').add(20, 'day')],
                                    beginDate: undefined
                                })
                            } else {
                                form.setFieldsValue({
                                    date: undefined,
                                    beginDate: moment().startOf('day').add(7, 'day')
                                })
                            }
                        }}
                    >
                        <Radio value="0">指定开始及结束日期</Radio>
                        <Radio value="1">长期投放</Radio>
                    </Radio.Group>
                </Form.Item>
                {dateType === '0' ? <Form.Item name='date' rules={[{ required: true, message: '请选择投放日期' }]} noStyle>
                    <DatePicker.RangePicker disabledDate={disabledDate} />
                </Form.Item> : <Form.Item label={<strong>投放日期</strong>} name='beginDate' rules={[{ required: true, message: '请选择开始投放日期' }]} noStyle>
                    <DatePicker disabledDate={disabledDate} />
                </Form.Item>}
            </Space>
        </Form.Item>

        <Form.Item label={<strong>投放时间</strong>}>
            <Card bordered className="cardResetCss newCss" bodyStyle={{ padding: 0 }}>
                <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>选择时段</div>
                        <Form.Item name='timeSeriesType' style={{ marginBottom: 0 }}>
                            <Radio.Group>
                                <Radio value="0">全天</Radio>
                                <Radio value="2">指定多个时段</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {timeSeriesType === '2' && <div className={style.newSpace_bottom}>
                        <Form.Item name='timeSeries' noStyle rules={[{ required: true, message: '请选择时段' }]}>
                            <TimeInSelect />
                        </Form.Item>
                    </div>}
                </div>
                <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}><Space>
                            <span>首日开始时间</span>
                            <Tooltip title={`指定了多个时段需要注意星期一到星期天都没指定的时段开始时间不可选`}>
                                <QuestionCircleFilled />
                            </Tooltip>
                        </Space>

                        </div>
                        <Form.Item name='isSetfirstDayBeginTime' style={{ marginBottom: 0 }} valuePropName="checked">
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                        </Form.Item>
                    </div>
                    {isSetfirstDayBeginTime && <div className={style.newSpace_bottom}>
                        <Form.Item name='firstDayBeginTime' noStyle rules={[{ required: true, message: '请选择首日开始时间' }]}>
                            <Select
                                style={{ width: 180 }}
                                allowClear
                                placeholder='请选择首日开始时间'
                                options={SelectTimeList}
                            />
                        </Form.Item>
                    </div>}
                </div>
            </Card>
        </Form.Item>
        {deliveryMethod === 'NORMAL' && <Form.Item
            label={<Space>
                <strong>自动衍生创意</strong>
                <Tooltip title={<div>
                    <p>1.使用自动衍生创意，系统将优选广告下多个创意的多个组件，自动衍生新的组件并组成新的创意。在创意列表中，可通过“自建创意”、“衍生创意”类型进行区分；</p>
                    <p>
                        2.广告提交后不支持再次修改
                    </p>
                </div>}>
                    <QuestionCircleFilled />
                </Tooltip>
            </Space>}
            name="autoDerivedCreativeEnabled"
        >
            <New1Radio data={[{ label: '系统衍生', value: true }, { label: '关闭衍生', value: false }]} />
        </Form.Item>}
        <Form.Item label={<strong>广告状态</strong>} name="configuredStatus" rules={[{ required: true, message: '请选择广告状态' }]}>
            <New1Radio data={Object.keys(AD_STATUS_ENUM).map(key => ({ label: AD_STATUS_ENUM[key as keyof typeof AD_STATUS_ENUM], value: key }))} />
        </Form.Item>
        <Form.Item
            label={<strong>广告名称</strong>}
            name='adgroupName'
            // tooltip="下标、日期时分秒、广告账户创建时默认自带"
            rules={[
                { required: true, message: '请输入广告名称!' },
                {
                    required: true, message: '广告名称不能包含特殊字符：< > & ‘ ” / 以及TAB、换行、回车键，请修改', validator(_, value) {
                        let reg = /[&‘’“”/\n\t\f]/ig
                        if (value && reg.test(value)) {
                            return Promise.reject()
                        }
                        return Promise.resolve()
                    }
                },
                {
                    required: true, message: '请确保广告名称长度不超过60个字（1个汉字等于2个字符)', validator(_, value) {
                        if (value && txtLength(value) > 50) {
                            return Promise.reject()
                        }
                        return Promise.resolve()
                    }
                }
            ]}
        >
            <InputName placeholder='广告名称' style={{ width: 480 }} length={50} />
        </Form.Item>
    </Card>
}

export default React.memo(AdgroupsAdSetting)