import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker, InputNumber, Checkbox, Row, Col } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import router from 'umi/router';
import moment from 'moment';
import apis from '../../../services/apis';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';
import ImageUploader from '../../../components/XForm/ImageUpload';
import BuildSelect from '../../../components/SelectButton/BuildSelect2'

const header = props => {
    const sampleId = props.location.query.id;

    const [data, setData] = useState({})

    const [visible, setVisible] = useState(false)
    // const sampleName = props.location.query.sampleName;
    // const [sampleData, setSampleData] = useState({})

    //   useEffect(() => {
    //     getSampleData(sampleId);
    //   },[])

    //   // 查询列表
    //   const getSampleData = (demandId) => {
    //       request({ ...apis.taH5SampleManager.taH5DemandById, urlData: {id: demandId} }).then((data) => {
    //           setDemandData(data)
    //           props.form.setFieldsValue(data)
    //       })
    //   }

    // 跳转到编辑
    const toDetail = rowData => () => {
        if (rowData) {
            router.push({
                pathname: '/h5SampleManager/h5Demand/edit',
                query: {
                    id: demandId,
                },
            });
            return
        }
    }

    function handleSubmit(e) {
        e.preventDefault();
        props.form.validateFields((err, values) => {
            if (!err) {
                values.h5SampleId = sampleId
                values.endDate = moment(values.endDate._d).format('YYYY-MM-DD HH:mm:ss')
                values.isMiniapp = 1
                values.fromH5Sample = true
                request({ ...apis.activity.addtaDrainage, data: { ...values } }).then(data => {
                    message.info('操作成功')
                    setData(data)
                    setVisible(true)

                }).catch(err => {
                    message.error(err.msg || err.message)
                })

                // values.sampleName = sampleName
                // request({ ...apis.taH5SampleManager.addTaH5Demand, data: { ...values } }).then(() => {
                //     message.info('保存成功')
                //     // router.go(-1);
                // }).catch((err) => {
                //     message.info(err.msg || err.message)
                // })
            }
        });
    }

    function disabledDate(current) {
        // Can not select days before today and today 
        // console.log(current, 'current')
        // return current && current < moment().startOf('day');
        return current < moment().add(0, 'd');
    }

    const disabledHours = () => {
        const hours = [];
        console.log(moment().hour(), 'moment().hour()')
        for (let i = 0; i < moment().hour(); i++) {
            hours.push(i);
        }
        return hours;
    };

    const disabledMinutes = currentDate => {
        const currentMinute = moment().minute();
        const currentHour = moment(currentDate).hour();
        const minutes = [];
        if (currentHour === moment().hour()) {
            for (let i = 0; i <= currentMinute; i++) {
                minutes.push(i);
            }
        }
        return minutes;
    };

    const disabledTime = dateTime => {
        if (moment(dateTime).isBefore(moment(), 'day')) {
            return {
                disabledHours: () => [],
                disabledMinutes: () => [],
            };
        }
        console.log(moment(dateTime).isSame(moment(), 'day'), 'moment(dateTime).isSame(moment(), )')
        console.log(moment(dateTime).isSame(moment().add(1, 'days'), 'day'), 'moment(dateTime).isSame(moment().add(1,  )')
        if (moment(dateTime).isSame(moment().add(1, 'days'), 'day')) {
            return {
                disabledHours: () => disabledHours(dateTime),
                disabledMinutes: () => disabledMinutes(dateTime),
            };
        }
    };

    const toH5Edit = () => {
        router.push({
            pathname: '/activity/drainage/h5edit',
            query: {
                id: data.activityId,
                name: data.name,
                drainageId: data.drainageId,
            },
        });
    }

    const toDrainageDetail = () => {
        router.push({
            pathname: '/activity/drainage/DetailDrainage',
            query: {
                drainageId: data.drainageId,
            },
        });
    }

    const { getFieldDecorator } = props.form;

    function validatorNum(rule, value, callback) {
        callback(value < 1 || value > 1000 ? '人数必须大于0 小于 1000' : undefined);
    }

    return (
        <>
            <Form labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} onSubmit={handleSubmit}>
                <Form.Item label="H5活动名称">
                    {getFieldDecorator('name', {
                        rules: [
                            {
                                required: true,
                                message: '请填写活动名称',
                            },
                        ],
                    })(<Input placeholder="H5活动名称" />)}
                </Form.Item>
                <Form.Item label="选择项目">
                    {getFieldDecorator('buildingId')(
                        <BuildSelect />,
                    )}
                </Form.Item>
                <Form.Item label="下架时间">
                    {getFieldDecorator('endDate', {
                        // initialValue: formsdate.endDate ? moment(formsdate.endDate, 'YYYY-MM-DD HH:mm:ss') : null,
                        rules: [
                            { required: true, message: '请输入下架时间' },

                            // {
                            //     validator: (rule, value, callback) => {
                            //         callback(moment(value).isSame(moment().add(1, 'days'), 'day') ? '金额最多5位整数 2位小数' : undefined)
                            //     }
                            // }

                        ]
                    })(
                        <DatePicker
                            showTime={{ format: 'HH:mm:ss' }}
                            disabledDate={disabledDate}
                            disabledTime={disabledTime}
                            showToday={false}
                        />,
                    )}
                </Form.Item>
                <Form.Item label="分享设置" help="建议图片尺寸：750*600px，比例5:4,格式：jpg">
                    {getFieldDecorator('shareImg', {
                        // initialValue: formsDate.shareImg,
                        rules: [
                            { required: true, message: '请选择分享图片' },
                        ]
                    })(<ImageUploader />)}
                </Form.Item>
                <Form.Item label="活动分享语" help="可使用{name}代表用户昵称。">
                    {getFieldDecorator('shareTitle', {
                        // initialValue: formsDate.shareTitle,
                        rules: [
                            { required: true, message: '请输入活动分享语' },
                        ]
                    })(
                        <Input
                            placeholder="分享语，不超过15个字"
                            maxLength="15"
                        />,
                    )}
                </Form.Item>
                <Form.Item label="中间页飞机图" help="建议图片尺寸：750*1667px，比例9:20,格式：jpg。图片底部不要放置关键信息。">
                    {getFieldDecorator('middleImg', {
                        // initialValue: formsDate.middleImg,
                        rules: [
                            { required: true, message: '请选择中间页飞机图' },
                        ]
                    })(<ImageUploader />)}
                </Form.Item>
                <Form.Item style={{ width: '400px', margin: 'auto', display: 'flex', justifyContent: 'space-between' }}>
                    <Button type="primary" htmlType="submit">保存</Button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <Button onClick={() => router.go(-1)}>取消</Button>

                </Form.Item>
                <Row>
                    <Col span={7}></Col>
                    <Col span={17}><span style={{ color: '#ef273a' }}>发布后请到资源位管理中关联资源位图，否则客户看不到</span></Col>
                </Row>
            </Form>
            <Modal
                title="新增成功"
                visible={visible}
                // onOk={handleOk}
                // confirmLoading={confirmLoading}
                onCancel={() => setVisible(false)}
                footer={null}
            // width="1000px"
            // maskClosable={false}
            >
                建议修改内容以适合您的项目，若有红包等需要消费的内容，请到资金管理中查看余额是否充足
                <div style={{ width: '300px', margin: '30px auto', display: 'flex', justifyContent: 'space-between' }}>
                    <Button type="primary" style={{ width: '140px' }} onClick={toH5Edit}>修改配置</Button>

                    <Button style={{ width: '140px' }} onClick={toDrainageDetail}>查看H5活动详情</Button>
                </div>
            </Modal>
        </>
    )
}

const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
