import React, { useEffect, useState } from "react";
import { DatePicker, TimePicker, Select, message } from 'antd';
import StoreService from "@/domains/store-domain/storeService";
import "./AddLiveClassInfoWorkWX.less";
import GraphicsEditor from "./GraphicsEditor";
import moment from "moment";
import _ from "underscore";
const { Option } = Select;

const defaultTeacherQuery = {
    size: 15,
    current: 1,
    nickName:null
  }

export default function AddLiveClassInfoWorkWX(props) {

    const [teacherQuery, setTeacherQuery] = useState(defaultTeacherQuery)
    const [teacherList, setTeacherList] = useState([])
    const [hasNext, setHasNext] = useState(false)

    const [introduce, setIntroduce] = useState({content:props.introduce})
    const [duration, setDuration] = useState(props.data.duration)
    const [cusTime, setCusTime] = useState(false)

    const [beginDate, setBeginDate] = useState(0)
    const [beginTime, setBeginTime] = useState(0)
    const [endDate, setEndDate] = useState(0)
    const [endTime, setEndTime] = useState(0)
    const [teacherId, setTeacherId] = useState("")
    const [remindTime, setRemindTime] = useState(0)

    useEffect(()=> {
        setBeginTime(props.data.startTime)
        setBeginDate(moment(props.data.startTime).startOf('day').valueOf())
        setEndTime(props.data.startTime+Number(props.data.duration))
        setEndDate(moment(props.data.startTime+Number(props.data.duration)).startOf('day').valueOf())
        setTeacherId(props.data.teacherId)
        setRemindTime(props.data.remindTime)
    },[props.data])

    useEffect(()=> {
        let intro = {content:props.introduce};
        setIntroduce(intro)
    },[props.introduce])

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

    //开始日期
    function onBeginDateChange(date, dateString) {
        if (date) {
            if (date.isBefore(moment())) {
                message.warning('开始日期不能早于当前日期')
                setBeginDate(moment().startOf('day').valueOf())
            } else {
                let _begindate = date.startOf('day').valueOf();
                let _begintime = moment(beginTime)
                let datetime = _begindate+(_begintime.hour()*60+_begintime.minute())*60*1000
                setBeginTime(datetime)
                props.onChange("beginTime",datetime)
                if (!cusTime) {
                    props.onChange("endTime",datetime+duration)
                }
                setBeginDate(_begindate)
            }
        } else {
            setBeginDate(0)
        }
    }

    function onBeginDateOK(date) {
        console.log(date)
    }
    //开始时间
    function onBeginTimeChange(date, dateString) {
        console.log("onBeginTimeChange",date)
        // props.onChange("beginTime",date.valueOf())
    }

    function onBeginTimeOK(time) {
        if (time.isBefore(moment())) {
            message.warning('开始时间不能早于当前时间')
            return
        }
        let begin = beginDate+(time.hour()*60+time.minute())*60*1000
        setBeginTime(begin)
        props.onChange("beginTime",begin)
        if (!cusTime) {
            props.onChange("endTime",begin+duration)
        }
        
    }
    //结束日期
    function onEndDateChange(date, dateString) {
        if (date) {
            let _endDate = date.startOf('day').valueOf()
            let _endtime = moment(endTime)
            let datetime = _endDate+(_endtime.hour()*60+_endtime.minute())*60*1000
            setEndTime(datetime)
            props.onChange("endTime",datetime)
            setEndDate(_endDate)
        } else {
            setEndDate(0)
        }
        
    }

    function onEndDateOK(date) {

    }
    //结束时间
    function onEndTimeChange(date, dateString) {
        // props.onChange("endTime",date.valueOf())
    }

    function onEndTimeOK(time) {
        if (time.isSameOrBefore(moment(beginTime))) {
            message.warning('结束时间不能早于开始时间')
            return
        }
        let end = endDate+(time.hour()*60+time.minute())*60*1000
        setEndTime(end)
        props.onChange("endTime",end)
    }

    function onDurationChange(value, option) {
        if (value === 0) {
            setCusTime(true)
            return
        }
        let d = value*60*1000;
        setDuration(d)
        props.onChange("endTime",beginTime+d)
    }

    function onTeacherChange(value, option) {
        setTeacherId(value)
        props.onChange("teacherId",value)
    }

    function onRemindChange(value, option) {
        setRemindTime(value)
        props.onChange("remindTime",value)
    }

    function onChangeIntro(val) {
        let intro = {...introduce}
        intro.content = val
        setIntroduce(intro)
        props.onChange("intro",val)
    }

    function getTeacherList(current = 1) {
        const _query = {
          ...teacherQuery
        };
        StoreService.getStoreUserBasicPage(_query).then((res) => {
            const { result = {} } = res;
            const { records = [], total = 0, hasNext } = result;
            const list = _query.current > 1 ? teacherList.concat(records) : records;
            console.log(list)
            setTeacherList(list)
            setHasNext(hasNext)
        });
    }
    useEffect(()=> {
        getTeacherList()
    },[teacherQuery])

       // 滑动加载更多讲师列表
    function handleScrollTeacherList(e) {
        const container = e.target;

        //判定元素是否滚动到底部
        const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
        if (scrollToBottom && hasNext) {
            let _teacherQuery = teacherQuery;
            _teacherQuery.current = _teacherQuery.current + 1
            setTeacherQuery({..._teacherQuery})
        }
    }

    return (
        <div className="AddLiveClassInfoWorkWX">
            <div className="begin-time item">
                <span className="label"><span className="require">*</span>开始时间：</span>
                <DatePicker  
                value={beginDate===0?undefined:moment(beginDate)}
                onChange={onBeginDateChange} 
                onOk={onBeginDateOK} 
                disabledDate={disabledDate}
                />
                <TimePicker 
                value={beginTime===0?undefined:moment(beginTime)}
                onChange={onBeginTimeChange} 
                onOk={onBeginTimeOK} 
                format="HH:mm" />
            </div>
            <div className="duration-time item">
                {
                    cusTime || props.type === "edit" ? (
                        <>
                        <span className="label"><span className="require">*</span>结束时间：</span>
                        <DatePicker 
                        value={endDate===0?undefined:moment(endDate)}
                        onChange={onEndDateChange} 
                        onOk={onEndDateOK} 
                        disabledDate={(current)=> {
                            return current && current < beginDate
                        }}
                        />
                        <TimePicker 
                        value={endTime === 0?undefined:moment(endTime)}
                        onChange={onEndTimeChange} 
                        onOk={onEndTimeOK} 
                        format="HH:mm" />
                        </>
                    ) : (
                        <>
                        <span className="label"><span className="require">*</span>时长：</span>
                        <Select onChange={onDurationChange} defaultValue={60} style={{width:"140px"}}>
                            <Option value={30}>0.5小时</Option>
                            <Option value={60}>1.0小时</Option>
                            <Option value={120}>2.0小时</Option>
                            <Option value={180}>3.0小时</Option>
                            <Option value={0}>自定义结束时间</Option>
                        </Select>
                        </>
                    )
                }

            </div>
            <div className="teacher item">
                <span className="label"><span className="require">*</span>讲师：</span>
                <Select 
                value={teacherId}
                onChange={onTeacherChange} 
                style={{width:"240px"}} 
                placeholder="请选择讲师"
                disabled={!props.isEdit ? true: false}
                filterOption={(input, option) => option}
                showSearch
                allowClear
                onPopupScroll={handleScrollTeacherList}
                onSearch={(value)=> {
                    let query = {...teacherQuery}
                    query.nickName = value
                    query.current = 1
                    setTeacherQuery(query)
                }}
                onClear={()=> {
                    setTeacherQuery({
                        current: 1,
                        nickName: null,
                        size: 15
                    })
                }}
                >
                    {
                    teacherList.map((item, index) => {
                        return (
                        <Select.Option value={item.id} key={item.id}>{item.nickName}</Select.Option>
                        );
                    })
                    }
                </Select>
            </div>
            <div className="remind-time item">
                <span className="label"><span className="require">*</span>提醒时间：</span>
                <Select value={remindTime} onChange={onRemindChange} defaultValue={0} style={{width:"100px"}}>
                    <Option value={0}>无</Option>
                    <Option value={300}>5分钟前</Option>
                    <Option value={3600}>1小时前</Option>
                    <Option value={86400}>1天前</Option>
                </Select>
            </div>
            <div className="introduce item">
                <span className="label">直播简介：</span>
                <div className="intro-edit">
                    <GraphicsEditor
                    id='intro'
                    isIntro={true}
                    maxLimit={1000}
                    detail={introduce}
                    onChange={(val) => {
                        onChangeIntro(val);
                    }}
                    ></GraphicsEditor>
                </div>
            </div>
        </div>
    )
}