import React, { useCallback, useEffect, useState, Fragment } from 'react';
import { Breadcrumb, Button, Form, Input, Select, Upload, Cascader, Spin } from 'antd';
import { getUploadActionUrl, getUrl, appendFileSizeToUploadFileAll } from 'educoder';
import { locData } from '../../forge/Utils/locData';
import { getStudentApplyInfo, taskList, studentApply, studentApplyEdit } from '../api';
import TextArea from 'antd/lib/input/TextArea';
import { httpUrl } from '../fetch';
import banner from "../img/banner.png";
import studentSvg from "../img/student.png";
import './index.scss';
import { Link } from 'react-router-dom';

const Option = Select.Option;
const gradeList = [
  { id: '大一', name: '大一' },
  { id: '大二', name: '大二' },
  { id: '大三', name: '大三' },
  { id: '大四', name: '大四' },
  { id: '大五', name: '大五' },
  { id: '研一', name: '研一' },
  { id: '研二', name: '研二' },
  { id: '研三', name: '研三' }];
function Apply(props) {
  const { form, current_user, showNotification, match, history, setStudentInfoReset } = props;
  const taskId = Number(match.params.taskId);
  // 可用于开发时不同账号报名
  // current_user && (current_user.user_id = 6)
  // current_user && (current_user.userName = "创新使者")
  const isStudentApplyDate = new Date().getTime() > new Date('2022-05-26').getTime() && new Date().getTime() < new Date('2022-06-25').getTime();

  const { getFieldDecorator, validateFields, setFieldsValue, validateFieldsAndScroll } = form;
  const [imageUrl, setImageUrl] = useState(undefined);
  const [loading, setLoading] = useState(false);
  const [reload, setReload] = useState();
  const [userApplyInfo, setUserApplyInfo] = useState(undefined);
  const [editable, setEditable] = useState(isStudentApplyDate);
  const [files, setFiles] = useState([]);
  const [files1, setFiles1] = useState([]);
  const initTask = {
    taskId,
    memo: '',
    memoAttachmentId: ''
  };
  const [myTaskList, setMyTaskList] = useState([]);
  const [allTaskList, setAllTaskList] = useState([]);

  // 学生报名时间范围内
  // 已过学生报名时间

  useEffect(() => {
    // 进入此页面到填写页面
    // setTimeout(()=>{
    // let clientWidth = document.body.clientWidth;
    // let scrollHeight = 500 * clientWidth / 1920;
    // window.scrollTo(0, scrollHeight);
    // },200);
    window.scrollTo(0, 50);

    if (new Date().getTime() < new Date('2022-05-26').getTime()) {
      // 不在开源夏令营报名时间之内
      window.location.href = "/glcc/subjects";
    } else if (current_user && current_user.login) {

    } else {
      window.location.href = `/login?go_page=/glcc/student/apply/${taskId}`;
    }
  }, [])


  useEffect(() => {
    const params = {
      curPage: 1,
      pageSize: 10000
    }
    taskList(params).then(response => {
      if (response && response.message === "success") {
        setAllTaskList(response.data.rows);
      }
    })
  }, [])


  useEffect(() => {
    // 获取当前用户报名信息
    current_user && getStudentApplyInfo({ userId: current_user.user_id }).then(response => {
      if (response && response.message === "success" && response.data) {
        let data = response.data;
        let applyInfo = {
          grade: data.grade,
          location: data.location && data.location.split(','),
          mail: data.mail,
          phone: data.phone,
          proveAttachmentId: data.proveAttachmentId,
          school: data.school,
          studentName: data.studentName,
          userId: current_user.user_id,
          profession: data.profession,
        };

        if (Array.isArray(data.registrationStudentTaskList)) {
          if (data.registrationStudentTaskList.length) {
            let initTaskList = [];
            for (const [i, item] of data.registrationStudentTaskList.entries()) {
              applyInfo['memo' + i] = item.memo;
              applyInfo['taskId' + i] = item.taskId;
              applyInfo['memoAttachmentId' + i] = item.memoAttachmentId;

              if (i == 0) {
                item.memoAttachment && setFiles([{
                  name: item.memoAttachment && item.memoAttachment.fileName || '已上传文件',
                  id: item.memoAttachmentId,
                  uid: item.memoAttachmentId
                }]);
              } else {
                item.memoAttachment && setFiles1([{
                  name: item.memoAttachment && item.memoAttachment.fileName || '已上传文件',
                  id: item.memoAttachmentId,
                  uid: item.memoAttachmentId,
                }]);
              }

              initTaskList.push({
                id: item.id,
                memo: item.memo,
                memoAttachmentId: item.memoAttachmentId,
                taskId: item.taskId,
              });
            }
            setMyTaskList(initTaskList);

            // 如果只有一条报名数据，且课题id与当前id不一致，那么新增一条默认数据
            if (data.registrationStudentTaskList.length === 1 && data.registrationStudentTaskList[0].taskId != taskId) {
              addTask(data.registrationStudentTaskList);
            }
          } else {
            // 先增加数据再给选择框赋默认值，否则不生效
            new Promise((resove) => {
              setMyTaskList(() => {
                resove();
                return [initTask]
              });
            }).then(res => setFieldsValue({ 'taskId0': taskId }))
          }
        }

        setFieldsValue(applyInfo);
        setUserApplyInfo(response.data);
      } else {
        // 先增加数据再给选择框赋默认值，否则不生效
        new Promise((resove) => {
          setMyTaskList(() => {
            resove();
            return [initTask]
          });
        }).then(res => setFieldsValue({ 'taskId0': taskId }))
      }
    })
  }, [current_user, reload])

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

  // 学生报名夏令营
  function handleSubmit(e) {
    e.preventDefault();
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        setLoading(true);
        const params = {
          grade: values.grade,
          location: Array.isArray(values.location) && values.location.join(),
          mail: values.mail,
          phone: values.phone,
          proveAttachmentId: values.proveAttachmentId.file ? values.proveAttachmentId.file.response.id : userApplyInfo.proveAttachmentId,
          school: values.school,
          profession: values.profession,
          studentName: values.studentName,
          userId: current_user.user_id,
          registrationStudentTaskList: myTaskList
        }

        if (userApplyInfo) {
          params.id = userApplyInfo.id;
          studentApplyEdit(params).then(response => {
            if (response && response.message === "success") {
              showNotification("修改信息成功");
              setStudentInfoReset(Math.random());
              setReload(Math.random());
              setLoading(false);
              history.push(`/glcc/subjects`)
            }
          });
        } else {
          studentApply(params).then(response => {
            if (response && response.message === "success") {
              showNotification("报名成功");
              setStudentInfoReset(Math.random());
              setReload(Math.random());
              setLoading(false);
              history.push(`/glcc/subjects`)
            }
          });
        }
      }
    });
  };

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


  // 检查图片文件上传是否符合规定
  function beforeUpload(file) {
    const isLittle = file.size / 1024 / 1024 < 5;
    if (!isLittle) {
      showNotification(`文件大小必须小于${5}MB!`);
    }
    const isType = file.type === "image/png" || file.type === "image/jpg" || file.type === "image/jpeg";
    if (!isType) {
      showNotification("只能上传png、jpg、jpeg格式文件");
    }
    return isLittle && isType;
  }

  // 检查文件上传是否符合规定
  function beforeUpload2(file) {
    const isLittle = file.size / 1024 / 1024 < 5;
    if (!isLittle) {
      showNotification(`文件大小必须小于${5}MB!`);
    }
    return isLittle;
  }


  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)
      );
    }
  }

  // 自荐书上传
  function bookChange(info, i) {
    if (info.file.status === 'uploading' || info.file.status === "done" || info.file.status === 'removed') {
      // setLoading(true);
      if (info.file.status === "done") {
        changeTaskItem('memoAttachmentId', info.fileList[0].response && info.fileList[0].response.data.id, i)
      }
      if (info.file.status === 'removed') {
        changeTaskItem('memoAttachmentId', '', i);
      }
      console.log(info.fileList);
      if (i) {
        setFiles1(appendFileSizeToUploadFileAll(info.fileList).slice(-1));
      } else {
        setFiles(appendFileSizeToUploadFileAll(info.fileList).slice(-1));
      }
    }

    // if (info.file.status === "done" || info.file.status === 'removed') {
    //   setLoading(false);
    // }
  }

  // 支持文件下载
  function download(file) {
    const fileId = file.id || file.response.data.id;
    window.open(`${httpUrl}/busiAttachments/download/${fileId}`);
  }

  function addTask(List) {
    let taskListNew = List ? [...List] : [...myTaskList];
    if (taskId != taskListNew[0].taskId) {
      taskListNew.push(initTask);
      // 先增加数据再给选择框赋默认值，否则不生效
      new Promise((resove) => {
        setMyTaskList(() => {
          resove();
          return taskListNew
        });
      }).then(res => setFieldsValue({ 'taskId1': taskId }))
    } else {
      taskListNew.push({ ...initTask, taskId: '' });
      setMyTaskList(taskListNew);
    }
  }

  function deleteTask(i) {
    let taskListNew = myTaskList.slice();
    let reWriteInfo;
    if (i) {
      reWriteInfo = {
        taskId1: '',
        memo1: '',
        memoAttachmentId1: ''
      }
      setFiles1([]);
    } else {
      reWriteInfo = {
        taskId0: taskListNew[1].taskId,
        memo0: taskListNew[1].memo,
        memoAttachmentId0: taskListNew[1].memoAttachmentId,
        taskId1: '',
        memo1: '',
        memoAttachmentId1: ''
      }
      setFiles(files1);
      setFiles1([]);
    }

    taskListNew.splice(i, 1);
    setMyTaskList(taskListNew);
    setFieldsValue(reWriteInfo);
  }

  function changeTaskItem(field, val, i) {
    let taskListNew = [...myTaskList];
    taskListNew[i][field] = val;
    setMyTaskList(taskListNew);
  }

  const chooseArr = myTaskList.map(i => { return i.taskId });

  return (
    <div className="glcc_student_apply">
      {/* <img className="glcc-banner" src={banner} alt=''></img> */}
      <Spin spinning={loading}>
        <div className='apply'>
          <Breadcrumb className='glcc_breadcrumb font-16'>
            <Breadcrumb.Item><Link to="/glcc">开源夏令营</Link></Breadcrumb.Item>
            <Breadcrumb.Item><Link to="/glcc/subjects">课题及项目列表</Link></Breadcrumb.Item>
            <Breadcrumb.Item style={{ color: '#202D40' }}>学生报名</Breadcrumb.Item>
          </Breadcrumb>

          <div className="head_introduce">
            <h4 className="head_tit">申请说明：</h4>
            <div className="head_content">1、学生报名时间为<span className="head_bold">2022年5月26日-6月24日</span>，请在报名截止时间（北京时间<span className="head_bold">2022年6月24日24点</span>）前提交报名信息。</div>
            <div className="head_content">2、本次GLCC夏令营基于GitLink代码托管平台完成编程任务，若您没有平台账户，请先注册后完成课题申请</div>
            <div className="head_content">3、每位学员最多可申请2个课题，至多有且仅有1个课题可以入选</div>
            <div className="head_content">4、建议在提交课题申请，与课题导师邮件沟通，详细了解课题描述、编码任务、技能要求&编程语言、预期产出结果等信息，以便您能够选择最适合的课题</div>
            <div className="head_content">5、提交申请后，请耐心等待，我们会在2022年7月1日公布入围结果。如有任何问题，请添加开源夏令营QQ群进行咨询</div>
          </div>
          <div className="main-tit">
            <img src={studentSvg} alt='' /><span className="tit-text">学生报名</span>
          </div>
          <div className="form-content">
            <div className="form-tit">申请课题</div>
            <Form className="glcc_info_form" onSubmit={handleSubmit}>
              <h4 className="item-tit">基本信息</h4>
              {helper('学生姓名',
                '',
                'studentName',
                [{ required: true, message: "请正确输入学生姓名" },
                { max: 32, message: '超出限制长度32位字符，请重新编辑' }],
                <Input placeholder="请输入学生姓名" onBlur={() => { verify("studentName") }} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
              )}
              {helper('所在高校',
                '',
                'school',
                [{ required: true, message: "请正确输入所在高校" },
                { max: 32, message: '超出限制长度32位字符，请重新编辑' }],
                <Input placeholder="请输入所在高校" onBlur={() => { verify("school") }} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
              )}
              {helper('所学专业',
                '',
                'profession',
                [{ max: 32, message: '超出限制长度32位字符，请重新编辑' }],
                <Input placeholder="请输入所学专业" onBlur={() => { verify("profession") }} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
              )}
              <Form.Item label="地区">
                {getFieldDecorator("location", {
                  rules: []
                })(
                  <Cascader expandTrigger="hover" popupClassName="glcc_cascader" placeholder="请选择省份城市" options={locData} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
                )}
              </Form.Item>
              {helper('所在年级',
                '',
                'grade',
                [],
                <Select placeholder="请选择所在年级" disabled={editable ? false : true} className={editable ? "" : "disabledInput"} dropdownClassName="glcc_select">
                  {gradeList.map(item => { return <Option value={item.name} key={item.id}>{item.name}</Option> })}
                </Select>
              )}
              {helper('联系电话',
                '',
                'phone',
                [{ required: true, message: "请正确输入联系电话" },
                { max: 14, message: '超出限制长度14位字符，请重新编辑' },
                { pattern: /(^(\d{3,4}-)?\d{7,8})$|([1][3,4,5,6,7,8,9][0-9]{9})/, message: '请正确输入联系电话' }],
                <Input placeholder="请输入联系电话" onBlur={() => { verify("phone") }} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
              )}
              {helper('邮箱地址',
                '',
                'mail',
                [
                  { type: 'email', message: '请输入正确的邮箱地址', },
                  { required: true, message: "请输入邮箱地址" },
                  { max: 50, message: '超出限制长度50位字符，请重新编辑' },
                ],
                <Input placeholder="请输入邮箱地址" onBlur={() => { verify("mail") }} className={editable ? "" : "disabledInput"} disabled={editable ? false : true} />
              )}

              <div className='introArea update_item'>{helper('学生证明',
                '请以图片的形式上传学生证明，大小不超过5M，格式为png、jpg、jpeg',
                'proveAttachmentId',
                [{ required: true, message: "请正确上传学生证明" }],
                <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' }} /> : userApplyInfo && userApplyInfo.proveAttachmentId ?
                    <div><img src={`${getUrl()}/api/attachments/${userApplyInfo.proveAttachmentId}`} alt='' style={{ maxWidth: '100px' }} /></div> : <div>
                      <i className='iconfont icon-tianjiadaohang font-30'></i>
                      <div className="ant-upload-text font-13">请上传学生证明</div>
                    </div>}
                </Upload>
              )}</div>

              {
                myTaskList.map((item, i) => {
                  return (
                    <Fragment key={item.taskId + '' + i}>
                      <h4 className="item-tit">课题信息（<span className="item-tit-num">{i + 1}</span>/2) {myTaskList.length > 1 && <span className="delete" onClick={() => { deleteTask(i) }}><i className="iconfont icon-shanchu mr5"></i>删除</span>}</h4>
                      {helper('课题名称',
                        '',
                        'taskId' + i,
                        [{ required: true, message: "请选择课题名称" }],
                        <Select
                          placeholder="请选择课题名称"
                          dropdownClassName="glcc_select"
                          showSearch
                          disabled={editable ? false : true}
                          className={editable ? "" : "disabledInput"}
                          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1}
                          onBlur={() => { verify("taskId" + i) }}
                          onChange={(val) => { changeTaskItem("taskId", val, i) }}
                        >
                          {allTaskList.map(item => { return <Option value={item.id} disabled={chooseArr.includes(item.id)} key={item.id + ''}>{item.taskName}</Option> })}
                        </Select>
                      )}
                      <div className='introArea'>{helper('自荐书',
                        <div className="memoExtra">如何写课题申请书：<a href="https://forum.gitlink.org.cn/forums/7299/detail" target="_black">https://forum.gitlink.org.cn/forums/7299/detail</a></div>,
                        'memo' + i,
                        [{ required: true, message: "请正确输入自荐书" },
                        { max: 500, message: '超出限制长度500位字符，请重新编辑' }],
                        <TextArea placeholder="自荐书可按如下结构填写：
                        1、申请书概要：说重点让导师打起精神看下去；
                        2、社区的贡献：告诉社区你能为他们做哪些贡献；
                        3、课题实施方案：详细阐述对课题的理解，如果有技术架构图更好；
                        4、课题实施规划：课题实施拆解、工作规划以及时间安排；
                        5、个人简介：编程技能、过往经验；
                        6、提示：文本框表达内容有限，建议您提供内容的pdf或url链接方式展示更精彩的陈述"
                          onBlur={(e) => { verify("memo" + i); changeTaskItem("memo", e.currentTarget.value, i) }} rows={7} className={editable ? "memoText" : "memoText disabledInput"} />
                      )}</div>

                      <div className='introArea'>{helper('附件',
                        '可以上传自荐书文件，大小不超过5M',
                        'memoAttachmentId' + i,
                        [],
                        <Upload
                          // action={getUploadActionUrl()}
                          action={httpUrl + `/busiAttachments/upload`}
                          fileList={i ? files1 : files}
                          onChange={(info) => { bookChange(info, i) }}
                          onDownload={download}
                          beforeUpload={beforeUpload2}
                          showUploadList={{
                            showDownloadIcon: true,
                            downloadIcon: <i className="iconfont icon-xiazai-icon"></i>,
                            showRemoveIcon: true
                          }}
                        >
                          <div className="glcc_btn">上传自荐书</div>
                        </Upload>
                      )}</div>
                    </Fragment>
                  )
                })
              }

              {
                myTaskList.length < 2 && <Button className="add_task" type="primary" onClick={() => { addTask() }}>添加课题</Button>
              }

              <Form.Item className='subInfo introArea'>
                <Button type="primary" htmlType="submit" className='sub' disabled={!editable}>提交</Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </Spin>
    </div>
  )
}
export default Form.create()(Apply);