package com.qiankun.controller.rainbowplan;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PaperSize;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qiankun.controller.base.BaseController;
import com.qiankun.dao.RainbowPlanUserDao;
import com.qiankun.dao.WishDao;
import com.qiankun.dao.core.Hints;
import com.qiankun.entity.Activity;
import com.qiankun.entity.RainbowPlanUser;
import com.qiankun.entity.Wish;
import com.qiankun.pages.IPageList;
import com.qiankun.service.ActivityService;
import com.qiankun.vo.RainbowPlanUserVo;
import com.qiankun.vo.WishVo;

@Controller
public class RainbowPlanWebController extends BaseController<Object>{
	
	@Autowired
    private RainbowPlanUserDao userDao;
	
	@Autowired
    private WishDao wishDao;
	
	@Autowired
    private ActivityService activityService;
	
	private ResourceBundle rb = ResourceBundle.getBundle("system");
	private String uploadAvatarPath = File.separator + "rainbowplan" + File.separator + rb.getString("uploadAvatar");
	private String uploadWishImagePath = File.separator + "rainbowplan" + File.separator + rb.getString("wishUploadImage");
	
	@RequestMapping("/rainbow/user/view")
	public ModelAndView userAdd(String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		RainbowPlanUser user = new RainbowPlanUser();
		if(StringUtils.isNotBlank(id)) {
			user = userDao.find(id);
		}
		view.getModelMap().addAttribute("user", user);
		view.setViewName("rainbow/saveuser");
        return view;
	}
	
	@RequestMapping(value = "/rainbow/user/save",method = RequestMethod.POST)
    public ModelAndView saveUser(@RequestParam(value = "file", required = false) MultipartFile file, RainbowPlanUserVo vo, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
	    		
	    RainbowPlanUser user = new RainbowPlanUser();
        if (StringUtils.isBlank(vo.getId())) {
        	if (file == null) {
        		view.getModelMap().addAttribute("message", "nopic");
        		return view;
        	}
        	
            view.getModelMap().addAttribute("status", 1);
        } else {
        	user = userDao.find(vo.getId());
        	view.getModelMap().addAttribute("status", 2); 
        	 
        }
       
        
       
        if (file != null) {
        	String fileFullName = file.getOriginalFilename();
        	String[] originalFileName = fileFullName.split("\\.");
        	String fileName = vo.getId() + "." + originalFileName[originalFileName.length-1];
            String rootPath = rb.getString("file_path");
            if (StringUtils.isNotBlank(user.getAvatar())) {
            	File oldFile =  new File(rootPath + user.getAvatar());
            	if (oldFile.isFile())
            		FileUtils.forceDelete(oldFile);
            }
            
            File destFile = new File(rootPath + uploadAvatarPath,fileName);
            FileUtils.writeByteArrayToFile(destFile,file.getBytes());
            user.setAvatar(uploadAvatarPath + File.separator + fileName);
        }
        user.setName(vo.getName());
        user.setConnectTel(vo.getConnectTel());
        user.setPhone(vo.getPhone());
        user.setReceiveAddress(vo.getReceiveAddress());
        user.setReceiveName(vo.getReceiveName());
        
        if (user.getType() == 0) {
        	user.setBedNum(vo.getBedNum());
        	user.setBirthday(vo.getBirthday());
        	user.setDisease(vo.getDisease());
        	user.setGender(vo.getGender());
        	user.setNickName(vo.getNickName());
        	user.setStatus(vo.getStatus());
        	
        }
        
        userDao.save(user);
        return view;
    }
	
	@RequestMapping("/rainbow/user/del")
	public ModelAndView userDelete(String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		if(StringUtils.isNotBlank(id)) {
			RainbowPlanUser user = userDao.find(id);
			user.setRemove(true);
			userDao.save(user);
			view.getModelMap().addAttribute("status", "success");
		}
		
        return view;
	}
	
