package com.ssj.sys.controller;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.award.domain.AwardActivity;
import com.ssj.bean.sys.award.domain.AwardConsume;
import com.ssj.bean.sys.award.domain.AwardGrant;
import com.ssj.bean.sys.award.domain.AwardMaterial;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.service.sys.award.service.*;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.apache.commons.lang3.StringUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 *    新版的抽奖后台管理功能
 * 2020年5月27日9:37:1
 * @author wuwen
 */

@Controller
@RequestMapping("/sys/award")
public class AwardController extends BaseController {
	
    @Autowired
    private AwardMaterialService awardMaterialService;
    
    @Autowired
    private AwardActivityService awardActivityService;
    
    @Autowired
    private AwardActivityLogService awardActivityLogService;
    
    @Autowired
    private AwardStockService awardStockService;
    
    @Autowired
    private AwardGrantService awardGrantService;
    
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private AwardConsumeService awardConsumeService;
	
	@Autowired
	private AwardSncodeService awardSncodeService;
	
	//指点的code
	public static String SSJCODE="ssj001";
	
	//管理层的org
	public static String SSJFX="SSJ-FX";
	
	//奖品物资列表
	@RequestMapping("/material/list")
    public String materialList(Model model,
                                        @RequestParam(required = false, defaultValue = "30") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {
        Map<String, Object> params = new HashMap<String, Object>();
        
    	HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
        
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardMaterialService.findAwardMaterialBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("curMerchant", curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/material/list";
    }
	
	
	//导出奖品物资列表
	@RequestMapping("/material/list_export")
    @ResponseBody
    public void materialListExport(Model model) throws Exception {
		
		 Map<String, Object> params = new HashMap<String, Object>();
	        
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
        
        Page<Map<String,Object>> page = awardMaterialService.findAwardMaterialBylist(params, initPage(1, 10000));
        List<Map<String,Object>> list=page.getContent();
       
        String libName="奖品物资列表";
        ServletOutputStream os = response.getOutputStream(); //获得输出流  
		response.reset();   //清空输出流  
		String fileName = new String(libName.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");
		
        for (Map<String, Object> map : list) {
			switch (map.get("level").toString()) {
				case "1":map.put("level", "一等奖");break;
				case "2":map.put("level", "二等奖");break;
				case "3":map.put("level", "三等奖");break;
				default:map.put("level", "");break;
			}
		}
	    List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
		myColumns3.add(new ExcelColumn("奖品名称", "name", 20));
		myColumns3.add(new ExcelColumn("等级", "level", 20));
		myColumns3.add(new ExcelColumn("库存数量", "stock_number", 20));
		myColumns3.add(new ExcelColumn("已用库存", "use_number", 20));
		myColumns3.add(new ExcelColumn("审核库存", "lock_number", 20));
		myColumns3.add(new ExcelColumn("兑换积分", "exchange_integral", 20));
		myColumns3.add(new ExcelColumn("市场价", "price", 20));
		myColumns3.add(new ExcelColumn("奖品备注", "remarks", 20));
		myColumns3.add(new ExcelColumn("创建时间", "create_time", 20));
    	CustomizeToExcel.downFile(myColumns3, list, os);
    }
	
	
	
	//奖品物资列表
	@RequestMapping("/material/consume")
    public String materialConsume(Model model,
                                        @RequestParam(required = false, defaultValue = "30") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
        
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);
		
		List<String> subMerchantIds=new ArrayList<String>();
        if(request.getParameter("merchantId")!=null && !"".equals(request.getParameter("merchantId").toString())) {
        	subMerchantIds.add(request.getParameter("merchantId").toString());
        }else {
    		for (Merchant merchant : subMerchants) {
    			subMerchantIds.add(merchant.getId());
    		}
        }
	 	params.put("awardMaterialId", request.getParameter("id")==null?"":request.getParameter("id"));
		params.put("status", request.getParameter("status")==null?"":request.getParameter("status"));
		params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
		params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardConsumeService.findAwardConsumeByAwardMaterial(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("curMerchant", curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("subMerchants",subMerchants);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/material/consume";
    }
	
	

	//奖品物资新增，编辑
	@RequestMapping("/material/edit")
    public String materialEdit(Model model,String id) throws Exception {
		AwardMaterial awardMaterial=new AwardMaterial();
		if(StringUtils.isNotEmpty(id)) {
			awardMaterial=awardMaterialService.getById(id);
		}
		model.addAttribute("awardMaterial", awardMaterial);
        return "sys/award/material/edit";
    }
	
	
	
	//奖品物资新增，编辑，保存
	@RequestMapping("/material/save")
	@ResponseBody
    public Response materialSave(Model model,AwardMaterial awardMaterial)throws Exception {
		Response response = new  Response();
		if(StringUtils.isEmpty(awardMaterial.getId())) {
			awardMaterial.setStockNumber(0);
			awardMaterial.setUseNumber(0);
			awardMaterial.setLockNumber(0);
			awardMaterial.setStatus(1);
			awardMaterial.setCreateTime(new Date());
			awardMaterial.setUpdateTime(new Date());
			awardMaterialService.save(awardMaterial);
		}else {
			AwardMaterial oldAwardMaterial=awardMaterialService.getById(awardMaterial.getId());
			oldAwardMaterial.setName(awardMaterial.getName());
			oldAwardMaterial.setImg(awardMaterial.getImg());
			oldAwardMaterial.setLevel(awardMaterial.getLevel());
			oldAwardMaterial.setExchangeIntegral(awardMaterial.getExchangeIntegral());
			oldAwardMaterial.setUpdateTime(new Date());
			oldAwardMaterial.setRemarks(awardMaterial.getRemarks());
			oldAwardMaterial.setPrice(awardMaterial.getPrice());
			awardMaterialService.save(oldAwardMaterial);
		}
		response.success("成功");
        return response;
    }
	
	
	//奖品物资的状态更新
	@RequestMapping("/material/status")
	@ResponseBody
    public Response materialStatus(Model model,String id,Integer status)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)) {
			AwardMaterial awardMaterial = awardMaterialService.getById(id);
			awardMaterial.setStatus(status);
			awardMaterial.setUpdateTime(new Date());
			awardMaterialService.save(awardMaterial);
		}
		response.success("成功");
        return response;
    }
	
	
	//奖品物资新增库存
	@RequestMapping("/material/number")
    public String materialNumber(Model model,String id) throws Exception {
		AwardMaterial awardMaterial=new AwardMaterial();
		if(StringUtils.isNotEmpty(id)) {
			awardMaterial=awardMaterialService.getById(id);
		}
		model.addAttribute("awardMaterial",awardMaterial);
        return "sys/award/material/number";
    }
	
	
	//奖品物资新增库存，保存
	@RequestMapping("/material/number/save")
	@ResponseBody
    public Response materialNumberSave(Model model,String id,Integer number)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)) {
			if(number==null) {
				number=0;
			}
			AwardMaterial awardMaterial = awardMaterialService.getById(id);
			awardMaterial.setStockNumber((awardMaterial.getStockNumber()==null?0:awardMaterial.getStockNumber())+number);
			awardMaterial.setUpdateTime(new Date());
			awardMaterialService.save(awardMaterial);
			
			
			AwardConsume awardConsume=new AwardConsume();
			awardConsume.setAwardMaterialId(id);
			awardConsume.setCreateTime(new Date());
			awardConsume.setType(6);
			awardConsume.setNumber(number);
			awardConsume.setRemarks("奖品入库");
			awardConsumeService.save(awardConsume);
		}
		response.success("成功");
        return response;
    }
	
	
	
	
	//奖品库存列表
	@RequestMapping("/stock/list")
    public String stockList(Model model,
                                        @RequestParam(required = false, defaultValue = "30") int pageSize,
                                        @RequestParam(required = false, defaultValue = "1") int pageNo) {

        Map<String, Object> params = new HashMap<String, Object>();
        
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		List<String> subMerchantIds=new ArrayList<String>();
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			subMerchantIds.add(curMerchant.getId());
		}
		params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardStockService.findAwardStockBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("curMerchant", curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/stock/list";
    }
		
	
	
	
	//奖品的发放列表
	@RequestMapping("/grant/list")
    public String grantList(Model model,
			            @RequestParam(required = false, defaultValue = "30") int pageSize,
			            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);
		
		List<String> subMerchantIds=new ArrayList<String>();
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			for (Merchant merchant : subMerchants) {
				subMerchantIds.add(merchant.getId());
			}
		}
		
	 	Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", request.getParameter("title")==null?"":request.getParameter("title"));
        
        params.put("status", request.getParameter("status")==null?"":request.getParameter("status"));
        params.put("ems", request.getParameter("ems")==null?"":request.getParameter("ems"));
        params.put("dingNumber", request.getParameter("dingNumber")==null?"":request.getParameter("dingNumber"));
        params.put("emsNumber", request.getParameter("emsNumber")==null?"":request.getParameter("emsNumber"));
        params.put("remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
        
        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardGrantService.findAwardGrantBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("subMerchants",subMerchants);
        model.addAttribute("curMerchant",curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/grant/list";
    }
	
	
	
	//奖品的发放新增，编辑
	@RequestMapping("/grant/edit")
    public String grantEdit(Model model,String id) throws Exception {
		AwardGrant awardGrant=new AwardGrant();
		if(StringUtils.isNotEmpty(id)) {
			awardGrant=awardGrantService.getById(id);
		}
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);
		
		List<AwardMaterial> level1Materials=awardMaterialService.findAwardMaterialByLevel(1);//一等奖
		List<AwardMaterial> level2Materials=awardMaterialService.findAwardMaterialByLevel(2);//二等奖
		List<AwardMaterial> level3Materials=awardMaterialService.findAwardMaterialByLevel(3);//三等奖
		
		model.addAttribute("subMerchants", subMerchants);
		model.addAttribute("curMerchant",curMerchant);
		model.addAttribute("awardGrant", awardGrant);
		model.addAttribute("level1Materials", level1Materials);
		model.addAttribute("level2Materials", level2Materials);
		model.addAttribute("level3Materials", level3Materials);
        return "sys/award/grant/edit";
    }
	
		
		
	//奖品发放新增，编辑，保存
	@RequestMapping("/grant/save")
	@ResponseBody
    public Response grantSave(Model model,AwardGrant awardGrant)throws Exception {
		Response response = new  Response();
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		awardGrant.setFromMerchantId(curMerchant.getId());
		awardGrant.setCreateTime(new Date());
		
		if(StringUtils.isNotEmpty(awardGrant.getLevel1MaterialId())) {
			Integer stock=awardStockService.getStockNumByMerchantIdAndLevelMaterialId(curMerchant.getId(), awardGrant.getLevel1MaterialId());
			if(stock<awardGrant.getLevel1Num()) {
				response.failure("您的一等奖库存不足。");
				return response;
			}
		}
		
		if(StringUtils.isNotEmpty(awardGrant.getLevel2MaterialId())) {
			Integer stock=awardStockService.getStockNumByMerchantIdAndLevelMaterialId(curMerchant.getId(), awardGrant.getLevel2MaterialId());
			if(stock<awardGrant.getLevel2Num()) {
				response.failure("您的二等奖库存不足。");
				return response;
			}
		}
		
		if(StringUtils.isNotEmpty(awardGrant.getLevel3MaterialId())) {
			Integer stock=awardStockService.getStockNumByMerchantIdAndLevelMaterialId(curMerchant.getId(), awardGrant.getLevel3MaterialId());
			if(stock<awardGrant.getLevel3Num()) {
				response.failure("您的三等奖库存不足。");
				return response;
			}
		}
		
		boolean is=true;
		Merchant merchant=merchantService.getById(awardGrant.getToMerchantId());
		if(SSJCODE.equals(merchant.getParentPosCode())) {
			awardGrant.setStatus(2);
			is= awardGrantService.addAwardGrantAndAwardStockBySSJFX(awardGrant);
		}else {
			awardGrant.setEmsTime(new Date());
			awardGrant.setStatus(1);
			is=awardGrantService.addAwardGrantAndAwardStock(awardGrant);
		}
		
		if(is) {
			response.success("成功");
		}else {
			response.failure("奖品发放异常，请刷新后重试。");
		}
        return response;
    }
	
		
		
	//当前商户的各奖品库存
	@RequestMapping("/grant/stock/get")
	@ResponseBody
    public Response grantStockGet(Model model,String merchantId,String levelMaterialId) throws Exception {
		 Response response = new  Response();
		 Map<String,Object> data=new HashMap<String, Object>();
		 
		 Merchant selectMerchant=null;
		 if(StringUtils.isNotEmpty(merchantId)) {
			 selectMerchant=merchantService.getById(merchantId);
		 }else {
			 HttpSession session = request.getSession();
			 Admin admin =(Admin) session.getAttribute("admin");
			 selectMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		 }
		 
		 Integer stock=0;
		 if(selectMerchant==null || StringUtils.isNotEmpty(levelMaterialId)) {
			 stock=awardStockService.getStockNumByMerchantIdAndLevelMaterialId(selectMerchant.getId(), levelMaterialId);
		 }
		 
		 data.put("stock", stock);
		 response.success(data, "成功");
		 return response;
    }

	//编辑Ems
	@RequestMapping("/grant/ems")
    public String grantEmsEdit(Model model,String id) throws Exception {
		AwardGrant awardGrant=new AwardGrant();
		if(StringUtils.isNotEmpty(id)) {
			awardGrant=awardGrantService.getById(id);
		}
		model.addAttribute("awardGrant", awardGrant);
        return "sys/award/grant/ems";
    }
		
		
	//奖品物流的保存
	@RequestMapping("/grant/ems/save")
	@ResponseBody
    public Response grantEmsSave(Model model,String id,String dingNumber,String emsNumber,String people,String telephone,String address,String remarks,String img) throws Exception {
		Response response = new  Response();
		AwardGrant awardGrant=new AwardGrant();
		if(StringUtils.isNotEmpty(id)) {
			awardGrant=awardGrantService.getById(id);
			if(awardGrant.getStatus()==1 && awardGrant.getEmsTime()==null) {
				awardGrant.setDingNumber(dingNumber);
				awardGrant.setEmsNumber(emsNumber);
				awardGrant.setPeople(people);
				awardGrant.setTelephone(telephone);
				awardGrant.setAddress(address);
				awardGrant.setEmsTime(new Date());
				awardGrant.setImg(img);
				awardGrant.setRemarks(remarks);

				awardGrantService.updateAwardGrantByStatus(awardGrant, 1);
			}
			response.success("成功");
		}else {
			response.failure("保存物流的异常");
		}
		return response;
    }
		
	
	//我的活动列表
	@RequestMapping("/activity/list")
    public String activityList(Model model,
			            @RequestParam(required = false, defaultValue = "30") int pageSize,
			            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);
		
		List<String> subMerchantIds=new ArrayList<String>();
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			for (Merchant merchant : subMerchants) {
				subMerchantIds.add(merchant.getId());
			}
		}
		
	 	Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", request.getParameter("title")==null?"":request.getParameter("title"));
        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        params.put("merchantId", String.join(";", subMerchantIds));
        params.put("status", "0;1;2;3");
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardActivityService.findAwardActivityBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("subMerchants",subMerchants);
        model.addAttribute("curMerchant", curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/activity/list";
    }
	
	
	//我的活动列表
		@RequestMapping("/activity/log")
	    public String activityLog(Model model,
				            @RequestParam(required = false, defaultValue = "30") int pageSize,
				            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
			
			HttpSession session = request.getSession();
			Admin admin =(Admin) session.getAttribute("admin");
			Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());

		 	Map<String, Object> params = new HashMap<String, Object>();
		 	params.put("id", request.getParameter("id")==null?"":request.getParameter("id"));
		 	params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
		 	params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
			params.put("sncode", request.getParameter("sncode")==null?"":request.getParameter("sncode"));
		 	
	        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
	        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));

	        
	        SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Map<String,Object>> page = awardActivityLogService.findAwardActivityLogBylist(params, initPage(pageNo, pageSize));
	        List<Map<String,Object>> list=page.getContent();
	       
	        sp.setRowCnt((int) page.getTotalElements());
	        model.addAttribute("curMerchant", curMerchant);
	        model.addAttribute("list",list);
	        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	        model.addAttribute("page", sp);
	        model.addAttribute("search", params);
	        return "sys/award/activity/log";
	    }
	
	
	//活动新增，编辑
	@RequestMapping("/activity/edit")
    public String activityEdit(Model model,String id) throws Exception {
		AwardActivity awardActivity=new AwardActivity();
		if(StringUtils.isNotEmpty(id)) {
			awardActivity=awardActivityService.getById(id);
		}
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//当前商户是SSJ-FX商户,查询的是指点下商户
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);
	
		List<AwardMaterial> level1Materials=awardMaterialService.findAwardMaterialByLevel(1);//一等奖
		List<AwardMaterial> level2Materials=awardMaterialService.findAwardMaterialByLevel(2);//二等奖
		List<AwardMaterial> level3Materials=awardMaterialService.findAwardMaterialByLevel(3);//三等奖
		
		model.addAttribute("subMerchants", subMerchants);
		model.addAttribute("awardActivity", awardActivity);
		model.addAttribute("level1Materials", level1Materials);
		model.addAttribute("level2Materials", level2Materials);
		model.addAttribute("level3Materials", level3Materials);
        return "sys/award/activity/edit";
    }
	
	
	
	//活动新增，编辑，保存
	@RequestMapping("/activity/save")
	@ResponseBody
    public Response activitySave(Model model,AwardActivity awardActivity) throws Exception {
		 Response response = new  Response();
		 AwardActivity statusAwardActivity=awardActivityService.getAwardActivityByMerchantId(awardActivity.getMerchantId(),1);
		 if(statusAwardActivity!=null) {
			 response.failure("此商户已有活动发布中，请先取消发布中的活动，再重试。");
			 return response;
		 }
		 if(StringUtils.isNotEmpty(awardActivity.getId())) {
			 response.failure("抽奖活动不支持修改");
			 return response;
		 }
		 
		 if(StringUtils.isEmpty(awardActivity.getId())) {
			 awardActivity.setStatus(1);
			 awardActivity.setCreateTime(new Date());
		
			 boolean is=awardActivityService.createAwardActivityAndAwardStock(awardActivity);
			 if(is) {
				response.success("成功");
			 }else {
			 	response.failure("活动保存异常，请刷新后重试。");
			 }
		 }
		 return response;
    }
	
	
	
	//审核活动列表.只看指点的下级商户列表
	@RequestMapping("/examine/list")
    public String examineList(Model model,
			            @RequestParam(required = false, defaultValue = "30") int pageSize,
			            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
		
		List<Merchant> subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		
		List<String> subMerchantIds=new ArrayList<String>();
	 	Map<String, Object> params = new HashMap<String, Object>();
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			for (Merchant merchant : subMerchants) {
				subMerchantIds.add(merchant.getId());
			}
		}
		
        params.put("title", request.getParameter("title")==null?"":request.getParameter("title"));
        params.put("status", request.getParameter("status")==null?"":request.getParameter("status"));
        
        params.put("dingNumber", request.getParameter("dingNumber")==null?"":request.getParameter("dingNumber"));
        params.put("emsNumber", request.getParameter("emsNumber")==null?"":request.getParameter("emsNumber"));
        params.put("remarks", request.getParameter("remarks")==null?"":request.getParameter("remarks"));
        
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardGrantService.findAwardGrantBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("subMerchants",subMerchants);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/examine/list";
    }
	
	
	@RequestMapping("/examine/status")
	@ResponseBody
    public Response examineStatus(Model model,String id,Integer status) throws Exception {
		Response response = new  Response();
		AwardGrant awardGrant=awardGrantService.getById(id);
		if(awardGrant!=null) {
			if(status==1) {//通过成功，EMS发货才添加增量
				awardGrant.setStatus(status);
				awardGrant.setUpdateTime(new Date());
				awardGrantService.save(awardGrant);
			}else {
				awardGrantService.updateAwardGrantByStatus(awardGrant, status);
			}
		}
		response.success("成功");
		return response;
    }
	
	
		
	//活动状态更新=审核=发布=停止
	@RequestMapping("/activity/status")
	@ResponseBody
    public Response activityStatus(Model model,String id,Integer status) throws Exception {
		Response response = new  Response();
		AwardActivity awardActivity=awardActivityService.getById(id);
		if(awardActivity!=null) {
			awardActivityService.updateAwardActivityByStatus(awardActivity, status);
		}
		response.success("成功");
		return response;
    }
	
	
	
	//奖品消耗的列表，只看指点商户下的商户
	@RequestMapping("/consume/list")
    public String consumeList(Model model,
			            @RequestParam(required = false, defaultValue = "30") int pageSize,
			            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);

        Page<Map<String,Object>> awardMaterialPage = awardMaterialService.findAwardMaterialBylist(new HashMap<String, Object>(), initPage(1, 1000));
        List<Map<String,Object>> awardMaterials=awardMaterialPage.getContent();
		
		List<String> subMerchantIds=new ArrayList<String>();
		String isSSJ="0";
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			for (Merchant merchant : subMerchants) {
				subMerchantIds.add(merchant.getId());
			}
			isSSJ="1";
		}
		
	 	Map<String, Object> params = new HashMap<String, Object>();
	 	params.put("isSSJ", isSSJ);
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("type", request.getParameter("type")==null?"1":request.getParameter("type"));
        
        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        
        params.put("awardMaterialId", request.getParameter("awardMaterialId")==null?"":request.getParameter("awardMaterialId"));
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardConsumeService.findAwardConsumeBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("awardMaterials",awardMaterials);
        model.addAttribute("subMerchants",subMerchants);
        model.addAttribute("curMerchant", curMerchant);
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/consume/list";
    }
	
	
	
	//导出奖品消耗的列表，只看指点商户下的商户
	@RequestMapping("/consume/list_export")
    @ResponseBody
    public void consumeListExport(Model model) throws Exception {
		
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查出它的所有的级的商户列表。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants=merchantService.getMerchantByParentPosCode(curMerchant.getPosCode());
		}
		subMerchants.add(curMerchant);

		List<String> subMerchantIds=new ArrayList<String>();
		String isSSJ="0";
		if(request.getParameter("merchantId")!=null && StringUtils.isNotEmpty(request.getParameter("merchantId").toString())) {
			subMerchantIds.add(request.getParameter("merchantId").toString());
		}else {
			for (Merchant merchant : subMerchants) {
				subMerchantIds.add(merchant.getId());
			}
			isSSJ="1";
		}
		
	 	Map<String, Object> params = new HashMap<String, Object>();
	 	params.put("isSSJ", isSSJ);
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("type", request.getParameter("type")==null?"1":request.getParameter("type"));
        
        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        
        params.put("awardMaterialId", request.getParameter("awardMaterialId")==null?"":request.getParameter("awardMaterialId"));
        params.put("merchantId", String.join(";", subMerchantIds));
        
        Page<Map<String,Object>> page = awardConsumeService.findAwardConsumeBylist(params, initPage(1, 1000));
        List<Map<String,Object>> list=page.getContent();
       
        String libName="奖品消耗明细";
        ServletOutputStream os = response.getOutputStream(); //获得输出流  
		response.reset();   //清空输出流  
		String fileName = new String(libName.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");
		
        for (Map<String, Object> map : list) {
			switch (map.get("type").toString()) {
				case "1":map.put("type", "我向下配送");break;
				case "2":map.put("type", "上级向我配送");break;
				case "3":map.put("type", "活动消耗");break;
				case "4":map.put("type", "兑换消耗");break;
				case "5":map.put("type", "取消活动返库");break;
				case "6":map.put("type", "奖品入库");break;
				default:map.put("type", "");break;
			}
			switch (map.get("material_level").toString()) {
				case "1":map.put("material_level", "一等奖");break;
				case "2":map.put("material_level", "二等奖");break;
				case "3":map.put("material_level", "三等奖");break;
				default:map.put("material_level", "");break;
			}
		}
	    List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
		myColumns3.add(new ExcelColumn("始商户", "fm_unit_name", 20));
		myColumns3.add(new ExcelColumn("至商户", "tm_unit_name", 20));
		myColumns3.add(new ExcelColumn("操作类型", "type", 20));
		myColumns3.add(new ExcelColumn("奖品数量", "number", 20));
		myColumns3.add(new ExcelColumn("奖品名称", "material_name", 20));
		myColumns3.add(new ExcelColumn("奖品等奖", "material_level", 20));
		myColumns3.add(new ExcelColumn("操作时间", "create_time", 20));
		myColumns3.add(new ExcelColumn("备注", "remarks", 20));
    	CustomizeToExcel.downFile(myColumns3, list, os);
    }
	

	
	@RequestMapping("/sncode/list")
    public String sncodeList(Model model,
			            @RequestParam(required = false, defaultValue = "30") int pageSize,
			            @RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {

		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant curMerchant=merchantService.getMerchantByPosCode(admin.getLoginName());
		
		//当前商户是SSJ-FX商户,查询的是指点下商户
		//如果是SSJ_FX管理层的商户，直接查指点下级的商户列表。
		//如果不是SSJ_FX管理层的商户，直接查它自己的。
		List<Merchant> subMerchants=new ArrayList<Merchant>();
		if(SSJFX.equals(curMerchant.getOrgCode())) {
			//subMerchants=merchantService.getMerchantByParentPosCode(SSJCODE);
		}else {
			subMerchants.add(curMerchant);
		}
	
		List<String> subMerchantIds=new ArrayList<String>();
		for (Merchant merchant : subMerchants) {
			subMerchantIds.add(merchant.getId());
		}

	 	Map<String, Object> params = new HashMap<String, Object>();
        params.put("awardActivityId", request.getParameter("awardActivityId")==null?"":request.getParameter("awardActivityId"));
        params.put("awardMaterialId", request.getParameter("awardMaterialId")==null?"":request.getParameter("awardMaterialId"));
        params.put("snCode", request.getParameter("snCode")==null?"":request.getParameter("snCode"));
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("level", request.getParameter("level")==null?"":request.getParameter("level"));
        
        params.put("status", request.getParameter("status")==null?"":request.getParameter("status"));
        params.put("startTime", request.getParameter("startTime")==null?"":request.getParameter("startTime"));
        params.put("endTime", request.getParameter("endTime")==null?"":request.getParameter("endTime"));
        params.put("merchantId", String.join(";", subMerchantIds));
        
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String,Object>> page = awardSncodeService.findAwardSncodeBylist(params, initPage(pageNo, pageSize));
        List<Map<String,Object>> list=page.getContent();
       
        sp.setRowCnt((int) page.getTotalElements());
        model.addAttribute("list",list);
        model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
        return "sys/award/sncode/list";
    }
	
	
	//查询商户的信息
	@RequestMapping("/merchant/info")
	@ResponseBody
    public Response merchantInfo(Model model,String id) throws Exception {
		 Response response = new  Response();
		 Map<String , Object> data=new HashMap<String, Object>();
		 Merchant merchant=merchantService.getById(id);
		 data.put("merchant",merchant);
		 response.success(data,"成功");
		 return response;
    }
	

	
	
	
	
}
