package egovframework.controller;

import egovframework.service.impl.AdminServiceImpl;
import egovframework.service.impl.NoticeServiceImpl;
import egovframework.utill.CommonPath;
import egovframework.utill.PageCriteria;
import egovframework.utill.PageMaker;
import egovframework.utill.SHA256;
import egovframework.vo.NoticeVO;
import egovframework.vo.PopupVO;
import egovframework.vo.StatsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RequiredArgsConstructor
@Controller
public class AdminController {

    private final AdminServiceImpl adminService;
    private final NoticeServiceImpl adminNoticeService;
    private final String ATTATCH_FILE_PATH = CommonPath.getFilePath();
    private final String IMAGE_FILE_PATH = CommonPath.getImageUploadPath();
    private PageCriteria criteria;

    @PostConstruct
    void init() {
        this.criteria = new PageCriteria();
    }

    @RequestMapping(value = "/admin/index.do", method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("siteSubInfo", "sub admin");
        //String requestUri = request.getRequestURI();
        //String requestAction = requestUri.substring(requestUri.lastIndexOf("/") + 1);
        if (request.getSession().getAttribute("userId") != null) {
            return "redirect:/admin/noticeList.do";
        }

        //return "admin/indexNew.tiles";
        return "admin/index.tiles";
    }

    @ResponseBody
    @RequestMapping(value = "/admin/login.do", method = RequestMethod.POST,	produces = {"application/json; charset=utf8"})
    public Map<String,Object> login(Model model, @RequestBody Map<String,Object> paramMap, HttpSession session){
        model.addAttribute("siteSubInfo", "sub admin");
        log.error("paramMap : {}", paramMap);
        Map<String, Object> resultMap = adminService.loginCheck(paramMap, session);
        return resultMap;
    }

