package com.iamberry.wechat.handles.admin;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.Page;
import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.banner.MessageDTO;
import com.iamberry.wechat.core.entity.giftCard.AgentInfo;
import com.iamberry.wechat.core.entity.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.giftCard.CardCashInfo;
import com.iamberry.wechat.core.entity.giftCard.GiftCardPayCode;
import com.iamberry.wechat.core.entity.giftCard.UserMachineInfo;
import com.iamberry.wechat.face.giftCard.AgentMachineService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.giftCard.GiftCardPayCodeService;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.tools.ResponseJson;

/**
 * 礼品卡后台管理
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2017年2月16日
 */
@Controller
@RequestMapping("/admin/card")
public class AdminGiftCardHandler {
	
	@Autowired
	private GiftCardService cardService;
	@Autowired
	private AgentMachineService agentMachineService;
	@Autowired
	private AgentService agentService;
	@Autowired
    private GiftCardPayCodeService payCodeService;
	/**
	 * 礼品卡列表
	 * @return
	 * @author 献
	 * @Time   2017年2月16日
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, 
			@RequestParam(value = "pageNO", required = false, defaultValue = "1") Integer pageNO) throws Exception {
		ModelAndView mv = new ModelAndView("admin/giftCard/list");
		List<UserMachineInfo> list = cardService.page(pageNO, pageSize);
		//将昵称转码
		if (list != null && list.size() > 0) {
			for (UserMachineInfo userMachineInfo : list) {
				if (StringUtils.isNotEmpty(userMachineInfo.getUserNickName())) {
					userMachineInfo.setUserNickName(URLDecoder.decode(userMachineInfo.getUserNickName(),"UTF-8"));
				}
			}
		}
		mv.addObject("list", list);
		mv.addObject("pageSize", PaperBean.justPaperCount(cardService.count(), pageSize));
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", "/admin/card/list?pageSize=" + pageSize + "&pageNO=");
		return mv;
	}
	
	/**
	 * 兑换发货
	 * @return
	 * @author 献
	 * @Time   2017年2月17日
	 */
	@ResponseBody
	@RequestMapping("/send")
	public ResponseJson send(@RequestParam("postNum") String postNum,
			@RequestParam("postFirm") String postFirm,
			@RequestParam("userMachineId") Integer userMachineId) {
		UserMachineInfo info = new UserMachineInfo();
		info.setUserMachineId(userMachineId);
		info.setUserMachinePostNum(postNum);
		info.setUserMachinePostName(postFirm);
		info.setUserMachineStatus(2);
		
		int i = cardService.update(info);
		
		if (i<=0) {
			ResponseJson json = new ResponseJson();
			json.setResultCode(200);
			json.setReturnCode(500);
			return json;
		} else {
			ResponseJson json = new ResponseJson();
			json.setResultCode(200);
			json.setReturnCode(200);
			return json;
		}
	}

