import React, { useEffect, useState } from "react";
import { DatePicker, Form, message } from "antd";
import WordsInput from "../components/wordsInput";
import './index.scss';
import '../index.scss';
import Link from "react-router-dom/Link";
import { editRules, getRules, updateRules } from "../api";
import moment from "moment";
import { queryString } from "educoder";

const {RangePicker} = DatePicker;

function ReviewRules({form, history, match, mygetHelmetapi}) {
  const {main_web_site_url} = mygetHelmetapi;
  //id：竞赛或者创客任务id，containerType，1创客2竞赛
  const {containerId, containerType} = match.params;
  const {identifier, name, status, createdAt, collectingEndTime, choosingDays, reviewStartTime, reviewEndTime} = queryString.parse(window.location.search.slice(1));
  const { getFieldDecorator,setFieldsValue } = form;
  //是否有初始值
  const [ initValue, setInitValue] = useState(false);
  const disabledDate = (current) =>{
    if(containerType == 1){
      //创客任务
      if(status == 1){
        const start = new Date((new Date(createdAt.replace("%20", " "))/1000 - 86400)*1000);
        return current && current < moment(start).endOf('day');
      }else if(status == 3){
        const start = new Date((new Date(collectingEndTime.replace("%20", " "))/1000 - 86400)*1000);
        const endDate = new Date((new Date(collectingEndTime.replace("%20", " "))/1000 + 86400*(choosingDays))*1000);
        return current && current < moment(start).endOf('day') || current > moment(endDate).endOf('day');
      }
    }else{
      //竞赛任务
      const start = new Date((new Date(reviewStartTime.replace("%20", " "))/1000 - 86400)*1000);
      return current && current < moment(start).endOf('day') || current > moment(new Date(reviewEndTime.replace("%20", " "))).endOf('day');
    }
  }

  useEffect(()=>{
    //获取评审规则
    const params = {
      containerId,
      containerType,
      statusString: 3,
    };
    getRules(params).then(response=>{
      if(response && response.message === "success"){
        const { criteriaFive, criteriaFour, criteriaOne, criteriaThree, criteriaTwo, rule } = response.data;
        const data = { criteriaFive, criteriaFour, criteriaOne, criteriaThree, criteriaTwo, rule }
        setFieldsValue(data);
        setInitValue(response.data);
      }
    })
  }, [])

  function rulesSubmit(){
    form.validateFields((err, values) => {
      if (!err) {
        let data = {
          containerId,
          containerName: decodeURI(name),
          containerType,
          criteriaOne: values.criteriaOne,
          reviewStartOn: values.reviewDate[0].format('YYYY-MM-DD HH:mm:ss'),
          reviewEndOn: values.reviewDate[1].format('YYYY-MM-DD HH:mm:ss'),
          rule: values.rule,
          criteriaTwo: values.criteriaTwo,
          criteriaThree: values.criteriaThree,
          criteriaFour: values.criteriaFour,
          criteriaFive: values.criteriaFive,
          status: 3
        }
        containerType == 2 && (data[`containerIdentifier`]=identifier);
        if(initValue){
          //更新评审规则
          updateRules({...data, id: initValue.id}).then(response=>{
            if(response && response.message === '更新成功'){
              message.success('更新成功');
              history.go(-1);
            }else{
              message.error(response.message);
            }
          })
        }else{
          //新增评审规则
          editRules(data).then(response=>{
            if(response && response.message === '成功'){
              message.success('保存成功');
              history.go(-1);
              setInitValue({id: response.data});
            }else{
              message.error(response.message);
            }
          })
        }
        
      }
    })
  }
  
  return (
    <div className="centerbox setRules">
      <div className="head_title mb20">
        <div className="-layout pb10">
          <span className="font-16 font-w color-grey3">任务信息</span>
          <button className="but41_border goback_but" onClick={()=>{history.goBack()}}>返回上一页</button>
        </div>
        <p className="mt10"><span className="font-w color-grey3">{containerType ==1 ? '任务':'竞赛'}名称</span><span className="ml10 color-grey3">{decodeURI(name)}</span></p>
        <p className="mt10 pb20">
          <span className="font-w color-grey3">{containerType ==1 ? '任务':'竞赛'}链接</span>
          {containerType == 1 && <Link className="taskLink ml10" target="_blank" to={`/task/taskDetail/${containerId}`} >{`${window.location.origin}/task/taskDetail/${containerId}`}</Link>}
          {containerType == 2 && <a href={`${main_web_site_url}/competitions/${identifier}/home`} target="_blank" className="taskLink ml10">{`${main_web_site_url}/competitions/${identifier}/home`}</a>}
        </p>
      </div>
      <Form className="pt10">
        <Form.Item
          label="评审规则"
        >
          {getFieldDecorator('rule', {
            rules: [{ required: true, message: '请输入评审规则' }],
          })(
            <WordsInput placeholder="请输入评审规则" rows={4} maxLength='200'/>,
          )}
        </Form.Item>
        <p className="rules_bar"></p>
        <p className="font-16 criteria_title mt25 mb10"><span className="font-w">评分标准</span><span className="ml5 be_carful font-14">注：管理员可设置1-5个评分项及对应评分标准，每个评分项固定设置为100分</span></p>
        <Form.Item
          label="评分标准一"
        >
          {getFieldDecorator('criteriaOne', {
            rules: [{ required: true, message: '请输入一个评分标准' }],
          })(
            <WordsInput placeholder="请输入评分项对应的评分标准" rows={3} maxLength='100'/>,
          )}
        </Form.Item>
        <Form.Item
          label="评分标准二"
        >
          {getFieldDecorator('criteriaTwo', {
            rules: [{}],
          })(
            <WordsInput placeholder="请输入评分项对应的评分标准" rows={3} maxLength='100' />,
          )}
        </Form.Item>
        <Form.Item
          label="评分标准三"
        >
          {getFieldDecorator('criteriaThree', {
            rules: [{}],
          })(
            <WordsInput placeholder="请输入评分项对应的评分标准" rows={3} maxLength='100'/>,
          )}
        </Form.Item>
        <Form.Item
          label="评分标准四"
        >
          {getFieldDecorator('criteriaFour', {
            rules: [{}],
          })(
            <WordsInput placeholder="请输入评分项对应的评分标准" rows={3} maxLength='100'/>,
          )}
        </Form.Item>
        <Form.Item
          label="评分标准五"
        >
          {getFieldDecorator('criteriaFive', {
            rules: [{}],
          })(
            <WordsInput placeholder="请输入评分项对应的评分标准" rows={3} maxLength='100'/>,
          )}
        </Form.Item>
        <p className="rules_bar"></p>
        <Form.Item
          label="评审时间"
        >
          {getFieldDecorator('reviewDate', {
            rules: [{ required: true, message: '请选择评审时间' }],
            initialValue: initValue && [moment(initValue.reviewStartOn) , moment(initValue.reviewEndOn)]
          })(
            <RangePicker
              showTime={{ format: 'HH:mm' }}
              format="YYYY-MM-DD HH:mm"
              placeholder={['开始时间', '结束时间']}
              disabledDate={disabledDate}
            />,
          )}
        </Form.Item>
      </Form>
      <div className="rules_buttom mt20">
        <button className="but41_fill" onClick={rulesSubmit}>保存</button>
        <button className="butE3_border ml30" onClick={()=>{history.goBack()}}>取消</button>
      </div>
    </div>
    )
}
export default Form.create()(ReviewRules);