	@RequestMapping("/rainbow/user/list")
	public ModelAndView userlist(RainbowPlanUserVo userVo,HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		 
		List<Activity> activitylist = activityService.findByAavailableAndType(true, "3"); 
        IPageList<RainbowPlanUser> userPage = userDao.findUserPage(userVo.getSearchStr(), userVo.getType(), userVo.getStatus(), userVo.getOrder(), userVo.getSort(), 
					new Hints(getStartRow(request), getPageCount(request)));
        view.getModelMap().addAttribute("activitylist", activitylist);	
		view.getModelMap().addAttribute("userPage", userPage);
		view.getModelMap().addAttribute("pageCount", getPageCount(request));
		view.getModelMap().addAttribute("pageNumber", getPageNumber(request));
		view.getModelMap().addAttribute("userVo", userVo);
		view.setViewName("rainbow/userlist");
        return view;
		
	}
	
	
	@RequestMapping("/rainbow/wish/list")
	public ModelAndView wishlist(WishVo wishVo,HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		
		List<Activity> activitylist = activityService.findByAavailableAndType(null, "3");
		
		IPageList<Wish> wishPage = wishDao.findPages(wishVo.getSearchStr(), wishVo.getActivityId(), wishVo.getStatus(), wishVo.getType(),
				wishVo.getOrder(), wishVo.getSort(), new Hints(getStartRow(request), getPageCount(request)));
		
        view.getModelMap().addAttribute("activitylist", activitylist);
		view.getModelMap().addAttribute("wishPage", wishPage);
		view.getModelMap().addAttribute("pageCount", getPageCount(request));
		view.getModelMap().addAttribute("pageNumber", getPageNumber(request));
		view.getModelMap().addAttribute("wishVo", wishVo);
		view.setViewName("rainbow/wishlist");
        
        return view;
		
	}
	
	
	@RequestMapping("/rainbow/wish/view")
	public ModelAndView wishview(String id, String userId, String activityId, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		Wish wish = new Wish();
		if(StringUtils.isNotBlank(id)) {
			wish = wishDao.find(id);
		}else {
			wish.setActivityId(activityId);
			wish.setRainbowPlanUserId(userId);
		}
		view.getModelMap().addAttribute("wish", wish);
		view.setViewName("rainbow/wishview");
        return view;
	}
	
	@RequestMapping("/rainbow/wish/status/update")
	public ModelAndView wishStatusUpdate(@RequestParam(value = "id[]") String[] id, String status, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		wishDao.batchUpdateStatus(id, status);
		return view;
	}
	
	@RequestMapping("/rainbow/wish/validate")
	public ModelAndView wishvalidate(String userId, String activityId,HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
		Long count = wishDao.countByUserIdAndActivityId(userId, activityId);
		if (count == 0) {
			view.getModelMap().addAttribute("message", "success");
		} else {
			view.getModelMap().addAttribute("message", "no");
		}
		
        return view;
	}
	
	
	@RequestMapping(value = "/rainbow/wish/save",method = RequestMethod.POST)
    public ModelAndView saveWish(@RequestParam(value = "file", required = false) MultipartFile file, WishVo vo, HttpServletResponse response, HttpServletRequest request) throws Exception {
		ModelAndView view = new ModelAndView();
	    		
	    Wish wish = new Wish();
        if (StringUtils.isBlank(vo.getId())) {
        	if (file == null) {
        		view.getModelMap().addAttribute("message", "nopic");
        		return view;
        	}
        	wish.setRainbowPlanUserId(vo.getRainbowPlanUserId());
            wish.setActivityId(vo.getActivityId());
            wish.setChildren(userDao.find(vo.getRainbowPlanUserId()));
            wish.setActivity(activityService.findById(vo.getActivityId()));
            wish.setVolunteer(null);
            view.getModelMap().addAttribute("status", 1);
        } else {
        	wish = wishDao.find(vo.getId());
        	view.getModelMap().addAttribute("status", 2); 
        	 
        }
       
        
       
        if (file != null) {
        	String fileFullName = file.getOriginalFilename();
        	String[] originalFileName = fileFullName.split("\\.");
        	String fileName = vo.getCode() + "." + originalFileName[originalFileName.length-1];
            String rootPath = rb.getString("file_path");
            if (StringUtils.isNotBlank(wish.getUploadImage())) {
            	File oldFile =  new File(rootPath + wish.getUploadImage());
            	if (oldFile.isFile())
            		FileUtils.forceDelete(oldFile);
            }
            
            
            File destFile = new File(rootPath + uploadWishImagePath,fileName);
            FileUtils.writeByteArrayToFile(destFile,file.getBytes());
            wish.setUploadImage(uploadWishImagePath + File.separator + fileName);
        }
        wish.setStatus(vo.getStatus());
        wish.setCode(vo.getCode());
        wish.setTitle(vo.getTitle());
        wish.setContent(vo.getContent());
        
        
        
        if (vo.getReset() != null && vo.getReset()) {
        	wish.setVolunteer(null);
        	wish.setExpressCode(null);
        	wish.setExpressCompany(null);
        	wish.setHelpType(0);
        }
        
       
        
        
        
        wishDao.save(wish);
            
        

        return view;
    }
	