	/**
	 * 分页查询礼品卡兑现的记录
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/selectCardCashList")
	public ModelAndView selectCardCashList(HttpServletRequest request,
			@RequestParam(value = "pageSize", required = false, defaultValue = "2") Integer pageSize, 
			@RequestParam(value = "pageNO", required = false, defaultValue = "1") Integer pageNO) throws Exception {
		
		ModelAndView mv = new ModelAndView("admin/giftCard/cardCashList");
		StringBuilder url = new StringBuilder("/admin/card/selectCardCashList?pageSize=" + pageSize);
		CardCashInfo cardCashInfo = new CardCashInfo();
		
		String nickName = request.getParameter("nickName");
		String agentTel = request.getParameter("agentTel");
		String cardPassword = request.getParameter("cardPassword");
		String cardCashStatus = request.getParameter("cardCashStatus");
		
		if (StringUtils.isNotEmpty(nickName)) {
			mv.addObject("nickName", nickName);
			url.append("&nickName=" + nickName);
			cardCashInfo.setCardCashSalesNickname(URLEncoder.encode(nickName, "UTF-8"));
		}
		if (StringUtils.isNotEmpty(agentTel)) {
			mv.addObject("agentTel", agentTel);
			url.append("&agentTel=" + agentTel);
			cardCashInfo.setAgentTel(agentTel);
		}
		if (StringUtils.isNotEmpty(cardPassword)) {
			mv.addObject("cardPassword", cardPassword);
			url.append("&cardPassword=" + cardPassword);
			cardCashInfo.setCardPassword(cardPassword);
		}
		if (StringUtils.isNotEmpty(cardCashStatus)) {
			mv.addObject("cardCashStatus", cardCashStatus);
			url.append("&cardCashStatus=" + cardCashStatus);
			cardCashInfo.setCardCashStatus(Integer.parseInt(cardCashStatus));
		}
		
		cardCashInfo.getPage().setPageNumber(pageNO);
		cardCashInfo.getPage().setPageSize(pageSize);
		cardCashInfo.getPage().initRecordBegin();
		
		//分页查询礼品卡兑现列表
		List<CardCashInfo> cardCashList = cardService.selectCardCashList(cardCashInfo);
		
		if (cardCashList != null && cardCashList.size() > 0) {
			for (CardCashInfo cardCash : cardCashList) {
				cardCash.setCardCashSalesNickname(URLDecoder.decode(cardCash.getCardCashSalesNickname(), "UTF-8"));
			}
		}
		url.append("&pageNO=");
		mv.addObject("cardCashList", cardCashList);
		mv.addObject("pageSize", cardService.selectCardCashCount(cardCashInfo));
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url.toString());
		return mv;
	}
	
	/**
	 * 审核礼品卡兑现方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/checkCash",produces = {"application/json;charset=UTF-8"})
	public boolean checkCash(HttpServletRequest request) throws Exception {
		
		CardCashInfo cardCashInfo = new CardCashInfo();
		String cardCashStatus = request.getParameter("cardCashStatus");
		String cardCashRemark = request.getParameter("cardCashRemark");
		String cardCashId = request.getParameter("cardCashId");
		
		if (StringUtils.isNotEmpty(cardCashStatus)) {
			cardCashInfo.setCardCashStatus(Integer.parseInt(cardCashStatus));
		}
		if (StringUtils.isNotEmpty(cardCashId)) {
			cardCashInfo.setCardCashId(Integer.parseInt(cardCashId));
		}
		if (StringUtils.isNotEmpty(cardCashRemark)) {
			cardCashInfo.setCardCashRemark(cardCashRemark);
		}
		cardCashInfo.setCardCashOldStatus(1);
		//根据状态和id修改兑现记录状态
		Integer num = cardService.updateCardCashStatus(cardCashInfo);
		if (num > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 跳转到添加礼品卡页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addCardInfo")
	public ModelAndView addCardInfo(HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("admin/giftCard/addCard");
		return mv;
	}
	
	/**
	 * 查询所有付费代理商信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectAgentList")
	public ResultMsg selectAgentList(HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		//查询所有付费代理商信息
		List<AgentInfo> agentList = agentService.selectAgentList();
		if (agentList != null && agentList.size() > 0) {
			for (AgentInfo agentInfo : agentList) {
				agentInfo.setAgentNickname(URLDecoder.decode(agentInfo.getAgentNickname(), "UTF-8"));
			}
			msg.setData(agentList);
			msg.setStatus(true);
		} else {
			msg.setStatus(false);
		}
		
		return msg;
	}
	
	/**
	 * 批量生成礼品卡信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveCardList")
	public ModelAndView saveCardList(HttpServletRequest request) throws Exception {
		String openId = request.getParameter("openId");
		String cardNum = request.getParameter("cardNum");
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		
		if (!StringUtils.isNotEmpty(openId)) {
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败,openId为空！"));
			return mv;
		}
		if (!StringUtils.isNotEmpty(cardNum)) {
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败,礼品卡数量为空！"));
			return mv;
		}
		//批量添加礼品卡
		boolean flag = cardService.saveCardList(openId, Integer.parseInt(cardNum));
		if (flag) {
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加成功！"));
		} else {
			mv.addObject("msgObj", new MessageDTO(true, "操作结果", "添加失败！"));
		}
		return mv;
	}
	
	
	/**
	 * 兑换入口 - 页面
	 * @return
	 * @author 献
	 * @Time   2017年2月15日
	 */
	@RequestMapping(value = "/deliveryUI")
	public ModelAndView exchangeUI(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String agentMachineId = request.getParameter("agentMachineId");
		String agentMachineStatus = request.getParameter("agentMachineStatus");
		mv.addObject("agentMachineId", agentMachineId);
		mv.addObject("agentMachineStatus", agentMachineStatus);
		mv.setViewName("/admin/giftCard/deliveryUI");
		return mv;
	}
	
