package com.wechat.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
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.alipay.api.AlipayApiException;
import com.wechat.common.Constants;
import com.wechat.common.utils.StringsUtils;
import com.wechat.dao.RedisGoodsSaleDao;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeGoods;
import com.wechat.model.dbEntity.MdeOrders;
import com.wechat.model.requestDto.GoodsOrdersReq;
import com.wechat.model.requestDto.MdeOrdersReq;
import com.wechat.model.responseDto.ResultEntity;
import com.wechat.service.CommonService;
import com.wechat.service.MdeGoodsService;
import com.wechat.service.MdeInvoiceTitleService;
import com.wechat.service.MdeOrdersService;
import com.wechat.service.MdeVipPackageService;
import com.wechat.service.OrderService;
import com.wechat.service.VerificationCodeService;

@Controller
@RequestMapping(value = "order")
public class OrderController extends BaseController{

	@Autowired
	OrderService orderService;

	@Autowired
	VerificationCodeService verificationCodeService;

	@Autowired
	MdeInvoiceTitleService mdeInvoiceTitleService;

	@Autowired
	MdeVipPackageService mdeVipPackageService;
	
	@Autowired
	MdeOrdersService MdeOrdersService;
	
	@Autowired
	RedisGoodsSaleDao goodsRedisDao;
	
	@Autowired
	MdeGoodsService goodService;

	@Autowired
	CommonService commonService;

	/**
	 * 订单页初始化 -> 获取套餐信息,套餐价格信息,开票信息
	 * @param pkgId 套餐id
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<Map<String, Object>> initOrderPage(HttpServletRequest request, @RequestParam int pkgId) {
		String lang = commonService.getLanguage(request);
		String identityFlag = commonService.getIdentityFlag(request);
		Map<String, Object> maps = new HashMap<String, Object>();
		// 套餐内容
		maps.put("vipPackage", mdeVipPackageService.getPkgInfoById(pkgId, lang));
		// 开票信息
		maps.putAll(orderService.initInvoiceInfo(lang, identityFlag));
		return new ResultEntity<Map<String, Object>>(InfoMsg.SUCCESS_REQUEST, maps);
	}
	
	
	/**
	 * 确认订单-服务套餐
	 * 
	 * @param mdeOrders
	 * @param req
	 * @param rep
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping(value = "confirmOrder", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String, String>> confirmOrder(@Validated @RequestBody MdeOrdersReq mdeOrdersReq,
			HttpServletRequest req, HttpServletResponse rep) throws AlipayApiException, IOException {
		// 订单类别[0会员套餐订单 1个人服务,2企业服务,3商品购买，4积分兑换] 
		mdeOrdersReq.setType(Constants.ORDER_TYPE_VIP);
		
		Map<String, String> map = orderService.confirmOrder(mdeOrdersReq, req, rep);
		if (!map.isEmpty()) {
			return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, map);
		}
		return new ResultEntity<Map<String, String>>(InfoMsg.ERROR_SYSTEM_ERROR);
	}
	
	/**
	 * 支付宝支付 回调方法
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "aliPay_notify_url", method = RequestMethod.POST)
	@ResponseBody
	public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		orderService.aliPayNotify(request, response);
	}
	
	/**
	 * 微信支付 回调方法
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "weChat_notify_url", method = RequestMethod.POST)
	@ResponseBody
	public String weChatNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return orderService.weChatNotify(request, response);
	}
	
	
	/**
	 * 获取订单详情 订单信息, 套餐信息, 套餐价格信息, 开票信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getOrderDetail", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity<Map<String, Object>> getOrderDetail(HttpServletRequest request,  @RequestParam String orderId,  @RequestParam String type) throws Exception {
		String lang = commonService.getLanguage(request);
		String userCode = commonService.getUserCode(request);
		String identityFlag = commonService.getIdentityFlag(request);
		
		ResultEntity<Map<String, Object>> result = new ResultEntity<Map<String, Object>>();
		Map<String, Object> repMap = orderService.getOrderDetail(orderId, lang, userCode, identityFlag,type);

		result.setResult(repMap);
		return result;
	}
	
	/**
	 * 检查支付状态
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "checkPayStatus", method = RequestMethod.GET)
	@ResponseBody
	public String checkPayStatus(@RequestParam String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userCode = commonService.getUserCode(request);
		return orderService.checkPayStatus(orderId,userCode);
	}
	

	
//	/**
//	 * 退款
//	 * 
//	 * @param map
//	 * @param req
//	 * @param rep
//	 * @throws AlipayApiException
//	 */
//	@RequestMapping(value = "refund", method = RequestMethod.POST)
//	@ResponseBody
//	public ResultEntity<String> refund(@RequestBody Map<String, Object> map, HttpServletRequest req, HttpServletResponse rep)
//			throws AlipayApiException {
//		return orderService.refund(map, req, rep);
//	}
//
//	/**
//	 * 退款查询
//	 * 
//	 * @param map
//	 * @param req
//	 * @param rep
//	 * @throws AlipayApiException
//	 */
//	@RequestMapping(value = "queryRefund", method = RequestMethod.POST)
//	@ResponseBody
//	public ResultEntity<Map<String, String>> queryRefund(@RequestBody Map<String, Object> map, HttpServletRequest req, HttpServletResponse rep)
//			throws AlipayApiException {
//		return orderService.queryRefund(map, req, rep);
//	}
	
