package com.iamberry.wechat.handles.receive;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.receive.ChargerReceive;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.face.receive.ChargReceiveService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.StitchAttrUtil;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wxm
 * Class Description: 免费领取充电器hander
 */
@Controller
@RequestMapping("/wechat/receive")
public class ChargReceiveHandler {

	@Autowired
	private ChargReceiveService chargReceiveService;
	@Autowired
	private PayService payService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ProductColorService productColorService;


//	private static String myOpenId = "oZ9pv02WMRQgyDVRY1a_daYecwHI";

	/**
	 *
	 * 查询免费领取列表页面
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/select_receive")
	public  ResultMsg selectReceive(HttpServletRequest request,
									  @RequestParam(value= "pageSize",defaultValue= "20" ,required=false) Integer pageSize,
									  @RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
									  @RequestParam(value = "totalNum", defaultValue = "0", required = false) Integer totalNum
									 ) throws Exception {
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		Member member = memberService.getMemberByUserOpenId(openId);
		if(member.getUserIdentity() !=1 ){	//不为上朵会员
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			remsg.setMessage("需要注册为上朵会员才能免费领取充电器！");
			return remsg;
		}

		ChargerReceive chargerReceive = new ChargerReceive();
		chargerReceive.setReceiveOpenId(openId);

		// 封装请求数据
		PageRequest<ChargerReceive> pageRequest = new PageRequest<>(chargerReceive, pageNO, pageSize, totalNum == 0);
		// 查询订单列表
		PagedResult<ChargerReceive> result = chargReceiveService.listChargerReceive(pageRequest);
		if (totalNum != 0) {
			result.setTotal(totalNum);
		}
		StitchAttrUtil.setPage(result);

		/*验证是否可以领取*/
		Boolean isReceive = false;
		Integer pickingNumber = 0;
		ChargerReceive verificaCR = new ChargerReceive();
		verificaCR.setReceiveOpenId(openId);
		verificaCR.setReceiveCreateTime(new Date());
		List<ChargerReceive> chargerReceiveList = chargReceiveService.getChargerReceiveList(verificaCR);
		if(chargerReceiveList == null || chargerReceiveList.size() < 1){
			isReceive = true;
		}else{
			pickingNumber = chargerReceiveList.size();
		}

