import React, { useEffect, useState } from "react";
import { DatePicker, TimePicker, Select, Form, 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(props.data.startTime===0?0:moment(props.data.startTime).startOf('day').valueOf())
    const [beginTime, setBeginTime] = useState(props.data.startTime)
    const [endDate, setEndDate] = useState((moment(props.data.endTime).startOf('day').valueOf()))
    const [endTime, setEndTime] = useState(props.data.endTime)
    const [teacherId, setTeacherId] = useState(props.data.teacherId)
    const [remindTime, setRemindTime] = useState(props.data.remindTime)

    // useEffect(()=> {
    //     setBeginTime(props.data.startTime)
    //     setBeginDate(props.data.startTime===0?0:moment(props.data.startTime).startOf('day').valueOf())
    //     if (props.data.startTime !== 0) {
    //         setEndTime(props.data.startTime+Number(props.data.duration)*1000)
    //         setEndDate(moment(props.data.startTime+Number(props.data.duration)*1000).startOf('day').valueOf())
    //     }
    //     setTeacherId(props.data.teacherId)
    //     setRemindTime(props.data.remindTime)
    // },[props.data])

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

    useEffect(()=> {
        let query = {...defaultTeacherQuery,nickName:props.data.teacherName}
        setTeacherQuery(query)
    },[])

    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 = beginTime === 0 ? moment().add(5,'minutes') : moment(beginTime)
                let datetime = _begindate+(_begintime.hour()*60+_begintime.minute())*60*1000
                setBeginTime(datetime)
                props.onChange("beginTime",datetime)
                setBeginDate(_begindate)
            // }
        } else {
            setBeginDate(0)
        }
    }

    function onBeginDateOK(date) {
        console.log(date)
    }
    //开始时间
    function onBeginTimeChange(time, dateString) {
        let begin = beginDate+(time.hour()*60+time.minute())*60*1000
        if (beginDate === 0) {
            begin = time.valueOf()
        }
        setBeginTime(begin)
        props.onChange("beginTime",begin)
    }

    function onBeginTimeOK(time) {

        // if (time.isBefore(moment())) {
        //     message.warning('开始时间不能早于当前时间')
        //     return
        // }
        let begin = beginDate+(time.hour()*60+time.minute())*60*1000
        if (beginDate === 0) {
            begin = time.valueOf()
        }
        setBeginTime(begin)
        
        props.onChange("beginTime",begin)       
    }
    //结束日期
    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(time, dateString) {
        // if (time.isSameOrBefore(moment(beginTime))) {
        //     message.warning('结束时间不能早于开始时间')
        //     return
        // }
        let end = endDate+(time.hour()*60+time.minute())*60*1000
        if (endDate === 0) {
            end = time.valueOf()
        }
        setEndTime(end)
        props.onChange("endTime",end)
    }

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

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

    function onTeacherChange(value, option) {
        setTeacherId(value)
        props.onChange("teacherId",{teacherId:value,teacherName:option ? option.children:undefined})
    }

    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) {
        let _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;
            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})
        }
    }

    function exItem(id) {
        const item = _.find(props.exItems,(item)=> {return item.id === id})
        return (
            item ? <div style={{position:"absolute",color:"#FF4F4F"}}>{item.msg}</div> : ""
        )
    }

    return (
        <div className="AddLiveClassInfoWorkWX">
            <div className="begin-time item">
                <span className="label"><span className="require">*</span>开始时间：</span>
                <div id="startTime" style={{display:"inline-block"}}>
                <DatePicker 
                className={_.find(props.exItems,(item)=>{return item.id === "startTime"})?"err":""}
                 placeholder="请选择开始日期"
                value={beginDate===0?undefined:moment(beginDate)}
                onChange={onBeginDateChange} 
                onOk={onBeginDateOK} 
                disabledDate={disabledDate}
                style={{width:"180px"}}
                />
                <TimePicker 
                className={_.find(props.exItems,(item)=>{return item.id === "startTime"})?"err":""}
                value={beginTime===0?undefined:moment(beginTime)}
                onChange={onBeginTimeChange} 
                onOk={onBeginTimeOK} 
                allowClear={false}
                format="HH:mm" 
                style={{width:"120px"}}
                />
                {exItem("startTime")}
                </div>
            </div>

            <div className="duration-time item" id="odqboqwdq">
                {
                    cusTime || props.type === "edit" ? (
                        <>
                        <span className="label"><span className="require">*</span>结束时间：</span>
                        <div id="endTime" style={{display:"inline-block"}}>
                        <DatePicker 
                        className={_.find(props.exItems,(item)=>{return item.id === "endTime"})?"err":""}
                        placeholder="请选择结束日期"
                        value={endDate===0?undefined:moment(endDate)}
                        onChange={onEndDateChange} 
                        onOk={onEndDateOK} 
                        disabledDate={(current)=> {
                            return current && current < beginDate
                        }}
                        style={{width:"180px"}}
                        />
                        <TimePicker 
                        className={_.find(props.exItems,(item)=>{return item.id === "endTime"})?"err":""}
                        value={endTime === 0?moment().add(5,'minutes'):moment(endTime)}
                        onChange={onEndTimeChange} 
                        onOk={onEndTimeOK} 
                        allowClear={false}
                        format="HH:mm" 
                        style={{width:"120px"}}
                        />
                        {exItem("endTime")}
                        </div>
                        </>
                    ) : (
                        <>
                        <span className="label"><span className="require">*</span>时长：</span>
                        <Select onChange={onDurationChange} defaultValue={60} style={{width:"300px"}} getPopupContainer={()=> document.getElementById("odqboqwdq")} className="eerr">
                            <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" id="ieouwowerwe">
                <span className="label"><span className="require">*</span>讲师：</span>
                <div id="teacherId" style={{display:"inline-block"}}>
                <Select 
                value={teacherId}
                onChange={onTeacherChange} 
                className={_.find(props.exItems,(item)=>{return item.id === "teacherId"})?"err":""}
                
                placeholder="请选择讲师"
                disabled={!props.isEdit ? true: false}
                filterOption={(input, option) => option}
                getPopupContainer={()=> document.getElementById("ieouwowerwe")}
                style={{width:"300px"}}
                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
                    })
                    setTeacherId(undefined)
                    props.onChange("teacherId",{teacherId:undefined,teacherName:undefined})
                }}
                onDropdownVisibleChange={(open)=> {
                    if (open) {
                        let query = {...teacherQuery,nickName:null}
                        setTeacherQuery(query)
                    }
                }}
                >
                    {
                    teacherList.map((item, index) => {
                        return (
                        <Select.Option value={item.id} key={item.id}>{item.nickName}</Select.Option>
                        );
                    })
                    }
                </Select>
                {exItem("teacherId")}
                </div>
            </div>
            <div className="remind-time item" id="jfjfiemc">
                <span className="label"><span className="require">*</span>提醒时间：</span>
                <Select 
                onChange={onRemindChange} 
                placeholder={"15分钟前"} 
                style={{width:"180px"}} 
                getPopupContainer={()=> document.getElementById("jfjfiemc")}
                >
                    <Option value={0}>无</Option>
                    <Option value={300}>5分钟前</Option>
                    <Option value={900}>15分钟前</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" id="intro">
                    <GraphicsEditor
                    id='intro'
                    isIntro={true}
                    maxLimit={1000}
                    detail={introduce}
                    onChange={(val) => {
                        onChangeIntro(val);
                    }}
                    ></GraphicsEditor>
                </div>
            </div>
        </div>
    )
}