import "../css/Signinstatistics.css"
import React from 'react'
import { Modal , Form, Input, Radio,DatePicker,Select,Button} from 'antd';
import moment from 'moment';
import axios from 'axios';
import TimePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
function range(start, end) {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}

function disabledDateTime() {
  return {
    disabledMinutes: () => range(1, 30).concat(range(31, 60)),
    // disabledSeconds: () => range(0,60)
  }
}

function disabledDate(current) {
  return current && current < moment().endOf('day').subtract(1, 'days');
}

const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(

  class extends React.Component {
    constructor(props){
      super(props);
      this.state = {
        course_groups:[],
        type:false,
        dateString:null,
        start_time:"",
        end_time:"",
        attendance_date:"",
        newmode:null,
        groupstype:false
      }
    }


    handleChangestart_time = (date) => {

      this.setState({
        start_time: date
      });
    };

    handleChangeend_time=(date)=>{

      this.setState({
        end_time: date
      });
    }
    getgroup_idss=(course_groups)=>{
      let newcourse_groups=course_groups;
      if(this.props.type==="edit"){
        let newlist=[]
        if(this.props.attendancesdata.groups.length>0){
          this.props.attendancesdata.groups.map((item,key)=>{
            newlist.push(item.id)
          })
        }

        newlist.map((item,key)=>{
          newcourse_groups.map((i,k)=>{
            if(i.id===item){
              i.disabled=true
            }
          })
        })

         // console.log(newlist)
        // this.setState({
        //
        // })

        this.setState({
          attendance_date: this.props.attendancesdata.attendance_date,
          start_time:new Date(this.props.attendancesdata.start_time),
          end_time:new Date(this.props.attendancesdata.end_time),
          newmode:this.props.attendancesdata.mode,
          course_groups:newcourse_groups,
          groupstype:newlist.length===0?true:false
        })


        this.props.form.setFieldsValue({
          name: this.props.attendancesdata.name,
          group_ids:newlist,
          mode:this.props.attendancesdata.mode,
          start_time:new Date(this.props.attendancesdata.start_time),
          end_time:new Date(this.props.attendancesdata.end_time),
        });
      }else{
        this.setState({
          start_time: new Date("2000-01-01T09:00:00.000+08:00"),
          course_groups:newcourse_groups,
          groupstype:false
        })

        this.props.form.setFieldsValue({
          start_time:new Date("2000-01-01T09:00:00.000+08:00"),
        });
      }

     }
    componentDidMount() {
      const coursesId=this.props.match.params.coursesId;
      let newurl=`/courses/${coursesId}/all_course_groups.json`;
      axios.get(newurl).then((response) => {
        this.getgroup_idss(response.data.course_groups)
      })



    }

    hideCreatesign=(e)=>{
      e.preventDefault();
      const {settabsdata,hideCreatesign} = this.props;
      const coursesId=this.props.match.params.coursesId;
      this.setState({
        type:true
      })
      this.props.form.validateFields((err, values) => {

        if (!err) {
          if(moment(values.end_time).format('HH:mm')<moment(values.start_time).format('HH:mm')){
            this.props.showNotification(`结束时间不能小于起始时间`);
            this.setState({
              type:false
            })
            return
          }
          if( moment(values.start_time).format('HH:mm')===moment(values.end_time).format('HH:mm')){
            this.props.showNotification(`结束时间不能与起始时间相同`);
            this.setState({
              type:false
            })
            return
          }

          if(this.props.type==="edit"){

            const attendancesid=this.props.attendancesid;

            let url=`/attendances/${attendancesid}.json`
            axios.put(url,{
                attendance_date:moment(values.attendance_date).format('YYYY-MM-DD'),
                end_time: moment(values.end_time).format('HH:mm'),
                group_ids:values.group_ids,
                mode: values.mode,
                name: values.name,
                start_time:moment(values.start_time).format('HH:mm'),
              }
            ).then((response) => {
              if (response.data.status == 0) {
                this.props.showNotification(`创建签到成功`);
                this.setState({
                  type:false
                })
                hideCreatesign()
                settabsdata()
              }
            }).catch((error) => {
              console.log(error)
            })

          }else{
            let url=`/weapps/courses/${coursesId}/attendances.json`;

            axios.post(url, {
              attendance_date:moment(values.attendance_date).format('YYYY-MM-DD'),
              end_time: moment(values.end_time).format('HH:mm'),
              group_ids:values.group_ids,
              mode: values.mode,
              name: values.name,
              start_time:moment(values.start_time).format('HH:mm'),
            })
              .then((response) => {
                if (response.data.status == 0) {
                  this.props.showNotification(`创建签到成功`);
                  this.setState({
                    type:false
                  })
                  hideCreatesign()
                  settabsdata()
                }
              })
              .catch(function (error) {
                console.log(error);
              });
          }



        }else{
          this.setState({
            type:false
          })
        }


      });
    }
    //  getDisabledHours=()=> {
    //   let hours = []
    //   if(this.state.dateString===moment().format('YYYY-MM-DD')){
    //     let time = moment().format('HH:mm')
    //     let timeArr = time.split(':')
    //     for (var i = 0; i < parseInt(timeArr[0]); i++) {
    //       hours.push(i)
    //     }
    //   }
    //
    //   return hours
    // }
    //
    //  getDisabledMinutes=(selectedHour)=>{
    //    let minutes = []
    //    if(this.state.dateString===moment().format('YYYY-MM-DD')){
    //      let time =  moment().format('HH:mm')
    //      let timeArr = time.split(':')
    //      if (selectedHour == parseInt(timeArr[0])) {
    //        for(var i = 0; i < parseInt(timeArr[1]); i++) {
    //          minutes.push(i)
    //        }
    //      }
    //    }
    //   return minutes
    // }

     onChange=(date, dateString)=>{
      this.setState({
        dateString:dateString
      })
    }
    render() {
      const { visible,form ,setRadio,Radiolist,hideCreatesign,editvisible} = this.props;
      let {course_groups,newmode,groupstype}=this.state;
      const { getFieldDecorator } = form;
      const { Option } = Select;
      const formItemLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 19},
      };

      const leftbuton={
        "width":"130px",
        "height":"40px",
        "border":"1px solid rgba(76,172,255,1)",
        "borderRadius":"4px",
      }

      const rightbuton={
        "width":"130px",
        "height":"40px",
        "background":"#4CACFF",
       "borderRadius":"4px",
      }


      return (
        <Modal
          visible={editvisible?editvisible:visible}
           title={this.props&&this.props.type==="edit"?"编辑签到":"创建签到"}
           closable={false}
           footer={null}
           width={600}
          destroyOnClose={true}
        >
          <Form {...formItemLayout}>

            <Form.Item label="签到名称：">
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入签到名称' },{whitespace:true,message: '请勿输入空格'}],
              })(<Input placeholder="请输入签到名称" style={{height:"40px"}} />)}
            </Form.Item>

            <Form.Item label="签到班级：">
              {getFieldDecorator('group_ids')(
                <Select mode="multiple" placeholder={this.props&&this.props.type==="edit"&&this.state.groupstype===true?"已选择全部分班":course_groups.length>0?"不选择分班时默认选择全部学生":'暂无分班，将默认选择课堂全部学生'} getPopupContainer={trigger => trigger.parentNode}
                        disabled={this.props&&this.props.type==="edit"&&this.state.groupstype===true?true:false}
                >

                  {course_groups.map((item,key)=>{
                  return(
                    <Option value={item.id} key={key} disabled={item.disabled?item.disabled:false}>{item.name}</Option>
                  )
                  })}

                </Select>,
              )}
            </Form.Item>

            <Form.Item label="签到方式：" >
              {getFieldDecorator('mode', {
                rules: [{ required: true, message: '请选择签到方式' }],
              })(
                <Radio.Group onChange={setRadio} getPopupContainer={trigger => trigger.parentNode}>
                  <Radio value="QUICK">快捷签到</Radio>
                  <Radio value="NUMBER">签到码签到</Radio>
                  <Radio value="QRCODE">二维码签到</Radio>
                </Radio.Group>,
              )}
              {Radiolist==="QUICK"||!Radiolist&&newmode==="QUICK"?<div
                style={{color:"#E6A23C",
                height:"15px",
                lineHeight: "15px"}}>学生点击签到按钮即可完成签到</div>:""}

              {Radiolist==="NUMBER"||!Radiolist&&newmode==="NUMBER"?<div
                style={{color:"#E6A23C",
                  height:"15px",
                  lineHeight: "15px"}}
              >学生需要输入签到码才能完成签到</div>:""}

              {Radiolist==="QRCODE"||!Radiolist&&newmode==="QRCODE"?<div
                style={{color:"#E6A23C",
                  height:"15px",
                  lineHeight: "15px"}}
              >学生需从小程序进入课堂扫码才能完成签到</div>:""}
            </Form.Item>

            <Form.Item label="签到日期：">
              {getFieldDecorator('attendance_date',  {
                initialValue:this.props.type==="edit"?moment(this.state.attendance_date,'YYYY-MM-DD'):"",
                rules: [{required: true, message: '请选择签到日期',}],
              })(<DatePicker style={{width:"413px"}} getPopupContainer={trigger => trigger.parentNode}
                             disabledTime={disabledDateTime}
                             disabledDate={disabledDate}
                             onChange={this.onChange}
                             // value={moment('2015-01-01', 'YYYY-MM-DD')}
              />)}
            </Form.Item>
            <style>
              {
                `
                #form_in_modal_start_time{
                   width:413px;
                   padding-left: 10px;
                }
                
                #form_in_modal_end_time{
                   width:413px;
                   padding-left: 10px;
                }
                `
              }
            </style>
            <Form.Item label="开始时间：">
              {getFieldDecorator('start_time',  {
                rules: [{ type: 'object', required: true, message: '请选择开始时间' }],
              })(
                // <TimePicker style={{width:"413px"}} format={format} getPopupContainer={trigger => trigger.parentNode}/>
                <TimePicker
                  style={{width:"413px"}}
                  selected={this.state.start_time}
                  onChange={date => this.handleChangestart_time(date)}
                  showTimeSelect
                  showTimeSelectOnly
                  timeIntervals={10}
                  timeCaption="Time"
                  timeFormat="HH:mm"
                  dateFormat="HH:mm"
                  getPopupContainer={trigger => trigger.parentNode}
                />
                )}
            </Form.Item>

            <Form.Item label="结束时间：">
              {getFieldDecorator('end_time',  {
                rules: [{ type: 'object', required: true, message: '请选择结束时间' }],
              })(
                // <TimePicker style={{width:"413px"}} format={format} getPopupContainer={trigger => trigger.parentNode}
                // disabledHours={this.getDisabledHours}
                // disabledMinutes={this.getDisabledMinutes}
                //
                // />
                <TimePicker
                style={{width:"413px"}}
                selected={this.state.end_time}
                onChange={date => this.handleChangeend_time(date)}
                showTimeSelect
                showTimeSelectOnly
                timeIntervals={10}
                minTime={this.state.dateString===moment().format('YYYY-MM-DD')||this.state.dateString===null?new Date():false}
                maxTime={this.state.dateString===moment().format('YYYY-MM-DD')||this.state.dateString===null?moment().endOf('day').toDate():false}
                timeCaption="Time"
                timeFormat="HH:mm"
                dateFormat="HH:mm"
                getPopupContainer={trigger => trigger.parentNode}
                />
                )}
            </Form.Item>


              <div className={"mt20 marginauto clearfix edu-txt-center"}>
                <a>
                  <Button type="primary" ghost style={leftbuton} onClick={hideCreatesign}>
                    取消
                  </Button>
                </a>

                <a>
                  <Button type="primary" className={"ml20"} style={rightbuton}  onClick={(e)=>this.hideCreatesign(e)} loading={this.state.type}>
                    确定
                  </Button>
                </a>

              </div>


          </Form>
        </Modal>
      );
    }
  },
);

class Createsignmodel extends React.Component {
  state = {
    Radiolist: null,
  };
  setRadio=(e)=>{

    this.setState({
      Radiolist:e.target.value
    })
  }
  render() {

    return (
      <React.Fragment>
        <CollectionCreateForm
          {...this.state}
          {...this.props}
          setRadio={(e)=>this.setRadio(e)}
        />
      </React.Fragment>
    );
  }
}

export default Createsignmodel;