	/**
	 * 物流信息列表（后台）
	 * @param pageNO
	 * @param pageSize
	 * @param agentMachineStatus
	 * @param request
	 * @return
	 * @author LJK
	 * @Time   2017年2月16日
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/agentMachineList")
	public ModelAndView agentMachineList(
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize,
			HttpServletRequest request) throws Exception {
		AgentMachine agentMachine = new AgentMachine();
		ModelAndView mv = new ModelAndView();
		Page page = new Page();
		
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		String agentMachineStatus = request.getParameter("agentMachineStatus");
		StringBuilder url = new StringBuilder("/admin/card/agentMachineList?pageSize=" + pageSize);
		if (agentMachineStatus != null && !"".equals(agentMachineStatus)) {
			agentMachine.setAgentMachineStatus(Integer.valueOf(agentMachineStatus));//赠送状态
			url.append("&agentMachineStatus=" + agentMachineStatus);
			mv.addObject("agentMachineStatus", agentMachineStatus);
		}
		if (beginDate != null && !"".equals(beginDate)) {
			agentMachine.setBeginDate(beginDate);
			url.append("&beginDate=" + beginDate);
			mv.addObject("beginDate", beginDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			agentMachine.setEndDate(endDate);
			url.append("&endDate=" + endDate);
			mv.addObject("endDate", endDate);
		}
		page.setPageNo((pageNO - 1) * pageSize);
		int count = agentMachineService.selectAllAgentMachineCount(agentMachine);
		int pageCount = count % pageSize == 0 ? count / pageSize : count
				/ pageSize + 1;
		page.setPageSize(pageSize);
		agentMachine.setPage(page);
		List<AgentMachine> agentMachineList = agentMachineService.selectAllAgentMachine(agentMachine);

		url.append("&pageNO=");
		mv.addObject("agentMachineList", agentMachineList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("pageSize", pageCount);
		mv.addObject("url", url);
		mv.setViewName("/admin/giftCard/agentMachineList");
		return mv;
	}
	
	/**
	 * 进行发货操作
	 * @return
	 * @author LJK
	 * @Time   2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/updateAgentMachineStatus")
	public ResponseJson updateAgentMachineStatus(HttpServletRequest httpServletRequest,AgentMachine agentMachine) {
		ResponseJson json = new ResponseJson();
		if (agentMachine == null) {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		if(agentMachine.getAgentMachineStatus() == 1){
			agentMachine.setAgentMachineStatus(2);
		}
		Integer msg = agentMachineService.updateAgentMachine(agentMachine);
		if(msg > 0){
			json.setResultCode(200);
			json.setReturnCode(200);
			json.addResponseKeyValue("操作成功！");
		}else{
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
		}
		return json;
	}
	
	/**
	 * 进入批量添加抵扣密码页面
	 * 2017年3月15日
	 * @author muzx
	 * @return
	 */
	@RequestMapping("/pay_code_list")
	public ModelAndView toAddPayCodeList(
	        @RequestParam(value = "pageSize", required = false, defaultValue = "8") Integer pageSize, 
            @RequestParam(value = "pageNO", required = false, defaultValue = "1") Integer pageNO){
	    ModelAndView mv = new ModelAndView("admin/giftCard/payCodeList");
	    
	    GiftCardPayCode payCode = new GiftCardPayCode();
	    payCode.getPage().setPageSize(pageSize);
	    payCode.getPage().setPageNumber(pageNO);
	    List<GiftCardPayCode> list = payCodeService.listPayCode(payCode);
	    
        //将昵称转码
        if (list != null) {
            for (GiftCardPayCode code : list) {
                    try {
                        if (StringUtils.isNotEmpty(code.getCodeReferrerName())) {
                            code.setCodeReferrerName(URLDecoder.decode(code.getCodeReferrerName(),"UTF-8"));
                        }
                        if (StringUtils.isNotEmpty(code.getCodeUseOpenName())) {
                            code.setCodeUseOpenName(URLDecoder.decode(code.getCodeUseOpenName(),"UTF-8"));
                        }
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
            }
        }
        
        int count = payCodeService.countPayCode();
        int pageCount =  count % payCode.getPage().getPageSize() == 0 ? count/payCode.getPage().getPageSize():(count/payCode.getPage().getPageSize()) + 1;
        //分页用
        mv.addObject("list", list);
        mv.addObject("pageNO", pageNO);
        mv.addObject("pageSize", pageCount);
        mv.addObject("url", "/admin/card/pay_code_list?pageSize=" + pageSize + "&pageNO=");
        return mv;
	}
	/**
     * 生成抵扣密码并加入到数据库中
     * 2017年3月3日
     * @author muzx
     * @return
     */
    @RequestMapping("/add_pay_password")
    @ResponseBody
    public ResultMsg getPayPassword(HttpServletRequest req){
        ResultMsg rm = new ResultMsg();
        rm.setStatus(false);
        rm.setMessage("操作有误!");
        rm.setResultCode("400");
        String num = req.getParameter("payCodeNum");
        String openId = req.getParameter("openId");
        
        if(StringUtils.isEmpty(openId) && StringUtils.isEmpty(num)){
            return rm;
        }
        payCodeService.insertPayCodeList(openId, StringUtils.isEmpty(num) ? 1 : Integer.parseInt(num));
        rm.setStatus(true);
        rm.setData("");
        rm.setResultCode("200");
        rm.setMessage("");
        return rm;
    }
    
}
