package com.iamberry.wechat.handles.admin;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

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

import com.iamberry.wechat.core.entity.OrderUtil;
import com.iamberry.wechat.tools.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.app.tool.log.RatFWLogger;
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.MessageDto;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderActionDto;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.reback.RebackInfo;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.face.relationship.WdRelationService;
import com.iamberry.wechat.handles.mq.MQServiceProxy;

@Controller
@RequestMapping("/admin/order")
public class AdminOrderHandlers {
	
	@Autowired
	private AdminOrderService adminOrderService;
	
	@Autowired
	private OrderUtil orderUtil;
	
	@Autowired
	private SendMessageUtil sendMessageUtil;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private WdRelationService wdRelationService;
	
	
	@Autowired
	private DealerRelationService dealerRelationService;
	
	@Autowired
	private PlaceInfoService placeInfoService;
	
	
	
	@Autowired
	private RatFWLogger logger;
	
	@Autowired
	private MQServiceProxy mQservice;
	
	@Autowired
	private RebackServices rebackServices;
	/**
	 * 后台进入订单列表功能
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/selectShopOrder")
	public ModelAndView selectShopOrder(HttpServletRequest request,
			@RequestParam(value= "pageSize",defaultValue= "20" ,required=false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO) throws Exception {
		ModelAndView mv = new ModelAndView("admin/order/orderList");
		String orderStatus = request.getParameter("orderStatus");
		if (orderStatus == null || "".equals(orderStatus)) {
			orderStatus = "paySuccess";
		}
		// 订单状态，数字标识
		int status = -1;
		if (!orderStatus.equals("allOrder")) {
			status = orderUtil.getOrderStatusByStr(orderStatus);
		}
		Order order = new Order();
		order.setSalesStatus(status);
		order.getPage().setPageSize(pageSize);
		order.getPage().setPageNumber(pageNO);
		order.getPage().initRecordBegin();
		List<Order> orderList = this.adminOrderService.selectShopOrder(order);
		// 订单是否按照状态查询的, 用于页面
		if (status == -1) {
			mv.addObject("orderListIsStatus", false);
			for (Order orders : orderList) {
				// 用户昵称编码
				if (orders.getUserNickname() != null && !orders.getUserNickname().isEmpty()) {
					orders.setUserNickname(URLDecoder.decode(orders.getUserNickname(), "UTF-8"));
				}
				// 获取用户的操作权限
				orders.setOperations(orderUtil.orderStatusToOperation(orders.getSalesStatus(), orders.getSalesOrderid()));
				orders.setOrderLinkStatus(orderUtil.orderStatusToString(orders.getSalesStatus())); // 订单状态描述，中文
			}
		} else {
			mv.addObject("orderListIsStatus", true);
			for (Order orders : orderList) {
				// 用户昵称编码
				if (orders.getUserNickname() != null && !orders.getUserNickname().isEmpty()) {
					orders.setUserNickname(URLDecoder.decode(orders.getUserNickname(), "UTF-8"));
				}
				// 获取用户的操作权限
				orders.setOperations(orderUtil.orderStatusToOperation(orders.getSalesStatus(), orders.getSalesOrderid()));
			}
		}
		mv.addObject("orderList", orderList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("orderStatus", status);// 订单状态
		mv.addObject("url", "/admin/order/selectShopOrder?orderStatus=" + orderStatus + "&pageSize=" + pageSize + "&pageNO=");
		mv.addObject("pageSize", this.adminOrderService.selectShopOrderCount(order));
		mv.addObject("orderStatusStr", orderUtil.orderStatusIntToOrderStatusString(status));// 订单状态描述（用于选中订单头）
		mv.addObject("orderLinkStatus", orderUtil.orderStatusToString(status));// 订单状态描述，中文（显示给用户看）
		mv.addObject("statusUrl", "/admin/order/selectShopOrder?bid=&sid=");
		return mv;
	}
	
	/**
	 * 订单详细信息
	 * @param request
	 * @param orderId
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/getShopOrderByOrderId/{orderId}")
	public ModelAndView getShopOrderByOrderId(HttpServletRequest request,
			@PathVariable("orderId") String orderId) throws Exception{
		ModelAndView mv = new ModelAndView("admin/order/order");
		if (null != orderId && !"".equals(orderId)) {
			Order order = this.adminOrderService.getShopOrderByOrderId(orderId);
			List<OrderItem> orderItemList = this.adminOrderService.getShopOrderItemByOrderId(orderId);
				// 用户昵称编码
				if (order.getUserNickname() != null && !order.getUserNickname().isEmpty()) {
					order.setUserNickname(URLDecoder.decode(order.getUserNickname(), "UTF-8"));
				}
				// 获取用户的操作权限
				order.setOperations(orderUtil.orderStatusToOperation(order.getSalesStatus(), order.getSalesOrderid()));
				order.setOrderLinkStatus(orderUtil.orderStatusToString(order.getSalesStatus())); // 订单状态描述，中文
			mv.addObject("order",order);
			mv.addObject("orderItemList", orderItemList);
		}
		return mv;
	}
	
	@RequestMapping(value="/selectShopOrderByOrderId")
	public ModelAndView selectShopOrderByOrderId(HttpServletRequest request, 
			@RequestParam(value= "pageSize",defaultValue= "20" ,required=false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO,
			OrderActionDto actionDto) throws Exception {
		ModelAndView mv = new ModelAndView("admin/order/orderList");
		String orderStatus = request.getParameter("orderStatus");
		
		// 判断是否输入数据
				if (!(actionDto.getText() == null || actionDto.getText().isEmpty())) {
					if (!request.getMethod().equalsIgnoreCase("post")) {
						String text = new String(actionDto.getText().getBytes("ISO-8859-1"), "UTF-8");
						actionDto.setText(text);
					}
				}
		//分页并带条件查询接收参数
		String beginTime = request.getParameter("beginDate");
		String endTime = request.getParameter("endDate");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		//url需要进行拼接，拼接的内容是页面上的时间条件
		StringBuffer url = new StringBuffer("/order/selectShopOrderByOrderId?orderStatus=" + actionDto.getOrderStatus() + "&text=" + actionDto.getText());
		if (null != beginTime && !"".equals(beginTime)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				actionDto.setBeginDate(format.parse(new String(beginTime.getBytes("ISO-8859-1"), "UTF-8")));
			} else {
				actionDto.setBeginDate(format.parse(beginTime));
			}
		}
		if (null != endTime && !"".equals(endTime)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				actionDto.setEndDate(format.parse(new String(endTime.getBytes("ISO-8859-1"), "UTF-8")));
			} else {
				actionDto.setEndDate(format.parse(endTime));
			}
		}
		if (null != actionDto.getBeginDate()) {
			url.append( "&beginDate=" + format.format(actionDto.getBeginDate()));
			mv.addObject("beginDate", format.format(actionDto.getBeginDate()));
		}
		if (null != actionDto.getEndDate()) {
			url.append("&endDate=" + format.format(actionDto.getEndDate()));
			mv.addObject("endDate", format.format(actionDto.getEndDate()));
		}
		url.append("&pageSize=" + pageSize + "&pageNO=");
		
		if (orderStatus == null || "".equals(orderStatus)) {
			orderStatus = "paySuccess";
		}
		// 订单状态，数字标识
		int status = -1;
		if (!orderStatus.equals("allOrder")) {
			status = orderUtil.getOrderStatusByStr(orderStatus);
		}
		Order order = new Order();
		order.setSalesStatus(status);
		order.setSalesOrderid(actionDto.getText());
		order.setBeginDate(actionDto.getBeginDate());
		order.setEndDate(actionDto.getEndDate());
		order.getPage().setPageSize(pageSize);
		order.getPage().setPageNumber(pageNO);
		order.getPage().initRecordBegin();
		List<Order> orderList = this.adminOrderService.selectShopOrderByOrderId(order);
		// 订单是否按照状态查询的, 用于页面
			if (status == -1) {
				mv.addObject("orderListIsStatus", false);
				for (Order orders : orderList) {
					// 用户昵称编码
					if (orders.getUserNickname() != null && !orders.getUserNickname().isEmpty()) {
						orders.setUserNickname(URLDecoder.decode(orders.getUserNickname(), "UTF-8"));
					}
					// 获取用户的操作权限
					orders.setOperations(orderUtil.orderStatusToOperation(orders.getSalesStatus(), orders.getSalesOrderid()));
					orders.setOrderLinkStatus(orderUtil.orderStatusToString(orders.getSalesStatus())); // 订单状态描述，中文
				}
			} else {
				mv.addObject("orderListIsStatus", true);
				for (Order orders : orderList) {
					// 用户昵称编码
					if (orders.getUserNickname() != null && !orders.getUserNickname().isEmpty()) {
						orders.setUserNickname(URLDecoder.decode(orders.getUserNickname(), "UTF-8"));
					}
					// 获取用户的操作权限
					orders.setOperations(orderUtil.orderStatusToOperation(orders.getSalesStatus(), orders.getSalesOrderid()));
				}
			}
		// 时间区间的处理
		String beginDateTime = "";
		SimpleDateFormat simple = null;
		if (actionDto.getBeginDate() != null) {
			simple = new SimpleDateFormat("yyyy-MM-dd");
			beginDateTime = simple.format(actionDto.getBeginDate());
		}
		String endDate = "";
		if (actionDto.getEndDate() != null) {
			if (simple == null) {
				simple = new SimpleDateFormat("yyyy-MM-dd");
			}
			endDate = simple.format(actionDto.getEndDate());
		}
		mv.addObject("orderList", orderList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("orderStatus", status);// 订单状态
		mv.addObject("url", url.toString());
		mv.addObject("pageSize", this.adminOrderService.selectShopOrderCount(order));
		mv.addObject("orderStatusStr", orderUtil.orderStatusIntToOrderStatusString(status));// 订单状态描述（用于选中订单头）
		mv.addObject("orderLinkStatus", orderUtil.orderStatusToString(status));// 订单状态描述，中文（显示给用户看）
		mv.addObject("statusUrl", "/admin/order/selectShopOrderByOrderId?bid=&sid=");
		mv.addObject("beginDate", beginDateTime);
		mv.addObject("endDate", endDate);
		mv.addObject("selectInput", actionDto.getText());
		return mv;
	}
	
	/**
	 * 操作订单
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/{action}/{orderId}")
	public synchronized ModelAndView actionOrder(
			@PathVariable("action") String action,
			@PathVariable("orderId") String orderId,
			OrderActionDto actionDto
			) throws Exception {
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		Order order = new Order();
		order.setSalesOrderid(orderId);
		// 订单状态，数字标识
		order.setSalesPostFirm(actionDto.getPostFirm());
		order.setSalesPostNum(actionDto.getPostNum());
		// 判断当前的订单，是否支持希望进行的操作
		Order currentOrder = adminOrderService.selectOrderStatusByOrderId(orderId);
		//获取当前订单订单项
		List<OrderItem> itemList = adminOrderService.getShopOrderItemByOrderId(orderId);

		Integer orderStatus = currentOrder.getSalesStatus();
		order.setOldStatus(orderStatus);
		if (!orderUtil.orderStatusIntToOrderStatusString(orderStatus).equals(actionDto.getOrderStatus())) {
			mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
			return mv;
		}
		switch (orderStatus) {
			case 0: // 取消的订单，不支持任何修改订单状态的操作
				
				mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，取消的订单不能操作!"));
				return mv;
			case 1: // 待支付（管理员存在操作权限：取消订单，如果取消订单，订单状态修改为0）
				
				if (!orderUtil.getOrderActin()[0].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(5).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
				// 执行修改操作
				if (adminOrderService.updateOrderStatusByOrderId(order)) {
					mv.addObject("msgObj", new MessageDto(true, "取消订单成功", "恭喜您！订单：" + orderId + "取消成功，本订单将不能操作!"));
					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
					return mv;
				}
			case 2: // 已支付、待发货（管理员的操作为：确认发货）
				System.out.println("orderUtil="+orderUtil);
				System.out.println("orderUtil.orderActin[2]="+orderUtil.getOrderActin()[2]);
				System.out.println("action="+action);
				if (!orderUtil.getOrderActin()[2].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(5).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				// 执行修改操作
				order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
				if (adminOrderService.deliverOrderByOrderId(order)) {
					mv.addObject("msgObj", new MessageDto(true, "操作成功", "请到百胜系统确认该订单是否已经确认，如果没有确认，该订单仍是待发货状态!"));
					logger.info("准备为用户推送模版信息!");
					// 给百胜推送信息
					try {
						MQMessage message = new MQMessage();
						message.setServiceToMessage(orderId);
						message.setServiceOtherMessage(actionDto.getPostFirm() + "-" + actionDto.getPostNum());
						message.setServiceIsSend(2);			// 没有推送的信息
						message.setServiceStatus(1); 			// 推送成功
						message.setServiceType(1); 				// 添加订单信息
						message.setServiceHandlerObjectName("efastOrderServiceImpl");
						message.setServiceHandlerMethodName("sendOrderInfoToEfast");
						mQservice.insertMQMessage(message);
					} catch (Exception e) {
						// TODO: handle exception
					}
					//给用户发送消息-已发货的通知
					
					/*发货推送*/
					Order newOrder = adminOrderService.selectOrderStatusByOrderId(orderId);
					try {
						sendMessageUtil.orderSendSuccess(
								"尊敬的用户，您的订单已发货，物流信息:",
								orderId,
								SendMessageUtil.getHashMap(newOrder.getSalesPostFirm()),
								newOrder.getSalesPostNum(),
								newOrder.getSalesAddressInfo(),
								ResultInfo.sendRemark1,
								newOrder.getSalesOpenid(),
								ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
						);
					} catch (Exception e) {
						logger.info("订单号："+ order.getSalesOrderid() +"的订单已发货，发送微信消息失败!");
					}
					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
					return mv;
				}
			case 3: // 退款申请中（管理员可以操作：确认退款）
				
				// 只有两种操作 : 确认退款、驳回退款
				if (orderUtil.getOrderActin()[4].equals(action)) {
					// 驳回退款
					
					if (!orderUtil.orderStatusIntToOrderStatusString(2).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
						mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
						return mv;
					}
					order.setSalesStatus(2);
					if (adminOrderService.updateOrderStatusByOrderId(order)) {// 驳回退款
						mv.addObject("msgObj", new MessageDto(true, "驳回退款成功!", "驳回退款成功，订单进入待发货状态!"));

						DecimalFormat df=new DecimalFormat("0.00");
						String payMoney = df.format((float)currentOrder.getSalesYetAmount()/100) + "元";
						try {
//							sendMessageUtil.orderRefundMsg(
//									"尊敬的用户，您的退款申请被退回",
//									payMoney,
//									itemList.get(0).getItemProductName(),
//									order.getSalesOrderid(),
//									ResultInfo.refundRejectRemark + ResultInfo.sendRemark1,
//									currentOrder.getSalesOpenid(),
//									ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
//							);
							sendMessageUtil.orderApplyRefund(
									"尊敬的用户，您的退款申请被退回",
									payMoney,
									itemList.get(0).getItemProductName(),
									order.getSalesOrderid(),
									currentOrder.getSalesReturnDes(),	//退款备注salesReturnDes
									ResultInfo.refundRejectRemark + ResultInfo.sendRemark1,
									currentOrder.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单驳回退款，发送微信消息失败!");
						}

						return mv;
					} else {
						mv.addObject("msgObj", new MessageDto(false, "对不起，驳回退款订单失败", "对不起，对不起，驳回退款订单失败，请稍后重试！"));
						return mv;
					}
				} else if (orderUtil.getOrderActin()[5].equals(action)) {
					// 同意退款 , 需要回滚积分
					
					if (!orderUtil.orderStatusIntToOrderStatusString(4).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
						mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
						return mv;
					}
					order.setSalesStatus(4);
					if (adminOrderService.updateOrderStatusByOrderId(order)) {
						//将返利表中待入账改为已入账
						RebackInfo rabackInfo = new RebackInfo();
						rabackInfo.setOrderId(order.getSalesOrderid());
						rabackInfo.setStatus(3);
						rebackServices.updateStatus(rabackInfo);
						mv.addObject("msgObj", new MessageDto(true, "订单退款成功", "恭喜您!订单退款成功，订单将封存!"));

						DecimalFormat df=new DecimalFormat("0.00");
						String payMoney = df.format((float)currentOrder.getSalesYetAmount()/100) + "元";
						try {
//							sendMessageUtil.orderRefundMsg(
//									"尊敬的用户，您的退款申请已通过",
//									payMoney,
//									itemList.get(0).getItemProductName(),
//									order.getSalesOrderid(),
//									ResultInfo.refundAgreeRemark + ResultInfo.sendRemark1,
//									currentOrder.getSalesOpenid(),
//									ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
//							);
							sendMessageUtil.orderApplyRefund(
									"尊敬的用户，您的退款申请已通过",
									payMoney,
									itemList.get(0).getItemProductName(),
									order.getSalesOrderid(),
									currentOrder.getSalesReturnDes(),	//退款备注salesReturnDes
									ResultInfo.refundAgreeRemark + ResultInfo.sendRemark1,
									currentOrder.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单同意退款，发送微信消息失败!");
						}

						return mv;
					} else {
						mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
						return mv;
					}
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
			case 4: // 已退款（管理员通过申请退款，此时订单任何人不能操作）
				
				mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已退款的订单不能操作!"));
				return mv;
			case 5: // 已发货（管理员不具有权限）
				
				mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，已发货的订单不能操作!"));
				return mv;
			case 6: // 申请退货中（只有管理员能操作 : 确认退货）
				
				if (!orderUtil.getOrderActin()[6].equals(action) && !orderUtil.getOrderActin()[10].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(7).equals(actionDto.getToOrderStatus())
						&& !orderUtil.orderStatusIntToOrderStatusString(5).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				// 执行修改操作
				order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));

				DecimalFormat df=new DecimalFormat("0.00");
				String payMoney = df.format((float)currentOrder.getSalesYetAmount()/100) + "元";

				if (adminOrderService.updateOrderStatusByOrderId(order)) {
					if(orderUtil.orderStatusIntToOrderStatusString(7).equals(actionDto.getToOrderStatus())){
						mv.addObject("msgObj", new MessageDto(true, "订单申请退货成功", "恭喜您！同意订单：" + orderId + "退货，等待收到货物后确认退货!"));

						int productNum = 0;
						for (OrderItem item : itemList) {
							productNum += item.getItemNum();
						}
						sendMessageUtil.orderApplyReturn(
								"尊敬的用户，您的退货申请已通过",
								orderId,
								orderId,
								itemList.get(0).getItemProductName(),
								productNum+"件",
								payMoney,
								ResultInfo.returnAgreeRemark,
								currentOrder.getSalesOpenid(),
								ResultInfo.ORDER_DETAIL+orderId
						);
					}else{
						mv.addObject("msgObj", new MessageDto(true, "成功驳回订单退货", "订单：" + orderId + "退货被驳回,状态返回已发货!"));

						int productNum = 0;
						for (OrderItem item : itemList) {
							productNum += item.getItemNum();
						}
						sendMessageUtil.orderApplyReturn(
								"尊敬的用户，您的退货申请被退回",
								orderId,
								orderId,
								itemList.get(0).getItemProductName(),
								productNum+"件",
								payMoney,
								ResultInfo.returnRejectRemark,
								currentOrder.getSalesOpenid(),
								ResultInfo.ORDER_DETAIL+orderId
						);
					}
					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
					return mv;
				}
			case 7: // 退货中（管理员具有操作能力:确认退货）
				
				if (!orderUtil.getOrderActin()[7].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(8).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				// 执行修改操作
				order.setSalesStatus(8);
				if (adminOrderService.updateOrderStatusByOrderId(order)) {
					//将返利表中待入账改为已入账
					RebackInfo rabackInfo = new RebackInfo();
					rabackInfo.setOrderId(order.getSalesOrderid());
					rabackInfo.setStatus(3);
					rebackServices.updateStatus(rabackInfo);
					mv.addObject("msgObj", new MessageDto(true, "确认订单退货成功", "恭喜您！同意订单：" + orderId + "退货，订单关闭!"));

					//推送金额变动消息
					Member member = memberService.getMemberByUserOpenId(currentOrder.getSalesOpenid());
					if(member != null || member.getUserResType() != null) {
						String toopenid = "";
						switch(member.getUserResType().intValue()){//用户来源
							case 2:		//用户来源	微代理
								WdRelation wdrelation = wdRelationService.getWdRelationByOpenid(currentOrder.getSalesOpenid());
								Member fatherMember = memberService.getMemberByUserId(wdrelation.getWdFirst());	//微代理父节点信息
								if(fatherMember != null && StringUtils.isNotEmpty(fatherMember.getUserOpenid())){
									toopenid = fatherMember.getUserOpenid();
								}
								break;
							case 3:		//用户来源	线下
								DealerRelation dealerrelation= dealerRelationService.getDealerRelationById(member.getUserDealers());
								int Dealerid = 0;
								if(dealerrelation!=null){
									if(dealerrelation.getDealerThird()!=null){ //第三极
										Dealerid = dealerrelation.getDealerThird();
									}else if(dealerrelation.getDealerSecond()!=null){ //第二级
										Dealerid = dealerrelation.getDealerSecond();
									}else if(dealerrelation.getDealerFifth()!=null){ //第一级
										Dealerid = dealerrelation.getDealerFifth();}
								}
								PlaceInfo fatherPlace = placeInfoService.getPlaceInfoById(Dealerid);//分销父节点信息
								if(fatherPlace!=null){
									toopenid = fatherPlace.getOpenid();
								}
								break;
						}
						//发送消息
//						String temp = ResultInfo.INCOMEREMINDTEMP;
//						temp = temp.replaceFirst("firstValueIamberry", ResultInfo.NEXTUSERTUIHUOMESSAGE)
//								.replaceFirst("accountValueIamberry",URLDecoder.decode( member.getUserNickname(), "UTF-8"))
//								.replaceFirst("timeValueIamberry", DateTimeUtil.format(new Date(),NameUtils.DATE_TIME_FORMAT))
//								.replaceFirst("typeValueIamberry", "用户退货")
//								.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
//						sendMessageUtil.sendTemplateMessageToOpenid(temp, toopenid, ResultInfo.TUIHUI_SHIPMENT,3);
					}
					
					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
					return mv;
				}
			case 8: // 订单退货，订单关闭（管理员收到货后，确认退货，订单状态修改为此，订单不对外提供操作能力）
				
				mv.addObject("msgObj", new MessageDto(false, "对不起，操作订单失败", "对不起，订单退货，订单关闭，本订单不能操作！"));
				return mv;
			case 9: // 换货中（管理员对申请换货的订单，确认换货时，订单状态为此，此时只有管理员具有操作权限，只能确认换货，录入物流信息，并重新计算订单关闭的时间，待入账积分的时间要修改）
				
				if (!orderUtil.getOrderActin()[9].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(5).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				// 执行修改操作
				if ("2".equals(currentOrder.getSalesProxyReward().toString())) {
					order.setSalesStatus(orderUtil.getOrderStatusByStr("inFinish"));
				} else {
					order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
				}
				if (adminOrderService.deliverOrderByOrderId(order)) {
					mv.addObject("msgObj", new MessageDto(true, "订单发货成功", "恭喜您！订单：" + orderId + "订单发货成功!"));
					try {
						MQMessage message = new MQMessage();
						message.setServiceToMessage(orderId);
						message.setServiceOtherMessage("efast.trade.new.add");
						message.setServiceIsSend(2);			// 没有推送的信息
						message.setServiceStatus(1); 			// 推送成功
						message.setServiceType(1); 				// 添加订单信息
						message.setServiceHandlerObjectName("efastOrderServiceImpl");
						message.setServiceHandlerMethodName("exchangeOrderInfoToEfast");
						mQservice.insertMQMessage(message);
					} catch (Exception e) {
						System.out.println("===========pay 201  插入返利到百胜失败==============");		
					}

					/*换货推送与发货一致*/
					Order newOrder = adminOrderService.selectOrderStatusByOrderId(orderId);
					try {
						sendMessageUtil.orderSendSuccess(
								"尊敬的用户，您的订单已发货，物流信息:",
								orderId,
								SendMessageUtil.getHashMap(newOrder.getSalesPostFirm()),
								newOrder.getSalesPostNum(),
								newOrder.getSalesAddressInfo(),
								ResultInfo.sendRemark1,
								newOrder.getSalesOpenid(),
								ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
						);
					} catch (Exception e) {
						logger.info("订单号："+ order.getSalesOrderid() +"的订单已发货，发送微信消息失败!");
					}

					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，订单发货失败", "对不起，订单发货失败，请稍后重试！"));
					return mv;
				}
			case 10: // 换货完成，当用户对换货中的订单，点击确认换货时，并录入物流信息，此订单进入已发货状态
				
				break;
			case 11: // 在订单为已发货时，用户具有的权限，用户申请换货
				
				if (!orderUtil.getOrderActin()[8].equals(action) && !orderUtil.getOrderActin()[11].equals(action)) {// 判断当前请求操作是否相符, 否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				if (!orderUtil.orderStatusIntToOrderStatusString(9).equals(actionDto.getToOrderStatus())
						&& !orderUtil.orderStatusIntToOrderStatusString(5).equals(actionDto.getToOrderStatus())) {// 判断请求修改的订单状态是否相符，否则提示不成功
					mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误，请按照系统流程操作！"));
					return mv;
				}
				// 执行修改操作
				if (!orderUtil.orderStatusIntToOrderStatusString(9).equals(actionDto.getToOrderStatus())) {
					if ("2".equals(currentOrder.getSalesProxyReward().toString())) {
						order.setSalesStatus(orderUtil.getOrderStatusByStr("inFinish"));
					} else {
						order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
					}
				} else {
					order.setSalesStatus(orderUtil.getOrderStatusByStr(actionDto.getToOrderStatus()));
				}
				if (adminOrderService.updateOrderStatusByOrderId(order)) {
					if(orderUtil.orderStatusIntToOrderStatusString(9).equals(actionDto.getToOrderStatus())){
						mv.addObject("msgObj", new MessageDto(true, "同意换货成功", "恭喜您！同意订单：" + orderId + "换货，请收货后录入物流信息并同意换货!"));
						try {
							sendMessageUtil.orderApplyBarter(
									"尊敬的用户，您的换货申请已通过。",
									orderId,
									itemList.get(0).getItemProductName(),
									ResultInfo.exchangeAgreeRemark,
									currentOrder.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+orderId
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单退货申请已通过，发送微信消息失败!");
						}

					}else{
						mv.addObject("msgObj", new MessageDto(true, "驳回换货成功", "您已驳回订单：" + orderId + "换货，订单状态改为已发货!"));
						try {
							sendMessageUtil.orderApplyBarter(
									"尊敬的用户，您的换货申请被退回。",
									orderId,
									itemList.get(0).getItemProductName(),
									ResultInfo.exchangeRejectRemark,
									currentOrder.getSalesOpenid(),
									ResultInfo.ORDER_DETAIL+orderId
							);
						} catch (Exception e) {
							logger.info("订单号："+ orderId +"的订单换货申请被退回，发送微信消息失败!");
						}

					}
					return mv;
				} else {
					mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
					return mv;
				}
			default: // 报错
				
				mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误!"));
				return mv;
		}
		
		return mv;
	}
	
	/**
	 * 订单备注
	 * @param actionDto
	 * @throws IOException 
	 */
	@RequestMapping("/remark/{id}")
	@ResponseBody
	public String orderRemark(OrderActionDto actionDto, @PathVariable("id") String orderId, HttpServletResponse response) throws IOException {
		String remark = "";
		// 订单备注
		if (actionDto.getRemarkColor() == null) {
			actionDto.setRemarkColor(1);
		}
		if (actionDto.getRemark() == null || actionDto.getRemark().isEmpty()) {
			return "{\"status\":\"false\",\"info\":\"备注信息不能为空!\"}";
		}
		if (actionDto.getRemark().length() > 100) {
			return "{'\"status\":\"false\",\"info\":\"备注信息不能超过100个字符!\"}";
		}
		//查询该订单的状态
		Order order = adminOrderService.selectOrderStatusByOrderId(orderId);
		if (null == order) {
			return "{\"status\":true,\"info\":\"该订单不存在!\"}";
		}
		if (!"8".equals(order.getSalesStatus().toString())) {
			remark = actionDto.getRemark();
		}
		// update到数据库
		if (adminOrderService.updateOrderAdminRemarkByOrderId(remark, orderId, actionDto.getRemarkColor())) {
			return "{\"status\":true,\"info\":\"备注成功!\"}";
		} else {
			return "{\"status\":\"false\",\"info\":\"备注失败，请稍后重试!\"}";
		}
	}

	/**
	 * 下载导出订单
	 */
	@ResponseBody
	@RequestMapping(value = "/download_order")
	public ModelAndView downloadOrder(HttpServletRequest request,Order order){
		List<Order> orderList = adminOrderService.getOrderListToExcel(order);

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 准备model
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("fileName", "Aiberle销售订单");	// 下载文件名称
		// 标题
		List<String> titles = new ArrayList<String>();
		titles.add("时间");
		titles.add("订单编号");
//		titles.add("产品类型");
		titles.add("产品名称");
		titles.add("产品颜色");
		titles.add("数量");
//		titles.add("订单金额");
		titles.add("支付金额");
		titles.add("订单状态");
		titles.add("优惠券使用");
		titles.add("收货人");
		titles.add("昵称");
		titles.add("手机号码");
		titles.add("地址");
		model.put("titles", titles);
		List<List<Object>> countexts = new ArrayList<List<Object>>();
		for (Order info : orderList) {
			Integer salesAmount = 0;	//总金额
			Integer salesYetAmount = info.getSalesYetAmount();	//总支付金额
			for (int i=0; i<info.getOrderItemList().size(); i++) {
				salesAmount += info.getOrderItemList().get(i).getItemNum()*info.getOrderItemList().get(i).getItemProductDiscount();
			}
			for (int j = 0; j < info.getOrderItemList().size() ; j++) {
				OrderItem item = info.getOrderItemList().get(j);

				List<Object> row = new ArrayList<Object>();
				row.add(info.getSalesCreateDate() == null ? "":formatter.format(info.getSalesCreateDate()));
				row.add(info.getSalesOrderid() == null ? "":info.getSalesOrderid());
//				row.add(item.getProductTypeName() == null ? "":item.getProductTypeName());
				row.add(item.getItemProductName() == null ? "":item.getItemProductName());
				row.add(item.getItemProductColor() == null ? "":item.getItemProductColor());
				row.add(item.getItemNum() == null ? "":item.getItemNum());

				if((j+1) >=  info.getOrderItemList().size()){
					Double dd = Double.valueOf(salesYetAmount);
					row.add(dd/100);  //订单金额
				}else{
					if(salesAmount > 0 ){
						Double itemPay =  Double.valueOf(info.getSalesYetAmount()) * (item.getItemNum()*item.getItemProductDiscount())/salesAmount;
						Integer itemDiscount = itemPay.intValue();
						Double dd = Double.valueOf(itemDiscount);
						row.add(dd/100);  //订单金额
						salesYetAmount -= itemDiscount;
					}else{
						row.add(0);  //订单金额
					}
				}

				String statusString = "";
				switch (info.getSalesStatus()){
					case 0:
						statusString = "取消订单";
						break;
					case 1:
						statusString = "待支付";
						break;
					case 2:
						statusString = "已支付、待发货";
						break;
					case 3:
						statusString = "退款申请中";
						break;
					case 4:
						statusString = "已退款";
						break;
					case 5:
						statusString = "已发货";
						break;
					case 6:
						statusString = "申请退货中";
						break;
					case 7:
						statusString = "退货中";
						break;
					case 8:
						statusString = "订单退货";
						break;
					case 9:
						statusString = "换货中";
						break;
					case 10:
						statusString = "换货完成";
						break;
					case 11:
						statusString = "申请换货中";
						break;
					case 12:
						statusString = "订单完成";
						break;
				}
				row.add(statusString);  //订单状态
				if(info.getCouponId() != null){
					row.add("是");
				}else{
					row.add("否");
				}
				row.add(info.getSalesAddressName() == null ? "":info.getSalesAddressName());
				try{
					row.add(info.getUserNickname() == null ? "":java.net.URLDecoder.decode(info.getUserNickname(), "UTF-8"));
				}catch (Exception e){
					row.add("");
				}
				row.add(info.getSalesAddressTel() == null ? "":info.getSalesAddressTel());
				row.add(info.getSalesAddressInfo() == null ? "":info.getSalesAddressInfo());
				countexts.add(row);
			}
		}
		model.put("varList", countexts);

		ObjectExcelView erv = new ObjectExcelView();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
		String name = "";
		if(order.getBeginDate() != null){
			name += sd.format(order.getBeginDate());
		}else{
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_MONTH,1);
			name += sd.format(calendar.getTime());
		}
		name += "-";
		if( order.getEndDate() != null){
			name += sd.format(order.getEndDate());
		}else{
			name += sd.format(new Date());
		}
		erv.setName(name);
		ModelAndView mv = new ModelAndView(erv, model);
		return mv;
	}

}