	@RequestMapping("/rainbow/wish/export")
	public void export(WishVo wishVo, HttpServletResponse response, HttpServletRequest request) throws Exception {
		
		try {
			
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-download");
	
			String fileName = "wish.xlsx";
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
	
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet("心愿");
			sheet.setMargin(HSSFSheet.TopMargin,( double ) 0.5 ); // 上边距
			sheet.setMargin(HSSFSheet.BottomMargin,( double ) 0.5 ); // 下边距
			sheet.setMargin(HSSFSheet.LeftMargin,( double ) 0.2 ); // 左边距
			sheet.setMargin(HSSFSheet.RightMargin,( double ) 0.0 ); // 右边距

			
			XSSFPrintSetup print =  sheet.getPrintSetup(); 
			print.setLandscape(true);
			print.setPaperSize(PaperSize.A4_PAPER);
			  
			sheet.setDefaultRowHeight((short) (2 * 256));//设置行高
			sheet.setColumnWidth(0,2500);//设置列宽
			sheet.setColumnWidth(1,2500);
			sheet.setColumnWidth(2,3500);
			sheet.setColumnWidth(3,1500);
			sheet.setColumnWidth(4,3000);
			sheet.setColumnWidth(5,2500);
			sheet.setColumnWidth(6,6000);
			sheet.setColumnWidth(7,3000);
			sheet.setColumnWidth(8,3000);
			sheet.setColumnWidth(9,4000);
			sheet.setColumnWidth(10,6000);
			
	
			XSSFFont topfont = wb.createFont();
			topfont.setFontName("宋体");
			topfont.setFontHeightInPoints((short) 11);
			topfont.setBold(true);
			//topfont.setBoldweight(Font.BOLDWEIGHT_BOLD);
			
			 
			
			XSSFCellStyle cellTopStyle=wb.createCellStyle();     
			cellTopStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
			cellTopStyle.setBorderBottom(BorderStyle.THIN); //setBorderBottom(CellStyle.BORDER_THIN);
			cellTopStyle.setBorderLeft(BorderStyle.THIN);//setBorderLeft(CellStyle.BORDER_THIN);
			cellTopStyle.setBorderRight(BorderStyle.THIN);//setBorderRight(CellStyle.BORDER_THIN);
			cellTopStyle.setBorderTop(BorderStyle.THIN);//setBorderTop(CellStyle.BORDER_THIN);
			cellTopStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);  
			cellTopStyle.setFont(topfont);
			
			cellTopStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); 
			