		Map<String,Object> map = new HashMap<String, Object>();
		map.put("list",result.getDataList());
		map.put("isReceive",isReceive);
		map.put("pickingNumber",pickingNumber);

		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}

	/**
	 *
	 * 领取免费充电器
	 * @param request
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/charger_receive")
	public  ResultMsg chargerReceive(HttpServletRequest request,ChargerReceive chargerReceive) throws Exception {
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();

		Member member = memberService.getMemberByUserOpenId(openId); // 当前用户
		if(member.getUserIdentity() !=1 ){	//不为上朵会员
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			remsg.setMessage("需要注册为上朵会员才能免费领取充电器！");
			return remsg;
		}

		chargerReceive.setReceiveOpenId(openId);

		remsg.setResultCode(ResultInfo.ERRORCODE);
		remsg.setStatus(false);
		if(chargerReceive.getColorId() == null || chargerReceive.getColorName() == null || "".equals(chargerReceive.getColorName())){
			remsg.setMessage("请选择颜色");
			return remsg;
		}
		if(chargerReceive.getReceiveAddressInfo() == null || "".equals(chargerReceive.getReceiveAddressInfo()) ||
				chargerReceive.getReceiveAddressName() == null || "".equals(chargerReceive.getReceiveAddressName()) ||
				chargerReceive.getReceiveAddressTel() == null || "".equals(chargerReceive.getReceiveAddressTel())
				){
			remsg.setMessage("请选择收货地址");
			return remsg;
		}

		/*验证今年是否已经领取过了*/
		ChargerReceive verificaCR = new ChargerReceive();
		verificaCR.setReceiveOpenId(openId);
		verificaCR.setReceiveCreateTime(new Date());
		List<ChargerReceive> chargerReceiveList = chargReceiveService.getChargerReceiveList(verificaCR);
		Integer apparatusNumber = chargReceiveService.getApparatusNumber(openId);
		Integer num = 2000;
		if(chargerReceiveList == null || chargerReceiveList.size() < apparatusNumber){
			num = Integer.valueOf(systemService.selectOneShopRuleById(254).getRuleNum().intValue());	//10
		}else{
			num = Integer.valueOf(systemService.selectOneShopRuleById(255).getRuleNum().intValue()); 	//20
		}

		if(true){
			String orderId = OrderNOUtil.createOrderCode(member.getUserId());
			chargerReceive.setReceiveOrderId("mflq" + orderId);
			chargerReceive.setReceivePostage(num);
			chargerReceive.setReceiveStatus(1);	//1:代付款  2:已付款 3:已发货
			Integer flag = chargReceiveService.insert(chargerReceive);
			if(flag < 1){
				System.out.println("=========插入信息失败======");
				remsg.setMessage("领取失败!请稍后重试!");
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}

			SendPayDto dto = new SendPayDto();
			dto.setSuccess(false);
			// 发起支付
			PayResult result = payService.requestPay(chargerReceive.getReceiveOpenId(), chargerReceive.getReceiveOrderId(), chargerReceive.getReceivePostage(), "上朵领取充电器的邮费", NameUtils.getConfig("WECHAT_ORDER_BACK"));
			if (result.isPaySuccess()) {
				dto.setInfo(result.getPayData());
				dto.setSuccess(true);
				dto.setOrderId(chargerReceive.getReceiveOrderId());
				remsg.setData(dto);
			} else {
				dto.setInfo(result.getPayData());
				dto.setOrderId(chargerReceive.getReceiveOrderId());
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setData(dto);
				remsg.setStatus(false);
				return remsg;
			}
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			return remsg;
		}else{
			remsg.setMessage("您今年已经领取过一次了");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
	}

	/**
	 *
	 * 免费领取充电器页面
	 * @param request
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/select_charg_price")
	public  ResultMsg getChargPrice(HttpServletRequest request) throws Exception {
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();

		Member member = memberService.getMemberByUserOpenId(openId);
		if(member.getUserIdentity() !=1 ){	//不为上朵会员
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			remsg.setMessage("需要注册为上朵会员才能免费领取充电器！");
			return remsg;
		}

		/*验证今年是否已经领过了*/
		Boolean isReceive = false;
		Integer pickingNumber = 0;
		ChargerReceive verificaCR = new ChargerReceive();
		verificaCR.setReceiveOpenId(openId);
		verificaCR.setReceiveCreateTime(new Date());
		List<ChargerReceive> chargerReceiveList = chargReceiveService.getChargerReceiveList(verificaCR);
		Integer apparatusNumber = chargReceiveService.getApparatusNumber(openId);
		if(chargerReceiveList == null || chargerReceiveList.size() < apparatusNumber){
			isReceive = true;
		}else{
			pickingNumber = chargerReceiveList.size();
		}
		Integer num = 2000;
		if(isReceive){	//可以免费领取
			num = Integer.valueOf(systemService.selectOneShopRuleById(254).getRuleNum().intValue());
		}else{
			num = Integer.valueOf(systemService.selectOneShopRuleById(255).getRuleNum().intValue());
		}

		Map<String,Object> map = new HashMap<>();
		map.put("pickingNumber",pickingNumber);
		map.put("price",num);

		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}

	/**
	 *
	 * 查询是否支付成功
	 * @param request
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/select_pay")
	public  ResultMsg selectPay(HttpServletRequest request,String orderId) throws Exception {
		ResultMsg remsg=new ResultMsg();

		if(orderId == null){
			remsg.setMessage("查询出错!请稍后重试!");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}

		ChargerReceive chargerReceive = chargReceiveService.selectByOrderId(orderId);

		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(chargerReceive);
		return remsg;
	}

	/**
	 *
	 * 查询牙刷的所有颜色
	 * @param request
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/select_color")
	public  ResultMsg selectColor(HttpServletRequest request,
								  @RequestParam(value = "productId", defaultValue = "61") Integer productId) throws Exception {
		ResultMsg remsg=new ResultMsg();
		List<ProductColor> colorList = productColorService.getChargReceiveColor(productId);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(colorList);
		return remsg;
	}


}
