package com.kubg.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kubg.domain.CategoryVO;
import com.kubg.domain.GoodsVO;
import com.kubg.domain.GoodsViewVO;
import com.kubg.domain.OrderListVO;
import com.kubg.domain.OrderVO;
import com.kubg.domain.ReplyListVO;
import com.kubg.domain.ReplyVO;
import com.kubg.service.AdminService;
import com.kubg.utils.UploadFileUtils;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/admin/*")
public class AdminController {

	private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
	
	@Inject
	AdminService adminService;
		
	@Resource(name="uploadPath")
	private String uploadPath;
	
	// 愿�由ъ옄�솕硫�
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void getIndex() throws Exception {
		logger.info("get index"); 
	}

	// �긽�뭹 �벑濡�
	@RequestMapping(value = "/goods/register", method = RequestMethod.GET)
	public void getGoodsRegister(Model model) throws Exception {
		logger.info("get goods register");
		
		List<CategoryVO> category = null;  // CatagoryVO �삎�깭�쓽 List�삎 蹂��닔 category �꽑�뼵
		category = adminService.category();  // DB�뿉 ���옣�맂 移댄뀒怨좊━瑜� 媛��졇���꽌 category�뿉 ���옣
		model.addAttribute("category", JSONArray.fromObject(category));  // 蹂��닔 category瑜� �젣�씠�뒯(json)���엯�쑝濡� 蹂��솚�븯�뿬 category �꽭�뀡�뿉 遺��뿬
	}

	
	
	/*@RequestMapping(value = "/goods/register")
	public String insertWarn(GoodsVO vo, HttpSession session,
			@ModelAttribute("file") MultipartFile file) {

		
		try {

			String imgUploadPath = uploadPath + File.separator + "imgUpload";
			String ymdPath = UploadFileUtils.calcPath(imgUploadPath);
			String fileName = null;

			if (file.getOriginalFilename() != null && file.getOriginalFilename() != "") {
				fileName = UploadFileUtils.fileUpload(imgUploadPath, file.getOriginalFilename(), file.getBytes(),
						ymdPath);
			} else {
				fileName = uploadPath + File.separator + "images" + File.separator + "none.png";
			}

			vo.setGdsImg(File.separator + "imgUpload" + ymdPath + File.separator + fileName);
			vo.setGdsThumbImg(File.separator + "imgUpload" + ymdPath + File.separator + "s" + File.separator + "s_" + fileName);

			System.out.println("vo = " + vo.getGdsName());
			System.out.println("vo = " + vo.getGdsImg());
			
			adminService.register(vo);
			

		} catch (Exception e) {

		}

		return "redirect:/admin/index";

	}*/
	
	// �긽�뭹 �벑濡�
	@RequestMapping(value = "/goods/register", method = RequestMethod.POST)
	public String postGoodsRegister(GoodsVO vo, MultipartFile file) throws Exception {
		
		String imgUploadPath = uploadPath + File.separator + "imgUpload";  // �씠誘몄�瑜� �뾽濡쒕뱶�븷 �뤃�뜑瑜� �꽕�젙 = /uploadPath/imgUpload 
		String ymdPath = UploadFileUtils.calcPath(imgUploadPath);  // �쐞�쓽 �뤃�뜑瑜� 湲곗��쑝濡� �뿰�썡�씪 �뤃�뜑瑜� �깮�꽦
		String fileName = null;  // 湲곕낯 寃쎈줈�� 蹂꾧컻濡� �옉�꽦�릺�뒗 寃쎈줈 + �뙆�씪�씠由�
				
		if(file.getOriginalFilename() != null && file.getOriginalFilename() != "") {
			// �뙆�씪 �씤�뭼諛뺤뒪�뿉 泥⑤��맂 �뙆�씪�씠 �뾾�떎硫�(=泥⑤��맂 �뙆�씪�씠 �씠由꾩씠 �뾾�떎硫�)
			
			fileName =  UploadFileUtils.fileUpload(imgUploadPath, file.getOriginalFilename(), file.getBytes(), ymdPath);
	
			// gdsImg�뿉 �썝蹂� �뙆�씪 寃쎈줈 + �뙆�씪紐� ���옣
			vo.setGdsImg(File.separator + "imgUpload" + ymdPath + File.separator + fileName);
			// gdsThumbImg�뿉 �뜽�꽕�씪 �뙆�씪 寃쎈줈 + �뜽�꽕�씪 �뙆�씪紐� ���옣
			vo.setGdsThumbImg(File.separator + "imgUpload" + ymdPath + File.separator + "s" + File.separator + "s_" + fileName);
			
		} else {  // 泥⑤��맂 �뙆�씪�씠 �뾾�쑝硫�
			fileName = File.separator + "images" + File.separator + "none.png";
			// 誘몃━ 以�鍮꾨맂 none.png�뙆�씪�쓣 ���떊 異쒕젰�븿
			
			vo.setGdsImg(fileName);
			vo.setGdsThumbImg(fileName);
		}
		
		
		System.out.println("=================");
		
		System.out.println("1 = " + vo.getGdsName());
		System.out.println("1 = " + vo.getGdsPrice());
		System.out.println("1 = " + vo.getGdsDes());
		System.out.println("1 = " + vo.getGdsImg());
		System.out.println("=================");
							
		adminService.register(vo);
		
		return "redirect:/admin/index";
	}
		  
	// �긽�뭹 紐⑸줉
	@RequestMapping(value = "/goods/list", method = RequestMethod.GET)
	public void getGoodsList(Model model) throws Exception {
		logger.info("get goods list");
		
		List<GoodsViewVO> list = adminService.goodslist();  // GoodsVO�삎�깭�쓽 List�삎 蹂��닔 list �꽑�뼵
		
		model.addAttribute("list", list);  // 蹂��닔 list�쓽 媛믪쓣 list �꽭�뀡�뿉 遺��뿬
	}
	
	// �긽�뭹 議고쉶
	@RequestMapping(value = "/goods/view", method = RequestMethod.GET)
	public void getGoodsview(@RequestParam("n") int gdsNum, Model model) throws Exception {
		logger.info("get goods view");
		
		GoodsViewVO goods = adminService.goodsView(gdsNum);
		model.addAttribute("goods", goods);
	}
	
	// �긽�뭹 �닔�젙 
	@RequestMapping(value = "/goods/modify", method = RequestMethod.GET)
	public void getGoodsModify(@RequestParam("n") int gdsNum, Model model) throws Exception {
	// @RequestParam("n")�쑝濡� �씤�빐, URL二쇱냼�뿉 �엳�뒗 n�쓽 媛믪쓣 媛��졇�� gdsNum�뿉 ���옣
		
		logger.info("get goods modify");
		
		GoodsViewVO goods = adminService.goodsView(gdsNum);  // GoodsViewVO�삎�깭 蹂��닔 goods�뿉 �긽�뭹 �젙蹂� ���옣
		model.addAttribute("goods", goods);
		
		List<CategoryVO> category = null;
		category = adminService.category();
		model.addAttribute("category", JSONArray.fromObject(category));
	}
	
	// �긽�뭹 �닔�젙
	@RequestMapping(value = "/goods/modify", method = RequestMethod.POST)
	public String postGoodsModify(GoodsVO vo, MultipartFile file, HttpServletRequest req) throws Exception {
		logger.info("post goods modify");
	
		// �깉濡쒖슫 �뙆�씪�씠 �벑濡앸릺�뿀�뒗吏� �솗�씤
		if(file.getOriginalFilename() != null && file.getOriginalFilename() != "") {
			// 湲곗〈 �뙆�씪�쓣 �궘�젣
			new File(uploadPath + req.getParameter("gdsImg")).delete();
			new File(uploadPath + req.getParameter("gdsThumbImg")).delete();
			
			// �깉濡� 泥⑤��븳 �뙆�씪�쓣 �벑濡�
			String imgUploadPath = uploadPath + File.separator + "imgUpload";
			String ymdPath = UploadFileUtils.calcPath(imgUploadPath);
			String fileName = UploadFileUtils.fileUpload(imgUploadPath, file.getOriginalFilename(), file.getBytes(), ymdPath);
			
			vo.setGdsImg(File.separator + "imgUpload" + ymdPath + File.separator + fileName);
			vo.setGdsThumbImg(File.separator + "imgUpload" + ymdPath + File.separator + "s" + File.separator + "s_" + fileName);
			
		} else {  // �깉濡쒖슫 �뙆�씪�씠 �벑濡앸릺吏� �븡�븯�떎硫�
			// 湲곗〈 �씠誘몄�瑜� 洹몃�濡� �궗�슜
			vo.setGdsImg(req.getParameter("gdsImg"));
			vo.setGdsThumbImg(req.getParameter("gdsThumbImg"));
			
		}
		
		adminService.goodsModify(vo);
		
		return "redirect:/admin/index";
	}
	
	// �긽�뭹 �궘�젣
	@RequestMapping(value = "/goods/delete", method = RequestMethod.POST)
	public String postGoodsDelete(@RequestParam("n") int gdsNum) throws Exception {
	// @RequestParam("n")�쑝濡� �씤�빐, URL二쇱냼�뿉 �엳�뒗 n�쓽 媛믪쓣 媛��졇�� gdsNum�뿉 ���옣
	
		logger.info("post goods delete");
	
		adminService.goodsDelete(gdsNum);
		
		return "redirect:/admin/index";
	}
	
	// ck �뿉�뵒�꽣�뿉�꽌 �뙆�씪 �뾽濡쒕뱶
	@RequestMapping(value = "/goods/ckUpload", method = RequestMethod.POST)
	public void postCKEditorImgUpload(HttpServletRequest req,
									  HttpServletResponse res,
									  @RequestParam MultipartFile upload) throws Exception {
		logger.info("post CKEditor img upload");
		
		// �옖�뜡 臾몄옄 �깮�꽦
		UUID uid = UUID.randomUUID();
		
		OutputStream out = null;
		PrintWriter printWriter = null;
				
		// �씤肄붾뵫
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=utf-8");
		
		try {
			
			String fileName = upload.getOriginalFilename();  // �뙆�씪 �씠由� 媛��졇�삤湲�
			byte[] bytes = upload.getBytes();
			
			// �뾽濡쒕뱶 寃쎈줈
			String ckUploadPath = uploadPath + File.separator + "ckUpload" + File.separator + uid + "_" + fileName;
			
			out = new FileOutputStream(new File(ckUploadPath));
			out.write(bytes);
			out.flush();  // out�뿉 ���옣�맂 �뜲�씠�꽣瑜� �쟾�넚�븯怨� 珥덇린�솕
			
			String callback = req.getParameter("CKEditorFuncNum");
			printWriter = res.getWriter();
			String fileUrl = "/ckUpload/" + uid + "_" + fileName;  // �옉�꽦�솕硫�
			
			// �뾽濡쒕뱶�떆 硫붿떆吏� 異쒕젰
			printWriter.println("<script type='text/javascript'>"
						+ "window.parent.CKEDITOR.tools.callFunction("
						+ callback+",'"+ fileUrl+"','�씠誘몄�瑜� �뾽濡쒕뱶�븯���뒿�땲�떎.')"
						+"</script>");
			
			printWriter.flush();
			
		} catch (IOException e) { e.printStackTrace();
		} finally {
			try {
				if(out != null) { out.close(); }
				if(printWriter != null) { printWriter.close(); }
			} catch(IOException e) { e.printStackTrace(); }
		} 
		
		return;	
	}
	
	// 二쇰Ц 紐⑸줉
	@RequestMapping(value = "/shop/orderList", method = RequestMethod.GET)
	public void getOrderList(Model model) throws Exception {
		logger.info("get order list");
				
		List<OrderVO> orderList = adminService.orderList();
		
		model.addAttribute("orderList", orderList);
	}
	 
	// 二쇰Ц �긽�꽭 紐⑸줉
	@RequestMapping(value = "/shop/orderView", method = RequestMethod.GET)
	public void getOrderList(@RequestParam("n") String orderId,
							OrderVO order, Model model) throws Exception {
		logger.info("get order view");
		
		order.setOrderId(orderId);		
		List<OrderListVO> orderView = adminService.orderView(order);
		
		model.addAttribute("orderView", orderView);
	}
	
	// 二쇰Ц �긽�꽭 紐⑸줉 - �긽�깭 蹂�寃�
	@RequestMapping(value = "/shop/orderView", method = RequestMethod.POST)
	public String delivery(OrderVO order) throws Exception {
		logger.info("post order view");
				
		adminService.delivery(order);
		
		// �깉濡쒖슫 Service �넂 DAO �넂 Mapper 瑜� �궗�슜�븯吏� �븡怨�, 湲곗〈�뿉 �엳�뜕 Service瑜� �궗�슜
		List<OrderListVO> orderView = adminService.orderView(order);	
		
		// �깮�꽦�옄 �궗�슜
		GoodsVO goods = new GoodsVO();
				
		for(OrderListVO i : orderView) {
			goods.setGdsNum(i.getGdsNum());
			goods.setGdsStock(i.getCartStock());
			adminService.changeStock(goods);
		}
	
		return "redirect:/admin/shop/orderView?n=" + order.getOrderId();
	}
	
	// 紐⑤뱺 �냼媛�(�뙎湲�)
	@RequestMapping(value = "/shop/allReply", method = RequestMethod.GET)
	public void getAllReply(Model model) throws Exception {
		logger.info("get all reply");
				
		List<ReplyListVO> reply = adminService.allReply();
		
		model.addAttribute("reply", reply);
	}

	// 紐⑤뱺 �냼媛�(�뙎湲�)
	@RequestMapping(value = "/shop/allReply", method = RequestMethod.POST)
	public String postAllReply(ReplyVO reply) throws Exception {
		logger.info("post all reply");
				
		adminService.deleteReply(reply.getRepNum());
		
		return "redirect:/admin/shop/allReply";
	}	

}