package com.ssj.sys.controller;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.cardinfo.domain.Card;
import com.ssj.bean.sys.cardinfo.domain.CardAward;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.service.sys.cardinfo.service.CardAwardService;
import com.ssj.service.sys.cardinfo.service.CardService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/sys/card")
public class CardController extends BaseController {
    @Autowired
	private CardService cardService;
    
    @Autowired
    private CardAwardService cardAwardService;
    
    @Autowired
    private ILibJoinService libJoinService;
	
    /**
     * 活动列表
     * @param model
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
	 @RequestMapping("/cardlist")
	 public String cardlist(Model model,
	    		@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
		 Map<String, Object> params = new HashMap<String, Object>();
		params.put("LIKE_name",request.getParameter("LIKE_name")==null?"":request.getParameter("LIKE_name"));
		params.put("LIKE_keyword",request.getParameter("LIKE_keyword")==null?"":request.getParameter("LIKE_keyword"));
		SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	    Page<Map<String, Object>> page= cardService.findBylist(params, initPage(pageNo,pageSize));
		sp.setRowCnt((int)page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
		 
	     return "sys/card/cardlist";
	 }
	 /**
	  * 某个活动的snCode
	  * @param model
	  * @param pageSize
	  * @param pageNo
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("/snCodeList/{id}")
	 public String snCodeList(Model model,
			 @RequestParam(required = false, defaultValue = "10") int pageSize,@PathVariable String id ,
			 @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("id", id==null?request.getParameter("id"):id);
	     params.put("award_type", request.getParameter("award_type")==null?"":request.getParameter("award_type"));
	     params.put("wx_name", request.getParameter("wx_name")==null?"":request.getParameter("wx_name"));
	     params.put("award_status", request.getParameter("award_status")==null?"":request.getParameter("award_status"));
		 SplitPage sp = new SplitPage();
		 sp.setAction(request.getRequestURI().toString());
		 sp.setPageNo(pageNo);
		 sp.setPageSize(pageSize);
		 sp.setParams(params);
		 Page<Map<String, Object>> page= cardService.findCardAward(params, initPage(pageNo,pageSize));
		 sp.setRowCnt((int)page.getTotalElements());
		 model.addAttribute("list", page.getContent());
		 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		 model.addAttribute("page", sp);
		 model.addAttribute("id", id!=null ? id :params.get("id"));
		 model.addAttribute("search", params);
		 
		 return "sys/card/snCodeList";
	 }
	 /**
	  * 抽奖日志
	  * @param model
	  * @param pageSize
	  * @param pageNo
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("/awardLog/{id}")
	 public String awardLog(Model model,
			 @RequestParam(required = false, defaultValue = "10") int pageSize,@PathVariable String id ,
			 @RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("id", id==null?request.getParameter("id"):id);
		 params.put("stat", request.getParameter("stat")==null?"":request.getParameter("stat"));
		 params.put("wx_name", request.getParameter("wx_name")==null?"":request.getParameter("wx_name"));
		 params.put("beginDate", request.getParameter("beginDate")==null?"":request.getParameter("beginDate"));
		 params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
		 
		 SplitPage sp = new SplitPage();
		 sp.setAction(request.getRequestURI().toString());
		 sp.setPageNo(pageNo);
		 sp.setPageSize(pageSize);
		 sp.setParams(params);
		 Page<Map<String, Object>> page= cardService.findAwardLog(params, initPage(pageNo,pageSize));
		 sp.setRowCnt((int)page.getTotalElements());
		 model.addAttribute("list", page.getContent());
		 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		 model.addAttribute("page", sp);
		 model.addAttribute("id", id!=null ? id :params.get("id"));
		 model.addAttribute("search", params);
		 
		 return "sys/card/awardLog";
	 }
	 @RequestMapping("/add/{id}")
	 public String add(Model model,@PathVariable String id ) throws Exception {
		 Card card = cardService.getById(id);
		 model.addAttribute("card", card!=null ? card :new Card());
		 return "sys/card/add";
	 }
	 
	  /**
	   * 生成sncode
	   * @param id
	   * @return
	   * @throws Exception
	   */
	    @RequestMapping(value = "/generatingSncode", method = RequestMethod.POST)
	    @ResponseBody
	    public Response generatingSncode(@RequestParam( defaultValue = "id")String id) throws Exception{
	    	Response response = new  Response();
	    	Card card =cardService.getById(id);
	    	if(card !=null ){
	    		if(card.getPlayStatus()==0){
	    			cardService.generatingSncode(id);
	    			response.success();
	    		}else{
	    			response.failure("活动进行中或已结束");
	    		}
	    	}else{
	    		response.failure("活动不存在");
	    	}
	        return response;
	    }
	    /**
	     * 给用户兑奖操作
	     * @param id
	     * @return
	     * @throws Exception
	     */
	    @RequestMapping(value = "/duijiang", method = RequestMethod.POST)
	    @ResponseBody
	    public Response duijiang(@RequestParam( defaultValue = "id")String id) throws Exception{
	    	Response response = new  Response();
	    	CardAward cardAward=cardAwardService.getById(id);
	    	if(cardAward !=null ){
	    		//cardAward.setAwardTime(new Date());
	    		cardAward.setUseTime(new  Date());
	    		cardAward.setAwardStatus(3);
	    		cardAwardService.save(cardAward);
	    		response.success("兑奖成功!");
	    	}else{
	    		response.failure("奖品不存在!");
	    	}
	    	return response;
	    }
	    /**
	     * 发布活动
	     * @param id
	     * @return
	     * @throws Exception
	     */
	    @RequestMapping(value = "/fabu", method = RequestMethod.POST)
	    @ResponseBody
	    public Response fabu(@RequestParam( defaultValue = "id")String id,Integer type) throws Exception{
	    	Response response = new  Response();
	    	Card card =cardService.getById(id);
	    	if(card !=null ){
	    		card.setPlayStatus(type);
	    		cardService.save(card);
	    		response.success(type==2?"结束成功":"发布成功");
	    	}else{
	    		response.failure("活动不存在");
	    	}
	    	return response;
	    }
	    /**
	     * 保存活动，发布
	     * @param card
	     * @return
	     * @throws Exception
	     */
	    @RequestMapping(value = "/saveCard", method = RequestMethod.POST)
	    @ResponseBody
	    public Response saveCard(Card card) throws Exception{
	    	Response response = new  Response();
	    	card.setCreateTime(new Date());
	      	if(card !=null && card.getQrCode() ==null && card.getId() !=null && card.getLibId() !=null){
	    		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
	    		String fPath = "/CARD";
	    		
				
				fPath += DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
				if(card.getLibId() !=null){
	    			TbLibJoin join=	libJoinService.getById(card.getLibId());
	    			fPath +="/"+join.getLeagueName();
	    		}
				if (!fPath.endsWith("/")) {
					fPath += "/";
				}
				File  f = new File(file_path+fPath);
				if (!f.exists()) {
					f.mkdirs();
				}
				    String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/hd/libgame_BOOKDetails.html";
					String fPathId = fPath + card.getId() + ".jpg";
					url=url.replace("BOOKDetails", card.getId());
					BarcodeFactory.bookencode(url,file_path+fPathId,400, 400);
					card.setQrCode(fPathId);	
	    	}
	    	cardService.save(card);
	    	response.success();
	    	return response;
	    }
	    