	/**
	 * 订单查询
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
	@RequestMapping(value = "queryOrder", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String, String>> queryOrder(@RequestBody Map<String, Object> map, HttpServletRequest req, HttpServletResponse rep)
			throws AlipayApiException {
		return orderService.queryOrder(map, req, rep);
	}
	
	/**
	 * 用户删除订单
	 * 
	 * @param orderId 订单号
	 */
	@RequestMapping(value = "deleteOrderByUser", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String, String>> deleteOrderByUser(@RequestBody Map<String, String> map, HttpServletRequest req){
		String orderId = map.get("orderId");
		String userCode = commonService.getUserCode(req);
		
		if(StringsUtils.isEmpty(orderId)) {
			return new ResultEntity<>(InfoMsg.ERROR_EMPTY_REQUEST);
		}
		int count = orderService.deleteOrderByUser(orderId,userCode);
		if (count < 1)
		{
			return new ResultEntity<>(InfoMsg.ERROR_DATA_UPDATE);
		}
		return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
	}
	
	
	/**
	 * 确认商品订单 
	 * 
	 * @param mdeOrders
	 * @param req
	 * @param rep
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping(value = "confirmGoodsOrder", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String, String>> confirmGoodsOrder(@Validated @RequestBody GoodsOrdersReq ordReq,
			HttpServletRequest req, HttpServletResponse rep) throws AlipayApiException, IOException {
		 ResultEntity<Map<String, String>> result = new ResultEntity<Map<String, String>>();
		// 订单类别[0会员套餐订单 1个人服务,2企业服务,3商品购买，4积分兑换] 
		
		Map<String, String> map = new HashMap<String, String>();
		
		String userCode = commonService.getUserCode(req);
		String identityFlag = commonService.getIdentityFlag(req);
		String lang = commonService.getLanguage(req);
    	//获取用户注册时间
		Date userCreatDate = commonService.getUserCreatDate(req);
		
		// 获取商品详情
		MdeGoods goodsDetail = goodService.getGoodsAllInfo(ordReq.getGoodsId());
		if(goodsDetail != null )
		{
			//购买资格验证
			ResultEntity<Boolean> checkEnt = orderService.checkQualification(goodsDetail, userCode, userCreatDate,ordReq);
			if(checkEnt.getResult())
			{
				//下订单
				MdeOrders mdeOrders = orderService.confirmGoodsOrder(ordReq, goodsDetail, userCode, identityFlag, lang);

				//下订单成功后计算销量并发起支付
				if(mdeOrders != null)
				{
					//新增订单计算销量
					if(StringsUtils.isEmpty(ordReq.getOrderId()))
					{
						//计算销量
						Integer goodsSale = goodService.getGoodsSale(goodsDetail.getGoodsId());
						//存入缓存 并设置30天过期
						goodsRedisDao.insertSaleNum(goodsDetail.getGoodsId(), goodsSale+mdeOrders.getGoodsNums());
					}
					
					//发起支付
					map = orderService.confirmOrderPay(mdeOrders,ordReq.getWxCode(), req, rep);
					if (!map.isEmpty()) {
						result.setResult(map);
					} else {
						result.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
					}
				} else {
					log.error("***************订单初始化异常*************");
					result.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
				}
			} else {
				result.setCode(checkEnt.getCode());
				result.setMsg(checkEnt.getMsg());
			}
		} else {
			log.error("***************商品不存在*************");
			result.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
		}

		return result;
	}
	

}
