import React , { useCallback, useEffect , useState } from 'react';
import { Breadcrumb, Button, Form, Input, Select, Upload, Modal } from 'antd';
import {getUploadActionUrl} from 'educoder';
import {getUserApplyInfo, applyGlcc} from '../api';
import axios from 'axios';
import TextArea from 'antd/lib/input/TextArea';
import { main_site_url } from '../fetch';
import banner from "../img/banner.png";
import './index.scss';
const Option = Select.Option;
function Apply(props) {
  const {form, current_user, showNotification, isGlccApplyDate} = props;
  // 可用于开发时不同账号报名
  // current_user && (current_user.user_id = 6)
  // current_user && (current_user.userName = "创新使者")
  const {getFieldDecorator, validateFields, setFieldsValue, validateFieldsAndScroll } = form;
  const [reload, setReload] = useState(undefined);
  const [imageUrl, setImageUrl] = useState(undefined);
  const [loading, setLoading] = useState(false);
  const [cateList, setCateList] = useState([]);
  const [userApplyInfo, setUserApplyInfo] = useState(undefined);

  const helper = useCallback(
    (label, extra, name, rules, widget) => (
      <Form.Item label={label} extra={extra}>
        {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
      </Form.Item>
    ),
    []
  );

  useEffect(()=>{
    // 进入此页面置顶
    window.scrollTo(0,0);
    if(!isGlccApplyDate){
      // 不在开源夏令营报名时间之内
      window.location.href="/glcc";
    }else if(current_user && current_user.login){
      // 获取项目分类参数
      const url = `/project_categories/pinned_index.json`;
      axios.get(url).then(result=>{
        if(result && result.data){
          setCateList(result.data.project_categories);
        }
      }).catch(error=>{})
    }else{
      window.location.href="/login?go_page=/glcc/apply";
    }
  }, [])

  useEffect(()=>{
    // 获取当前用户报名信息
    current_user && getUserApplyInfo({userId: current_user.user_id}).then(response=>{
      if(response && response.message === "success"){
        response.data && setFieldsValue({
          ...response.data
        })
        setUserApplyInfo(response.data);
      }
    })
  }, [reload])

  // 当用户输入结束时 检验用户输入是否符合规范
  function verify(dataIndex){
    validateFields([dataIndex],(error, values)=>{
      if(error && error[dataIndex]){
        return;
      }
    })
  }

  // 报名夏令营
  function handleSubmit(e){
    e.preventDefault();
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        Modal.confirm({
          title: "报名",
          content: "确定提交报名信息，提交后报名信息将无法修改",
          onOk: ()=>{
            const params ={
              ...values,
              projectLogoId: values.logo.file.response.id,
              userId: current_user.user_id,
              userName: current_user.username
            }
            applyGlcc(params).then(response=>{
              if(response && response.message === "success"){
                showNotification("报名成功");
                setReload(Math.random());
              }
            })
          }
        })}
    });
  };

  // 检查文件上传是否符合规定
  function beforeUpload(file){
    const isLt100M = file.size / 1024 / 1024 < 2;
    if (!isLt100M) {
      showNotification(`文件大小必须小于${2}MB!`);
    }
    const isType = file.type === "image/png" || file.type === "image/jpg" || file.type === "image/jpeg";
    if (!isType) {
      showNotification("只能上传png、jpg、jpeg格式文件");
    }
    return isLt100M && isType;
  }
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
    reader.onload = function(e) {
      setImageUrl(e.target.result);  // 上传的图片的编码
    }
  }

  // 上传完成后
  function handleChange(info){
    if(info && info.file && info.file.status === "done"){
      getBase64(info.file.originFileObj, imageUrl =>
        setImageUrl(imageUrl)
      );
    }
  }
  return(
    <div className="glcc_apply">
      <img className="glcc-banner" src={banner} alt=''></img>
      <div className='apply'>
        <Breadcrumb className='pt20 font-16'>
          <Breadcrumb.Item><a href="/glcc">开源夏令营</a></Breadcrumb.Item>
          <Breadcrumb.Item>项目报名</Breadcrumb.Item>
        </Breadcrumb>
        {userApplyInfo && <div className='applySuccess mt20 font-15'>
          <i className='iconfont icon-wancheng mr5'></i>您已报名成功，请关注活动后续新闻公告!
        </div>}
        <Form className="pt20 glcc_info_form" onSubmit={handleSubmit}>
          {helper('项目名称',
            '',
            'projectName',
            [{ required: true, message: "请正确输入项目名称" },
            { max: 32, message: '超出限制长度32位字符，请重新编辑' }],
            <Input placeholder="请输入项目名称" onBlur={()=>{verify("name")}} disabled = {userApplyInfo ? true : false} className={userApplyInfo? "disabledInput":""}/>
          )}
          {helper('项目分类',
            '',
            'projectType',
            [],
            <Select placeholder="请选择项目分类" disabled = {userApplyInfo ? true : false} className={userApplyInfo? "disabledInput":""}>
              {cateList && cateList.map(item=> {return <Option value={item.name} key={item.id}>{item.name}</Option>})}
            </Select>
          )}
          {helper('GitLink项目地址',
            '',
            'gitlinkUrl',
            [{ required: true, message: "请正确输入预申报项目在GitLink平台的地址" },
            { max: 252, message: '超出限制长度252位字符，请重新编辑' }],
            <Input placeholder="请输入预申报项目在GitLink平台的地址" onBlur={()=>{verify("gitlink")}} disabled = {userApplyInfo ? true : false} className={userApplyInfo? "disabledInput":""}/>
          )}
          {helper('官网地址',
            '',
            'officialWebsiteUrl',
            [{ max: 252, message: '超出限制长度252位字符，请重新编辑' }],
            <Input placeholder="请输入官网地址" disabled = {userApplyInfo ? true : false} className={userApplyInfo? "disabledInput":""}/>
          )}
          <div className='introArea'>{helper('项目简介',
            '',
            'projectIntro',
            [{ required: true, message: "请正确输入项目简介" },
            { max: 200, message: '超出限制长度200位字符，请重新编辑' }],
            <TextArea placeholder="请输入项目简介，长度不超过200字符" onBlur={()=>{verify("intro")}} rows={4} disabled = {userApplyInfo ? true : false} className={userApplyInfo? "disabledInput":""}/>
          )}</div>
          <div className='introArea'>{helper('项目logo',
            'logo格式为png、jpg、jpeg，限制上传大小2m，建议上传尺寸为382*228',
            'logo',
            [{ required: true, message: "请正确上传项目logo" }],
            userApplyInfo && userApplyInfo.projectLogoId ? <div className='projectLogo'><img src={`${main_site_url}/api/attachments/${userApplyInfo.projectLogoId}`} alt=''/></div>
            :<Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={getUploadActionUrl()}
              accept=".png,.jpg,.jpeg"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ maxWidth: '100px', maxHeight: '100px' }} /> : <div>
                <i className='iconfont icon-tianjiadaohang font-30'></i>
                <div className="ant-upload-text font-13">请上传logo图片</div>
              </div>}
            </Upload>
          )}</div>
          <p className='introArea tips'>注: 课题及导师信息请在GitLink项目中以issue的形式编辑</p>
          {!userApplyInfo && <Form.Item className='subInfo introArea'>
            <Button type="primary" htmlType="submit" className='sub'>提交</Button>
          </Form.Item>}
        </Form>
        <div className={`explain ${userApplyInfo ? "mt70" : ""}`}>
          <p className='font-15 c000'>申请说明</p>
          <div>1、项目报名时间为<span className='c000'>4月15日—5月20日</span>，请在报名截止时间（北京时间<span className='c000'>2022年5月20日24点</span>）前提交报名信息。</div>
          <div>2、本次夏令营使用Gitlink为代码托管平台，学员基于Gitlink上项目数量完成课程任务。如果您的项目还未在Gitlink中，请现将项目迁移到Gitlink，迁移事项请查看<a href='https://forum.gitlink.org.cn/forums/7296/detail' target="_blank" className='link'>迁移说明文档</a>。如在迁移过程中遇到问题，请加qq群: 1071514693  联系qq群管理员。</div>
          <div>3、提交社区和项目信息后，欢迎与组委会联系沟通本次编程夏令营宣传推广和后续合作工作。联系人: _TigerWang（微信号，添加请备注Gitlink编程夏令营）</div>
        </div>
      </div>
    </div>
  )
}
export default Form.create()(Apply);