import React, {useState, useEffect} from 'react';
import {WhiteSpace, WingBlank, Modal, Button, List, InputItem, DatePicker, Toast} from 'antd-mobile'
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
import Document from 'react-document-title'
import Skeleton from '../../../components/Skeleton'
import axiosRequest from '../../../utils/request';
import '../index.less'
import { createForm } from 'rc-form';
import moment from 'moment'

const alert = Modal.alert;

const DateCalendar = (props) => {
    // const [value, onChange] = useState(new Date());

    useEffect(() => {
        getRange()
        getDate()
    }, []);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const getDate = (dd) => {
        setLoading(true);
        const starttime = moment(dd).startOf('day').format("YYYY-MM-DD HH:mm:ss");
        const endtime = moment(dd).endOf('day').format("YYYY-MM-DD HH:mm:ss");
        axiosRequest({
            method: 'post',
            url: '/idtAppServiceV6/application/interfaces/getMyRcList.jsp',
            body: {starttime, endtime}
        }).then(res => {
            setLoading(false);
            setData(res);
        });
    }


    const [visible, setVisible] = useState(false);
    const [editVisible, setEditVisible] = useState(false);
    const {getFieldProps} = props.form;

    const onSubmit = () => {
        props.form.validateFields({ force: true }, (error) => {
            if (!error) {
                const values = props.form.getFieldsValue();
                values.starttime = moment(values.starttime).format("YYYY-MM-DD HH:mm:ss");
                values.endtime = moment(values.endtime).format("YYYY-MM-DD HH:mm:ss");
                axiosRequest({
                    method: 'post',
                    url: '/idtAppServiceV6/application/interfaces/addCalendar.jsp',
                    body: values,
                }).then(res => {
                    Toast.success('添加成功');
                    getDate();
                    onReset()
                });
            }
        });
    };
    const onReset = () => {
        setEditVisible(false);
        props.form.resetFields();
    };
    //自定义日历组件
    const [selectedDays, setSelectedDays] = useState(new Date(moment()));
    const WEEKDAYS_LONG = {
        zh: ['周日', '周一', '周二', '周三', '周四', '周五', '周六',]
    };
    const WEEKDAYS_SHORT = {
        zh: ['日', '一', '二', '三', '四', '五', '六'],
    };
    const MONTHS = {
        zh: ['01 月', '02 月', '03 月', '04 月', '05 月', '06 月', '07 月', '08 月', '09 月', '10 月', '11 月', '12 月'],
    };
    const FIRST_DAY = { zh: 0 };
    function formatDay(d, locale = 'zh') {
        return `${WEEKDAYS_LONG[locale][d.getDay()]}, ${d.getDate()} ${
            MONTHS[locale][d.getMonth()]
            } ${d.getFullYear()}`;
    }
    function formatMonthTitle(d, locale = 'zh') {
        return `${d.getFullYear()} 年 ${MONTHS[locale][d.getMonth()]} `;
    }
    function formatWeekdayShort(i, locale = 'zh') {
        return WEEKDAYS_SHORT[locale][i];
    }
    function formatWeekdayLong(i, locale = 'zh') {
        return WEEKDAYS_SHORT[locale][i];
    }
    function getFirstDayOfWeek(locale = 'zh') {
        return FIRST_DAY[locale];
    }
    const localeUtils = {
        formatDay,
        formatMonthTitle,
        formatWeekdayShort,
        formatWeekdayLong,
        getFirstDayOfWeek,
    };

    //查看详情
    const [birthday, setBirthday] = useState([]);
    const modifiers = {birthday: birthday};
    const getRange = (dd) => {
        const starttime = moment(dd).startOf('month').format("YYYY-MM-DD HH:mm:ss");
        const endtime = moment(dd).endOf('month').format("YYYY-MM-DD HH:mm:ss");
        axiosRequest({
            method: 'post',
            url: '/idtAppServiceV6/application/interfaces/getMyRc.jsp',
            body: {starttime, endtime},
        }).then(res => {
            const date = [];
            res.map(item => {
                let time = item.SJ;
                let year = parseInt(time.substr(0, 4), 0);
                let month = parseInt(time.substr(4, 2), 0) - 1;
                let day = parseInt(time.substr(6, 2), 0);
                let result = moment(new Date(year, month, day)).startOf('day').valueOf();
                date.indexOf(result) < 0 && date.push(result);
                return null;
            });
            const bir = date.map(item => new Date(item));
            setBirthday(bir)
        });
    };

    const dateDelete = () => {
        setVisible(false);
        alert('删除日程', '确定删除此日程吗', [
            { text: '取消', onPress: () =>  setVisible(true)},
            {
                text: '确认',
                onPress: () =>
                    new Promise((resolve) => {
                        axiosRequest({
                            method: 'post',
                            url: '/idtAppServiceV6/application/interfaces/deleteGRRC.jsp',
                            body: {uuid: dateInfo.UUID},
                        }).then(res => {
                            resolve();
                            Toast.success('删除成功', 1, () => {
                                getDate(selectedDays);
                            })

                        });
                    }),
            },
        ])

    };

    const [dateInfo, setDateInfo] = useState({});
    const openInfo = (item) => {
        setDateInfo(item);
        setVisible(true)
    };

    const monthChange = day => {
        setSelectedDays(day);
        getDate(day);
        getRange(day)
    };
    const daySelect = day => {
        setSelectedDays(day);
        getDate(day);
    };
    console.log(modifiers)
    return (
        <Document title="待办">
            <WingBlank>
                <WhiteSpace/>
                <div className="auto-day-picker">
                    <DayPicker
                        locale="zh"
                        localeUtils={localeUtils}
                        modifiers={modifiers}
                        selectedDays={selectedDays}
                        onDayClick={daySelect}
                        onMonthChange={monthChange}
                    />
                </div>
                <WhiteSpace/>
                <div className="date-todo-card">
                    {loading ? <Skeleton/> : data.length > 0 && data.map((item, index) => (
                        <div key={index} className="date-todo-item" onClick={() => openInfo(item)}>
                            <div>{item.SUBJECT}</div>
                            <div>
                                <p>{item.TIME.split('-')[0]}</p>
                                <p>{item.TIME.split('-')[1]}</p>
                            </div>
                        </div>
                    ))}
                    {}
                </div>
                <Modal
                    className="date-modal"
                    visible={editVisible}
                    transparent
                    onClose={() => setEditVisible(false)}
                >
                    <form>
                        <List>
                            <InputItem
                                {...getFieldProps('subject')}
                                placeholder="请输入标题"
                            >输入标题</InputItem>
                            <DatePicker
                                {...getFieldProps('starttime', {rules: [{ required: true, message: '必须选择开始日期' }],})}
                            >
                                <List.Item>选择开始日期</List.Item>
                            </DatePicker>
                            <DatePicker
                                {...getFieldProps('endtime', {rules: [{ required: true, message: '必须选择开始日期' }]})}
                            >
                                <List.Item>选择结束日期</List.Item>
                            </DatePicker>
                        </List>
                        <div className="modal-form-footer">
                            <Button className="date-button mr-12 bg-gray" inline onClick={onReset}>取消</Button>
                            <Button className="date-button" inline type="primary" onClick={onSubmit}>保存日程</Button>
                        </div>
                    </form>
                </Modal>
                <Modal
                    className="date-modal"
                    visible={visible}
                    transparent
                    onClose={() => setVisible(false)}
                >
                    <List className="date-info">
                        <InputItem disabled={true} extra={dateInfo.SUBJECT}>标题</InputItem>
                        <InputItem disabled={true} extra={dateInfo.TIME && moment(selectedDays).format("YYYY-MM-DD") + ' ' + dateInfo.TIME.split('-')[0]}>开始日期</InputItem>
                        <InputItem disabled={true} extra={dateInfo.TIME && moment(selectedDays).format("YYYY-MM-DD") + ' ' + dateInfo.TIME.split('-')[1]}>结束日期</InputItem>
                    </List>
                    <div className="modal-form-footer-right">
                        <Button className="date-button" inline type="warning" onClick={dateDelete}>删除日程</Button>
                    </div>
                </Modal>
                <div className="event-footer">
                    <div className="event-footer-button" onClick={() => setEditVisible(true)}>添加日程</div>
                </div>

            </WingBlank>

        </Document>
    );
};

export default createForm()(DateCalendar);