	    @RequestMapping(value = "/deleteCard", method = RequestMethod.POST)
	    @ResponseBody
	    public Response deleteCard(@RequestParam( defaultValue = "id")String id){
	    	Response response = new  Response();
	    	cardService.deleteCardAndCardAward(id);
	    	response.success();
	    	return response;
	    }
	    
	
	    
	    /**
	     * 导出中奖
	    * @param request
	    * @param response
	    * 创建人：ZhangCaibao 
	    * 2017年8月22日 上午10:02:34 
	    * @void
	     */
	     @RequestMapping(value = "/exportZhongJiang/{id}", method = RequestMethod.POST)
	     @ResponseBody
	     public void exportZhongJiang( HttpServletRequest request, HttpServletResponse response ,@PathVariable String id ) {  
	     	ServletOutputStream os = null;
	     	try {  
	     		 Map<String, Object> params = new HashMap<String, Object>();
	    		 params.put("id", id==null?request.getParameter("id"):id);
	    	     params.put("award_type", request.getParameter("award_type")==null?"":request.getParameter("award_type"));
	    	     params.put("wx_name", request.getParameter("wx_name")==null?"":request.getParameter("wx_name"));
	    	     params.put("award_status", request.getParameter("award_status")==null?"":request.getParameter("award_status"));
	     		os = response.getOutputStream(); //获得输出流  
	     		response.reset();   //清空输出流  
	     		String fileName = new String("奖品中奖记录".getBytes("gb2312"), "ISO8859-1") +".xlsx";  
	     		response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
	     		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
	     		response.setCharacterEncoding("utf-8");
	     		List<Map<String, Object>> list = cardService.zhongjiang(params);
	     		List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	     		
	     		myColumns3.add(new ExcelColumn("奖品名称", "award_type", 20));
	     		myColumns3.add(new ExcelColumn("兑奖SN码", "sn_code", 20));
	     		myColumns3.add(new ExcelColumn("奖品状态", "award_status", 20));
	     		myColumns3.add(new ExcelColumn("中奖时间", "award_time", 20));
	     		myColumns3.add(new ExcelColumn("中奖人", "wx_name", 20));
	     		CustomizeToExcel.downFile(myColumns3, list, os);
	     	}catch (IOException e) {
				logger.error("异常", e);
	     	}catch (Exception e1){
				logger.error("异常", e1);
	     	}finally{
	     		if(os != null){
	     			try {
	     				os.flush();
	     				os.close(); 
	     			} catch (IOException e) {
						logger.error("异常", e);
	     			}  
	     		}
	     		
	     	}
	     	
	     	
	     }   
	     /**
	      * 导出抽奖记录
	      * @param request
	      * @param response
	      * 创建人：ZhangCaibao 
	      * 2017年8月22日 上午10:02:34 
	      * @void
	      */
	     @RequestMapping(value = "/exportCJlog/{id}", method = RequestMethod.POST)
	     @ResponseBody
	     public void exportCJlog( HttpServletRequest request, HttpServletResponse response ,@PathVariable String id ) {  
	    	 ServletOutputStream os = null;
	    	 try {  
	    		 Map<String, Object> params = new HashMap<String, Object>();
	    		 params.put("id", id==null?request.getParameter("id"):id);
	    		 params.put("award_type", request.getParameter("award_type")==null?"":request.getParameter("award_type"));
	    		 params.put("wx_name", request.getParameter("wx_name")==null?"":request.getParameter("wx_name"));
	    		 params.put("award_status", request.getParameter("award_status")==null?"":request.getParameter("award_status"));
	    		 os = response.getOutputStream(); //获得输出流  
	    		 response.reset();   //清空输出流  
	    		 String fileName = new String("抽奖中奖记录".getBytes("gb2312"), "ISO8859-1") +".xlsx";  
	    		 response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头  
	    		 response.setContentType("application/vnd.ms-excel;charset=UTF-8");
	    		 response.setCharacterEncoding("utf-8");
	    		 List<Map<String, Object>> list = cardService.exportCJlog(params);
	    		 List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
	    		 
	    		 myColumns3.add(new ExcelColumn("用户昵称", "wx_name", 20));
	    		 myColumns3.add(new ExcelColumn("兑奖SN码", "sn_code", 20));
	    		 myColumns3.add(new ExcelColumn("中奖状态", "stat", 20));
	    		 myColumns3.add(new ExcelColumn("中奖时间", "create_time", 20));
	    		 myColumns3.add(new ExcelColumn("奖品名次", "award_place", 20));
	    		 myColumns3.add(new ExcelColumn("奖品内容", "award_type", 20));
	    		 CustomizeToExcel.downFile(myColumns3, list, os);
	    	 }catch (IOException e) {
				 logger.error("异常", e);
	    	 }catch (Exception e1){
				 logger.error("异常", e1);
	    	 }finally{
	    		 if(os != null){
	    			 try {
	    				 os.flush();
	    				 os.close(); 
	    			 } catch (IOException e) {
						 logger.error("异常", e);
	    			 }  
	    		 }
	    		 
	    	 }
	    	 
	    	 
	     }   
}
