Mathcha.js 6.91 KB
import React, { useState, useEffect } from 'react';
import { Upload, message,Form, InputNumber, Button, Select, Modal,Row,Col} from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import {saveFileAndQno,getMathData} from 'lib/api/mathCha';
import {checkQno} from '../lib/api/mathCha';

const {Option} =Select;

const fetchSaveData = async (data) => {
  try{
    const result = await saveFileAndQno(data);
    console.log(result);
    if(result.status===200){
      return result.data;
    }    
  }catch(e){
    console.log(e);
    message.warning(e.message);
  }
}

const fetchCheckQno = async(qno) => {
  try{
    const result = await checkQno(qno);
    if(result.status===200){
      console.log(result);
      message.info("사용 가능한 문항 번호 입니다.");
      return true;
    }else{ 
      message.info("존재 하지 않는 문항 번호 입니다.");
      return false;
    }
  }catch(e){
    console.log(e);
    message.info("존재 하지 않는 문항 번호 입니다.");
    return false;
  }
}
const Mathcha = ({ visible, onCancel, callback }) => {
  const [fields,setFields] =useState([]);
  const [qno, setQno] = useState(null);
  const [upload,setUpload]=useState(false);
  const [fileList, setFileList]=useState([]);
  const [qnoCheck,setQnoCheck] = useState(false);

  const changeNumber = (value) => {
      setQno(value);
      setFields([...fields, {name:['qno'],value:value}]);
  };

  useEffect(()=>{
    if(!visible){
      let initFields = [
        {name:['qno'],value:null},
        {name:['typeSol'],value:null},
        {name:['typeQue'],value:null},
        {name:['creator'],value:null},
      ];
      setQno(null);
      setFields(initFields);
      setFileList([]);
    }
  },[visible]);

  const props = {
    multiple:false,
    //data: { qno: qno },
    accept:'.mathcha',
    onRemove: file => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        return {
          fileList: newFileList,
        };
    },

    beforeUpload: file => {
      console.log(file);
      if(file.name.indexOf('.mathcha')>0)
      {
        setFileList([file]);
      }else {
        setFileList([]);
        message.info("MathCha 형식의 파일이 아닙니다.");
      }
      return false;
          
    },
   };

   const onOk = () => {
     setUpload(true)
   };
  

   const normFile = e => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const onClickQno = async(e)=>{
    e.preventDefault();
    //번호가 호출 성공시 setQnoCheck(true);
    if(qno){
      const _checkQno= await fetchCheckQno(qno);
      setQnoCheck(_checkQno);
    }
  };

  const onFinish = async values => {
    console.log(qnoCheck);
    if(!qnoCheck){
      message.warning("문제 번호를 확인해 주세요.")
      return;
    }else{
    const creator = sessionStorage.getItem('id');
    console.log('Received values of form: ', values);
    const formData = new FormData();
    formData.append('qno', values.qno);
    formData.append('typeSol', values.typeSol);
    formData.append('typeQue', values.typeQue);
    formData.append('math', values.math[0]);
    formData.append('creator', creator);
  
    const result = await fetchSaveData(formData);
    console.log(result);
    if(result){
      message.info(result.message);
      let initFields = [
        {name:['qno'],value:null},
        {name:['typeSol'],value:null},
        {name:['typeQue'],value:null},
        {name:['creator'],value:null},
      ];
      setQno(null);
      setFields(initFields);
      setFileList([]);
      onCancel();
      callback({status:'SAVE_OK'});
    }else{
      callback({status:'SAVE_FAIL'})
     }
    }
  };

  const onChangeTypeSol = (value) => {
    console.log(value);
    setFields([...fields, {name:['typeSol'],value:value}]);
  }

  const onChangeTypeQue = (value) => {
    console.log(value);
    setFields([...fields, {name:['typeQue'],value:value}])
  }


   
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  return (
    <Modal
      placement={'bottom'}
      closable={true}
      height={'75%'}
      visible={visible}
      okText={'저장'}
      cancelText={'이전'}
      onCancel={onCancel}
      footer={null}
     >
      <Form  name="validate_other"
      {...formItemLayout}
      onFinish={onFinish}
      fields={[{name:['math'],value:fileList},...fields]}
      >
        <Form.Item
          name="qno"
          label="문제 번호"
          rules={[
            {
              required: true,
              message: '저장할 html의 파일의 문항번호를 입력해 주세요.',
            },
          ]}><Row>
          <Col>
            <InputNumber
              min={0}
              max={10000}
              value={qno}
              onChange={changeNumber}>
            </InputNumber>
          </Col>
          <Col>
            <Button onClick={onClickQno}>번호 확인</Button>
          </Col>
        </Row>
        </Form.Item>
        <Form.Item
          name="typeSol"
          label="문제 타입"
          rules={[
            {
              required: true,
              message: '저장할 html의 문제 타입을 선택해 주세요.',
            },
          ]}>
          <Select onChange={onChangeTypeSol}>
             <Option value="오지선다형">오지선다형</Option>
             <Option value="단답형">단답형</Option>
             <Option value="계산식">계산식</Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="typeQue"
          label="문제/풀이 구분"
          rules={[
            {
              required: true,
              message: '저장할 html의 문제/풀이 구분을 선택해 주세요.',
            },
          ]}>
          <Select onChange={onChangeTypeQue}>
             <Option value="문제">문제</Option>
             <Option value="풀이">풀이</Option>
          </Select>
        </Form.Item>
        <Form.Item label="파일 업로드">
        <Form.Item 
          name="math" 
          valuePropName="fileList" 
          getValueFromEvent={normFile} 
    
          noStyle   
          rules={[
            {
              required: true,
              message: '파일을 드래그하거나 선택해 주세요.',
            },
          ]}>
          <Upload.Dragger name="files" {...props} >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">Click or drag file to this area to upload</p>
            <p className="ant-upload-hint">Support for a single or bulk upload.</p>
          </Upload.Dragger>
        </Form.Item>
      </Form.Item>

      <Form.Item wrapperCol={{ span: 12, offset: 6 }}>
        <Button type="primary" htmlType="submit">
          저장
        </Button>
      </Form.Item>
      </Form>
     
    </Modal>
  );
};


export default Mathcha;