    @RequestMapping(value = "/admin/logout.do", method = RequestMethod.GET)
    public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("siteSubInfo", "sub admin");
        HttpSession session = request.getSession(false);
        if (session.getAttribute("userId") != null) {
            this.adminService.adminLogoutMake(null);
            request.getSession().removeAttribute("userId");
        }
        return "redirect:/admin/index.do";
    }

    @RequestMapping(value = "/admin/modiAdmin.do", method = RequestMethod.GET)
    public String pwChange(Model model, HttpServletRequest request) {
        model.addAttribute("siteSubInfo", "sub admin");
        model.addAttribute("id", request.getSession().getAttribute("userId"));
        return "admin/modiAdminNew.tiles";
    }

    @RequestMapping(value = "/admin/popupList.do", method = RequestMethod.GET)
    public String popup(Model model) {
        model.addAttribute("siteSubInfo", "sub admin");
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
        Date currentTime = new Date();
        String mTime = mSimpleDateFormat.format(currentTime);
        List<PopupVO> popupList = this.adminService.getPopupList(null);

        SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        for (PopupVO vo : popupList) {
            Date date;
            try {
                date = transFormat.parse(vo.getRegDate());
                vo.setRegDate(format.format(date));
                date = transFormat.parse(vo.getPost_from());
                vo.setPost_from(format2.format(date));
                date = transFormat.parse(vo.getPost_to());
                vo.setPost_to(format2.format(date));
            } catch (ParseException e) {
                log.error("/admin/popupList.do, can not transFormat Date Data...");
            }
        }

        model.addAttribute("popupList", popupList);
        model.addAttribute("mTime", mTime);

        return "admin/popupListNew.tiles";
    }


    @RequestMapping(value = "/admin/noticeList.do", method = RequestMethod.GET)
    public String noticeList(Model model, @RequestParam HashMap<String, String> paramMap) {
        if (paramMap.get("page") != null) {
            this.criteria.setPage(Integer.parseInt(paramMap.get("page")));
        } else {
            this.criteria.setPage(1);
        }

        model.addAttribute("siteSubInfo", "sub admin");

        String searchText = paramMap.get("searchText");
        if (searchText != null) {
            this.criteria.setSearchType(paramMap.get("searchType"));
            this.criteria.setSearchText(searchText);
        } else {
            this.criteria.setSearchText("");
        }

        PageMaker pageMaker = new PageMaker();
        pageMaker.setCriteria(this.criteria);
        pageMaker.setTotalCount(this.adminNoticeService.getNoticeTotalCount(paramMap));
        List<NoticeVO> noticeList = this.adminNoticeService.getNoticeList(this.criteria);
        SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (NoticeVO vo : noticeList) {
            try {
                Date date = transFormat.parse(vo.getRegDate());
                vo.setRegDate(format.format(date));
                log.error("bSubject{}", vo.getbSubject());
            } catch (ParseException e) {
                log.error("/admin/noticeList.do, date format Exception...");
            }
        }
        model.addAttribute("noticeList", noticeList);
        model.addAttribute("pageMaker", pageMaker);
        return "admin/noticeListNew.tiles";
    }

    @RequestMapping(value = "/admin/noticeView.do", method = RequestMethod.GET)
    public String view(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, String> paramMap) {

        model.addAttribute("siteSubInfo", "sub admin");

        this.adminNoticeService.updateNoticeReadCount(paramMap);

        NoticeVO result = this.adminNoticeService.getNotice(paramMap);

        if (result.getAttachFile() != null) {
            String attatchFile = result.getAttachFile();
            String[] fileArr = attatchFile.split("[|]", -1);
            List<String> attatchFiles = new ArrayList<>();
            if (fileArr.length > 0) {
                for (String file : fileArr) {
                    if (!file.isEmpty()) {
                        attatchFiles.add(file);
                    }
                }
            }
            result.setAttatchFiles(attatchFiles);
        }

        if (result.getAttachFileId() != null) {
            String attatchFileId = result.getAttachFileId();
            String[] idArr = attatchFileId.split("[|]", -1);
            List<String> attatchFileIds = new ArrayList<>();
            if (idArr.length > 0) {
                for (String id : idArr) {
                    if (!id.isEmpty()) {
                        attatchFileIds.add(id);
                    }
                }
            }
            result.setAttatchFileIds(attatchFileIds);
        }

        SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date = transFormat.parse(result.getRegDate());
            result.setRegDate(format.format(date));
        } catch (ParseException e) {
            log.error("/admin/noticeView.do date format Exception...");
        }
        model.addAttribute("notice", result);

        return "admin/noticeViewNew.tiles";
    }

    @RequestMapping(value = "/admin/noticeWrite.do", method = RequestMethod.GET)
    public String write(Model model) {
        model.addAttribute("siteSubInfo", "sub admin");
        return "admin/noticeWriteNew.tiles";
    }

    @RequestMapping(value = "/admin/insertNotice.do", method = RequestMethod.POST)
    public String insertNotice(Model model, HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("attachFile1") MultipartFile file1,
                               @RequestParam("attachFile2") MultipartFile file2,
                               @RequestParam("attachFile3") MultipartFile file3) {
        MultipartFile[] fileArr = new MultipartFile[]{file1, file2, file2};
        File uploadFileHome = new File(ATTATCH_FILE_PATH);

        uploadFileHome.setExecutable(false, true);
        uploadFileHome.setReadable(true);
        uploadFileHome.setWritable(false, true);
        if (!uploadFileHome.exists()) {
            uploadFileHome.mkdir();
        }

        String fileNames = file1.getOriginalFilename() + "|" + file2.getOriginalFilename() + "|" + file3.getOriginalFilename();
        String fileIds = "";

        for (MultipartFile file : fileArr) {
            if (!"".equals(file.getOriginalFilename())) {
                try {
                    if (file.getSize() <= 200000000) {
                        String fileUuid = UUID.randomUUID().toString().replace("-", "");
                        File uploadFile = new File(uploadFileHome, fileUuid);
                        file.transferTo(uploadFile);
                        fileIds += fileUuid;
                    } else {
                        log.error("/admin/insertNotice.do, {} is Too Large Size(Limit Size 200000000)", file.getOriginalFilename());
                    }
                } catch (IllegalStateException | IOException e) {
                    log.error("/admin/insertNotice.do, can not upload {}", file.getOriginalFilename());
                }
            }
            fileIds += "|";
        }
        fileIds = fileIds.substring(0, fileIds.length() - 1);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        HttpSession session = request.getSession();
        paramMap.put("categoryCd", "N");
        paramMap.put("bSubject", request.getParameter("subject"));
        paramMap.put("bContent", request.getParameter("content"));
        paramMap.put("webUserId", session.getAttribute("userId"));
        paramMap.put("attachFile", fileNames);
        paramMap.put("ATTACHFILEID", fileIds);
        paramMap.put("bNotice", (request.getParameter("notice") == null) ? "N" : "Y");

        this.adminService.insertNotice(paramMap);

        return "redirect:/admin/noticeList.do";

    }

    @RequestMapping(value = "/admin/deleteNotice.do", method = RequestMethod.GET)
    public String noticeDelete(Model model, @RequestParam HashMap<String, Object> paramMap) {
        this.adminService.deleteNotice(paramMap);
        return "redirect:/admin/noticeList.do";
    }

    @RequestMapping(value = "/admin/editNotice.do", method = RequestMethod.GET)
    public String noticeEdit(Model model, @RequestParam HashMap<String, String> paramMap) {
        model.addAttribute("siteSubInfo", "sub admin");
        NoticeVO resultList = this.adminNoticeService.getNotice(paramMap);
        if (!"||".equals(resultList.getAttachFile())) {
            String attachfile = resultList.getAttachFile();
            String[] attachfileArr = attachfile.split("[|]", -1);

            resultList.setAttachfile1(attachfileArr[0]);
            resultList.setAttachfile2(attachfileArr[1]);
            resultList.setAttachfile3(attachfileArr[2]);
        }

        model.addAttribute("noticeEdit", resultList);

        return "admin/noticeEditNew.tiles";
    }

    @RequestMapping(value = "/admin/updateNotice.do", method = RequestMethod.POST)
    public String updateNotice(Model model, HttpServletRequest request, HttpServletResponse response,
                               @RequestParam HashMap<String, String> param,
                               @RequestParam("attachFile1") MultipartFile file1,
                               @RequestParam("attachFile2") MultipartFile file2,
                               @RequestParam("attachFile3") MultipartFile file3) {
        model.addAttribute("siteSubInfo", "sub admin");
        MultipartFile[] fileArr = new MultipartFile[]{file1, file2, file3};
        NoticeVO vo = this.adminNoticeService.getNotice(param);
        String[] orginAttatch = new String[]{};
        String[] orginAttatId = new String[]{};

        if (vo.getAttachFile() != null) {
            orginAttatch = vo.getAttachFile().split("\\|");
        }
        if (vo.getAttachFileId() != null) {
            orginAttatId = vo.getAttachFileId().split("\\|");
        }

        String file1Name = request.getParameter("attachFile1Name");
        String file2Name = request.getParameter("attachFile2Name");
        String file3Name = request.getParameter("attachFile3Name");
        String[] fileNameArr = new String[]{file1Name, file2Name, file3Name};

        File uploadFile;
        File uploadFileHome = new File(ATTATCH_FILE_PATH);
        uploadFileHome.setExecutable(false, true);
        uploadFileHome.setReadable(true);
        uploadFileHome.setWritable(false, true);

        if (!uploadFileHome.exists()) {
            uploadFileHome.mkdir();
        }

        String fileNames = file1Name + "|" + file2Name + "|" + file3Name;
        String fileIds = "";

        for (int ii = 0; ii < fileArr.length; ii++) {
            MultipartFile file = fileArr[ii];
            if (!"".equals(file.getOriginalFilename())) {
                try {
                    if (file.getSize() <= 200000000) {
                        String fileUuid = UUID.randomUUID().toString().replace("-", "");
                        uploadFile = new File(uploadFileHome, fileUuid);
                        file.transferTo(uploadFile);
                        fileIds += fileUuid;
                    } else {
                        log.error("/admin/updateNotice.do, {} is Too Large Size(Limit Size 200000000)", file.getOriginalFilename());
                    }
                } catch (IllegalStateException | IOException e) {
                    log.error("/admin/updateNotice.do, can not upload {}", file.getOriginalFilename());
                }
            }
            else {
                if (orginAttatch.length > ii && fileNameArr.length > ii) {
                    if (!orginAttatch[ii].isEmpty() && !fileNameArr[ii].isEmpty()) {
                        if (orginAttatch[ii].equals(fileNameArr[ii])) {
                            fileIds += orginAttatId[ii];
                        }
                    }
                }
            }
            fileIds += "|";
        }

        fileIds = fileIds.substring(0, fileIds.length() - 1);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("boardNo", request.getParameter("boardNo"));
        paramMap.put("bSubject", request.getParameter("subject"));
        paramMap.put("bContent", request.getParameter("content"));
        paramMap.put("attachFile", fileNames);
        paramMap.put("ATTACHFILEID", fileIds);
        paramMap.put("bNotice", (request.getParameter("notice") == null) ? "N" : "Y");
        this.adminService.updateNotice(paramMap);
        model.addAttribute("boardNo", request.getParameter("boardNo"));
        return "redirect:/admin/noticeView.do";
    }


    @RequestMapping(value = "/admin/editPopup.do", method = RequestMethod.POST)
    public String editPopup(Model model, @RequestParam Map<String, Object> paramMap) {
        model.addAttribute("siteSubInfo", "sub admin");
        List<PopupVO> popup = this.adminService.getPopupList(paramMap);
        popup.get(0).setPost_from(popup.get(0).getPost_from().substring(0, 10));
        popup.get(0).setPost_to(popup.get(0).getPost_to().substring(0, 10));
        model.addAttribute("popup", popup.get(0));
        return "admin/editPopupNew.tiles";
    }

    @RequestMapping(value = "/admin/popupInsert.do", method = RequestMethod.POST)
    public String popupInsert(Model model, HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("popupImg") MultipartFile file,
                              @RequestParam Map<String, Object> paramMap) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("/admin/popupInsert.do request can not characterEncoding utf-8...");
        }

        File uploadFileHome = new File(IMAGE_FILE_PATH);
        uploadFileHome.setExecutable(false, true);
        uploadFileHome.setReadable(true);
        uploadFileHome.setWritable(false, true);

        if (!uploadFileHome.exists()) {
            uploadFileHome.mkdir();
        }

        String fileName;
        String fileUuid;

        fileName = file.getOriginalFilename();
        String fileExe = fileName.substring(fileName.lastIndexOf("."));
        fileUuid = UUID.randomUUID().toString().replace("-", "") + fileExe;
        File uploadImgFile = new File(uploadFileHome, fileUuid);
        try {
            if (file.getSize() <= 200000000) {
                file.transferTo(uploadImgFile);
            } else {
                log.error("/admin/popupInsert.do, PopupImage is Too Large Size(Limit Size 200000000)");
            }
        } catch (IllegalStateException | IOException e) {
            log.error("/admin/popupInsert.do, can not transfer To uploadImgFile...");
        }

        paramMap.put("postFrom", paramMap.get("postFrom").toString().replace("-", ""));
        paramMap.put("postTo", paramMap.get("postTo").toString().replace("-", ""));
        paramMap.put("imgId", fileUuid);
        paramMap.put("imgName", fileName);

        BufferedImage bi;
        try {
            bi = ImageIO.read(uploadImgFile);
            if (bi != null) {
                paramMap.put("popImgWidth", bi.getWidth());
                paramMap.put("popImgHeight", bi.getHeight());
            }
        } catch (IOException e) {
            log.error("/admin/popupInsert.do, can not read ImageIO...");
        }

        this.adminService.insertPopup(paramMap);

        return "redirect:/admin/popupList.do";
    }

    @RequestMapping(value = "/admin/updatePopupUseYN.do", method = RequestMethod.POST)
    public String updatePopupUseYN(Model model, @RequestParam Map<String, Object> paramMap) {
        this.adminService.updatePopupUseYN(paramMap);
        return "redirect:/admin/popupList.do";
    }

    @RequestMapping(value = "/admin/deletePopup.do", method = RequestMethod.POST)
    public String removePopup(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
        List<PopupVO> listVo = this.adminService.getPopupList(paramMap);
        String imgFileName = listVo.get(0).getImg_id();

        String imguploadPath = IMAGE_FILE_PATH;
        File tempImgFile = new File(imguploadPath, imgFileName);
        tempImgFile.setExecutable(false, true);
        tempImgFile.setReadable(true);
        tempImgFile.setWritable(false, true);
        log.error("tempImgFile : {}",tempImgFile);
        if (tempImgFile.exists()) {
            tempImgFile.delete();
        }

        this.adminService.deletePopup(paramMap);

        return "redirect:/admin/popupList.do";

    }

    @RequestMapping(value = "/admin/updatePopup.do", method = RequestMethod.POST)
    public String updatePopup(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap,
                              @RequestParam("popupImg") MultipartFile file) {
        List<PopupVO> popup = this.adminService.getPopupList(paramMap);
        PopupVO vo = popup.get(0);
        if (vo.getImg_name().equals(paramMap.get("img_name"))) {
            paramMap.put("imgId", vo.getImg_id());
            paramMap.put("imgName", vo.getImg_name());
        } else {
            File uploadFileHome = new File(IMAGE_FILE_PATH);
            uploadFileHome.setExecutable(false, true);
            uploadFileHome.setReadable(true);
            uploadFileHome.setWritable(false, true);

            if (!uploadFileHome.exists()) {
                uploadFileHome.mkdir();
            }
            String fileName;
            String fileUuid = "";

            fileName = file.getOriginalFilename();
            BufferedImage bi = null;

            if (!"".equals(fileName)) {
                List<PopupVO> popupList = this.adminService.getPopupList(paramMap);
                File tempImgFile = new File(uploadFileHome, popupList.get(0).getImg_id());

                if (tempImgFile.exists()) {
                    tempImgFile.delete();
                }

                String fileExe = fileName.substring(fileName.lastIndexOf("."));
                fileUuid = UUID.randomUUID().toString().replace("-", "") + fileExe;
                File uploadImgFile = new File(uploadFileHome, fileUuid);
                try {
                    if (file.getSize() <= 200000000) {
                        file.transferTo(uploadImgFile);
                    } else {
                        log.error("/admin/updatePopup.do, PopupImage is Too Large Size(Limit Size 200000000)");
                    }
                } catch (IllegalStateException | IOException e) {
                    log.error("/admin/updatePopup.do, can not transfetTo uploadImgFile...");
                }

                try {
                    bi = ImageIO.read(uploadImgFile);
                } catch (IOException e) {
                    log.error("/admin/popupInsert.do, can not read ImageIO...");
                }
            }

            paramMap.put("imgId", fileUuid);
            paramMap.put("imgName", fileName);

            if (bi != null) {
                paramMap.put("popImgWidth", bi.getWidth());
                paramMap.put("popImgHeight", bi.getHeight());
            } else {
                paramMap.put("popImgWidth", "250");
                paramMap.put("popImgHeight", "250");
            }
        }

        this.adminService.updatePopup(paramMap);

        return "redirect:/admin/popupList.do";
    }

    @ResponseBody
    @RequestMapping(value = "/admin/checkPrePw.do", method = RequestMethod.POST)
    public Map<String, Object> checkPrePw(@RequestParam Map<String, Object> paramMap) {
        String pw = paramMap.get("pw").toString();
        if (pw != null) {
            pw = pw.replaceAll("<", "&lt;");
            pw = pw.replaceAll(">", "&gt;");
        }
        String encodePassword = SHA256.encrypt(pw);//원본
        //String encodePassword =pw;//temp

        paramMap.put("prePw", encodePassword);
        //System.out.println(this.adminService.checkPrePw(paramMap));
        return this.adminService.checkPrePw(paramMap);
    }

    @RequestMapping(value = "/admin/pwUpdate.do", method = RequestMethod.POST)
    public String pwUpdate(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {

        paramMap.put("pwd", SHA256.encrypt(paramMap.get("afterPw").toString()));//원본

        this.adminService.updatePw(paramMap);
        HttpSession session = request.getSession();
        session.invalidate();
        return "redirect:/admin/index.do";
    }

    @RequestMapping(value = "/admin/status.do", method = RequestMethod.GET)
    public String stats(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("siteSubInfo", "sub admin");
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);

        Calendar cal = Calendar.getInstance();

        model.addAttribute("thisYear", Integer.toString(cal.get(Calendar.YEAR)));
        model.addAttribute("thisMonth", nf.format(cal.get(Calendar.MONTH) + 1));
        model.addAttribute("thisDate", nf.format(cal.get(Calendar.DATE)));
        model.addAttribute("lastDate", "31");
        return "admin/statusNew.tiles";
    }

    @RequestMapping(value = "/admin/getStatsList.do", method = RequestMethod.POST)
    public @ResponseBody List<StatsVO> getStatsList(@RequestParam Map<String, Object> paramMap) {
        List<StatsVO> result = null;
        if ("hhStats".equals(paramMap.get("dateType"))) {
            paramMap.put("statDate", paramMap.get("date"));
            result = this.adminService.getHHStatus(paramMap);

        } else if ("ddStats".equals(paramMap.get("dateType"))) {
            paramMap.put("statMonth", paramMap.get("date"));
            result = adminService.getDDStatus(paramMap);
        } else if ("mnStats".equals(paramMap.get("dateType"))) {
            paramMap.put("statYear", paramMap.get("date"));
            result = adminService.getMMStatus(paramMap);
        }
        return result;
    }

    /* Naver editor 사진첨부하기 설정*/
    @RequestMapping(value = "/admin/noticeImgupload.do", method = RequestMethod.POST)
    public @ResponseBody String noticeImgUpload(
            Model model,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        String sFileInfo = "";
        String filename = request.getHeader("file-name");

        String filenameExt = filename.substring(filename.lastIndexOf(".") + 1);
        filenameExt = filenameExt.toLowerCase();

        String filePath = IMAGE_FILE_PATH;
        File file = new File(filePath);
        file.setExecutable(false, true);
        file.setReadable(true);
        file.setWritable(false, true);

        if (!file.exists()) {
            file.mkdirs();
        }

        String realFileNm;
        realFileNm = UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf("."));
        String rlFileNm = filePath + File.separator + realFileNm;

        try (
                InputStream is = request.getInputStream();
                OutputStream os = new FileOutputStream(rlFileNm);
        ) {
            int numRead;
            byte b[] = new byte[Integer.parseInt(request.getHeader("file-size"))];
            if (is != null) {
                while ((numRead = is.read(b, 0, b.length)) != -1) {
                    os.write(b, 0, numRead);
                }
            }
            os.flush();
        } catch (IOException e) {
            log.error("noticeImgupload() IO Exception");
        } catch (Exception e1) {
            log.error("noticeImgupload() Exception");
        }

        sFileInfo += "&bNewLine=true";
        sFileInfo += "&sFileName=" + filename;
        sFileInfo += "&sFileURL=" + "/upload/" + realFileNm;

        return sFileInfo;
    }

    @RequestMapping(value = "/admin/noticeImguploadSingle.do", method = RequestMethod.POST)
    public String noticeImguploadSingle(
            Model model,
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("Filedata") MultipartFile file
    ) {

        String callback = request.getParameter("callback");
        String callbackFunc = request.getParameter("callback_func");

        File uploadFileHome = new File(IMAGE_FILE_PATH);
        uploadFileHome.setExecutable(false, true);
        uploadFileHome.setReadable(true);
        uploadFileHome.setWritable(false, true);

        String fileName;
        String fileUuid;

        fileName = file.getOriginalFilename();
        String fileExe = fileName.substring(fileName.lastIndexOf("."));

        fileUuid = UUID.randomUUID().toString().replace("-", "") + fileExe;

        File uploadImgFile = new File(uploadFileHome, fileUuid);
        try {
            if (file.getSize() <= 200000000) {
                file.transferTo(uploadImgFile);
            } else {
                log.error("/admin/noticeImguploadSingle.do, PopupImage is Too Large Size(Limit Size 200000000)");
            }
        } catch (IllegalStateException | IOException e) {
            log.error("/admin/noticeImguploadSingle.do, can not transfetTo uploadImgFile...");
        }

        String fileResult = "";
        if (!"".equals(file.getOriginalFilename())) {
            fileResult += "&bNewLine=true&sFileName=" + file.getOriginalFilename() + "&sFileURL=/upload/" + fileUuid;
        } else {
            fileResult += "&errstr=error";
        }

        return "redirect:" + callback + "?callback_func=" + callbackFunc + fileResult;
    }

}