Html.js 6.55 KB
import React, { useState, useEffect } from 'react';
import { Modal, Upload, message, Form, InputNumber, Button , Select ,Row, Col} from 'antd';
import { InboxOutlined, LockOutlined, SaveTwoTone } from '@ant-design/icons';
import { saveFileAndQno } from 'lib/api/html';
import { checkQno } from '../lib/api/html';

const { Option} = Select;
//파일 업로드
//업로드 폼에서의 로직

const fetchSaveData = async (data) => {
  try{
    console.log(data);
    const result = await saveFileAndQno(data);
    if(result.status===200){
      return result.data;
    }    
  }catch(e){
    console.log(e);
    message.warn(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 Html = ({ 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:'.html',
    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('.jpg')>0) || (file.name.indexOf('.png')>0) )
      {
        setFileList([file]);
      }else {
        setFileList([]);
        message.info("그림 형식의 파일이 아닙니다.");
      }
      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('html', values.html[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:['html'],value:fileList},...fields]}
      >
        <Form.Item
          name="qno"
          label="그림 번호"
          rules={[
            {
              required: true,
              message: '저장할 그림의 문항번호를 입력해 주세요.',
            },
          ]}>
          <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: '저장할 그림의 타입을 선택해 주세요.',
            },
          ]}>
          <Select onChange={onChangeTypeSol}>
             <Option value="JPEG">JPEG</Option>
             <Option value="PNG">PNG</Option>

          </Select>
        </Form.Item>

        <Form.Item label="파일 업로드">
        <Form.Item 
          name="html" 
          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 style={{alignContent:'middle'}} wrapperCol={{ span: 12, offset: 6 }}>
        <Button type="primary" htmlType="submit">
          저장
        </Button>
      </Form.Item>
      </Form>
     
    </Modal>
  );
};

export default Html;