			XSSFRow row = sheet.createRow(0);
			row.setHeightInPoints(30); 
			XSSFCell cell = row.createCell(0);
			cell.setCellValue("编号 ");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(1);
			cell.setCellValue("宝宝昵称 ");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(2);
			cell.setCellValue("宝宝真实姓名");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(3);
			cell.setCellValue("性别");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(4);
			cell.setCellValue("出生年月");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(5);			
			cell.setCellValue("楼层床号");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(6);
			cell.setCellValue("心愿礼物");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(7);
			cell.setCellValue("收件人姓名");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(8);
			cell.setCellValue("联系方式");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(9);
			cell.setCellValue("邮寄地址");
			cell.setCellStyle(cellTopStyle);
			
			cell = row.createCell(10);
			cell.setCellValue("爱心人士");
			cell.setCellStyle(cellTopStyle);
			
			XSSFCellStyle cellStyle=wb.createCellStyle();     
			cellStyle.setWrapText(true);  
			
			cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
			cellStyle.setBorderBottom(BorderStyle.THIN); //setBorderBottom(CellStyle.BORDER_THIN);
			cellStyle.setBorderLeft(BorderStyle.THIN);//setBorderLeft(CellStyle.BORDER_THIN);
			cellStyle.setBorderRight(BorderStyle.THIN);//setBorderRight(CellStyle.BORDER_THIN);
			cellStyle.setBorderTop(BorderStyle.THIN);//setBorderTop(CellStyle.BORDER_THIN);
			cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);  
			cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); 
			
			XSSFFont cellfont = wb.createFont();
			cellfont.setFontName("宋体");
			cellfont.setFontHeightInPoints((short) 10);
			cellStyle.setFont(cellfont);
			
			IPageList<Wish> wishPage = wishDao.findPages(wishVo.getSearchStr(), wishVo.getActivityId(), wishVo.getStatus(), wishVo.getType(),
					wishVo.getOrder(), wishVo.getSort(), new Hints(0));
			
			List<Wish> wish = wishPage.getRecords();
			XSSFRow rows;
    		XSSFCell cells;
    		for (int i = 0; i < wish.size(); i++) {
    			// 第三步：在这个sheet页里创建一行
    			rows = sheet.createRow(i+1);
    			rows.setHeightInPoints(70); 
    			// 第四步：在该行创建一个单元格
    			
    			Wish data = wish.get(i);
    			
    			cells = rows.createCell(0);
    			cells.setCellValue(data.getCode());
    			cells.setCellStyle(cellStyle);
    			
    			// 第五步：在该单元格里设置值
    			
    			cells = rows.createCell(1);
    			cells.setCellValue(data.getChildren().getNickName());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(2);
    			cells.setCellValue(data.getChildren().getName());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(3);
    			String gender = "男";
    			if ("2".equals(data.getChildren().getGender())) 
    				gender = "女";
    			cells.setCellValue(gender);
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(4);
    			cells.setCellValue(data.getChildren().getBirthday());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(5);
    			cells.setCellValue(data.getChildren().getBedNum());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(6);
    			cells.setCellValue(data.getContent());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(7);
    			cells.setCellValue(data.getChildren().getReceiveName());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(8);
    			cells.setCellValue(data.getChildren().getConnectTel());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(9);
    			cells.setCellValue(data.getChildren().getReceiveAddress());
    			cells.setCellStyle(cellStyle);
    			
    			cells = rows.createCell(10);
    			if (data.getVolunteer()!=null) {
    				String tel = data.getVolunteer().getConnectTel();
    				tel = tel==null ? "" : "\n" + tel;
    				String addr = data.getVolunteer().getReceiveAddress();
    				addr = addr==null ? "" : "\n" + addr;
    				cells.setCellValue(data.getVolunteer().getName() + tel +  addr);
    			} else {
    				cells.setCellValue("");
    			}
    			
    			cells.setCellStyle(cellStyle);
    			
    		}
    			
				
			OutputStream out = response.getOutputStream();
			wb.write(out);
			out.close();
			wb.close();
		
			
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
