package com.iamberry.wechat.handles.cart;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.bind.annotation.ResponseBody;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.ProbationOrderDto;
import com.iamberry.wechat.core.entity.probation.ProbationUserDto;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.order.ProbationShopOrderService;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.sendMsg.SendMessageUtil;
@Controller
@RequestMapping("/wechat/probationOrder")
public class ProbationOrderHandler {
	@Autowired
	private ProbationShopOrderService probationShopOrderService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private MQServiceProxy mQservice;
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private MemberService memberService;
	
	/**
	 *  获取会员试用订单
	 * @param request
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/membersProbationOrder",method = RequestMethod.POST)
	public ResultMsg membersProbationOrder(HttpServletRequest request) throws Exception {
		ResultMsg remsg=new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			remsg.setMessage(ResultInfo.loginOutError);
			remsg.setResultCode(ResultInfo.loginOutError);
			remsg.setStatus(false);
			return remsg;
		}
		List<ProbationOrderDto> probationOrderDtoList= probationShopOrderService.selectProbationOrderByOpenid(member.getUserOpenid());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("probationOrderDtoList", probationOrderDtoList);
		remsg.setData(map);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		return remsg;
	}
	
	/**
	 * 添加试用订单接口
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/addProbationOrder")
	public ResultMsg addProbationOrder(HttpServletRequest request, ProbationUserDto probationUserDto) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ProbationOrderDto probationOrderDto = new ProbationOrderDto();
		probationOrderDto.setProbationProductId(Integer.parseInt(probationUserDto.getPuserProductid()));
		probationOrderDto.setProbationReceiveTel(probationUserDto.getPuserTel());
		probationOrderDto.setProbationReceiveName(probationUserDto.getPuserName());
		probationOrderDto.setProbationAddressInfo(probationUserDto.getPuserAddress());
		String colorId = request.getParameter("colorId");
		if (colorId != null && !"".equals(colorId)) {
			probationOrderDto.setProbationColorId(Integer.parseInt(colorId));
		} else {
			resultMsg.setMessage("产品颜色id为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		if (member == null || member.getUserOpenid() == null || "null".equals(member.getUserOpenid())) {
			resultMsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		
		//查询用户信息
		Member user= memberService.getMemberByUserOpenId(member.getUserOpenid());
		
		//判断该手机号是否已经生成过订单，如果有，则不能再次申请
		int num = probationShopOrderService.selectProbationOrderCountByTel(probationOrderDto.getProbationReceiveTel());
		if (num > 0) {
			resultMsg.setMessage("该用户有试用订单，不能再次申请");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		
		probationOrderDto.setProbationOpenid(member.getUserOpenid());
		//生成订单orderId
		probationOrderDto.setProbationOrderid(OrderNOUtil.createOrderCode(member.getUserId()));
		
		if (probationOrderDto == null || probationOrderDto.getProbationProductId() == null || "".equals(probationOrderDto.getProbationProductId())) {
			resultMsg.setData(0);
			resultMsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setStatus(false);
			return resultMsg;
		}
		
		//查询商品信息
		Product product = probationShopOrderService.selectProductInfo(probationOrderDto.getProbationProductId(),probationOrderDto.getProbationColorId());
		if (product == null) {
			resultMsg.setData(0);
			resultMsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setStatus(false);
			return resultMsg;
		}
		// 不再优惠
		probationOrderDto.setProbationYetAmount(product.getProductDiscount());
		probationOrderDto.setProbationAmount(product.getProductDiscount());
		probationOrderDto.setProbationStatus(1);
		probationUserDto.setPuserOpenid(member.getUserOpenid());
		
		//添加试用人信息
		probationShopOrderService.addProbationUser(probationUserDto);
		//将信息加入到试用订单表中
		probationShopOrderService.addProbationOrder(probationOrderDto);
		
		try {
			MQMessage message = new MQMessage();
			message.setServiceToMessage(probationOrderDto.getProbationOrderid());
			message.setServiceOtherMessage("efast.trade.new.add");
			message.setServiceIsSend(2);			// 没有推送的信息
			message.setServiceStatus(1); 			// 推送成功
			message.setServiceType(1); 				// 添加订单信息
			message.setServiceHandlerObjectName("efastOrderServiceImpl");
			message.setServiceHandlerMethodName("addProbationOrderToEfast");
			mQservice.insertMQMessage(message);
		} catch (Exception e) {
			System.out.println("===========试用订单插入mq表失败==============");		
		}
		
		try {
			//试用订单生成，给试用人推送消息
			sendMessageUtil.probationApplyNotice(ResultInfo.PROBATION_START_FIRST, product.getProductName(),probationOrderDto.getProbationOrderid(), ResultInfo.PROBATION_END_FIRST, probationOrderDto.getProbationOpenid(), ResultInfo.TRY_ORDER_DETAIL+"?orderId="+probationOrderDto.getProbationOrderid());
		} catch (Exception e) {
			System.out.println("试用订单生成，消息提示失败！");
		}
		try {
			//查询上级商户层信息
			PlaceInfo placeInfo = placeInfoService.selectPlaceByPlacePids(user.getUserDealers());
			//试用订单生成，给上级商户层推送消息
			if (placeInfo.getOpenid() != null && !"".equals(placeInfo.getOpenid())) {
				sendMessageUtil.probationApplyNotice(ResultInfo.ADDPROBATIONORDER, product.getProductName(),format.format(new Date()), "", placeInfo.getOpenid(),null);
			}
		} catch (Exception e) {
			System.out.println("===========试用订单生成，给上级商户推送消息失败==============");
		}
		
		resultMsg.setData(1);
		resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
		resultMsg.setStatus(true);
		return resultMsg;
	}
	
	/**
	 * 发送手机验证码
	 * @param phone 手机号 
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/send_code", method = RequestMethod.GET)
	@ResponseBody
	private ResponseJson sendCode(@RequestParam("phone") String phone) {
		//amqtask.probationRewardPush();
		ResponseJson json = new ResponseJson();
		json =	codeService.sendCode(phone);
		return json;
	}
	/**
	 * 手机号验证
	 * @param phone 手机号 
	 * @param code 验证码 
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/validation_code", method = RequestMethod.GET)
	@ResponseBody
	private ResponseJson sendCode(@RequestParam("phone") String phone,@RequestParam("code") String validationCode) {
		ResponseJson json =	codeService.validCode(phone,validationCode);
		return json;
		
	}
}
