package com.qiankun.controller.rainbowplan;

import java.io.File;
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.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;
	
	@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.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();

	    String uploadWishImagePath = File.separator + "rainbowplan" + File.separator + "wishUploadImage";
	    ResourceBundle rb = ResourceBundle.getBundle("system");
	    		
	    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;
    }
}
