package com.iamberry.wechat.handles.admin;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.OrderUtil;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.CashLog;
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.efast.EfastRentService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.reback.LoadRewardTaskService;
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;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.SendMessageUtil;
import org.apache.commons.collections.map.HashedMap;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.iamberry.wechat.service.ImberryConfig.INFORM_SHIPPING;
//import cn.jpush.api.common.connection.IHttpClient.RequestMethod;

@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;

    @Autowired
    private EfastRentService efastRentService;

    @Autowired
    private CodeService codeService;


    /**
     * 后台进入订单列表功能
     *
     * @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())); // 订单状态描述，中文

                // 遍历订单, 判断用户角色
                if (orders.getPlaceOpenID() != null && orders.getPlaceOpenID().equals(orders.getSalesOrderid())) {
                    // 金牌会员
                    orders.setUserResource("金牌会员");
                } else if (orders.getVipRole() != null && orders.getVipRole().equals("52") && orders.getUserResource().equals("3")) {
                    // 金牌会员直属下线
                    orders.setUserResource("金牌会员直属下线");
                } else {
                    // 会员
                    String role = "会员";
                    switch (Integer.parseInt(orders.getUserResource())) {
                        case 47:
                            role = "合伙人下线";
                            break;
                        case 48:
                            role = "门店下线";
                            break;
                        case 49:
                            role = "微代理下线";
                            break;
                        case 51:
                            role = "VIP会员下线";
                            break;
                        case 52:
                            role = "金牌会员下线";
                            break;
                        case 53:
                            role = "钻石下线";
                            break;
                        default:
                            break;
                    }
                    orders.setUserResource(role);
                }
            }
        } 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()));

                // 遍历订单, 判断用户角色
                if (orders.getPlaceOpenID() != null && orders.getPlaceOpenID().equals(orders.getSalesOrderid())) {
                    // 金牌会员
                    orders.setUserResource("金牌会员");
                } else if (orders.getVipRole() != null && orders.getVipRole().equals("52") && orders.getUserResource().equals("3")) {
                    // 金牌会员直属下线
                    orders.setUserResource("金牌会员直属下线");
                } else {
                    // 会员
                    String role = "会员";
                    switch (Integer.parseInt(orders.getUserResource())) {
                        case 47:
                            role = "合伙人下线";
                            break;
                        case 48:
                            role = "门店下线";
                            break;
                        case 49:
                            role = "微代理下线";
                            break;
                        case 51:
                            role = "VIP会员下线";
                            break;
                        case 52:
                            role = "金牌会员下线";
                            break;
                        case 53:
                            role = "钻石下线";
                            break;
                        default:
                            break;
                    }
                    orders.setUserResource(role);
                }
            }
        }
        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
     * @param type    1:销售订单
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_efast_order/{orderId}/{type}")
    public ResultMsg selectEfastOrder(HttpServletRequest request,
                                      @PathVariable("orderId") String orderId,
                                      @PathVariable("type") Integer type) throws Exception {
        //efast的订单编号
        String efastOrderId = request.getParameter("efastOrderId");

        ResultMsg msg = new ResultMsg();

        if (!cn.jpush.api.utils.StringUtils.isNotEmpty(orderId) || type == null) {
            msg.setMessage("订单号或类型为空!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        //获取队列中的map集合
        Map<String, Object> queuesMap = new HashedMap();
        String id = efastOrderId;
        String EsastType = "1";
        //查询efast系统该订单的状态
        Map<String, Object> map = efastRentService.getEfastSendOrderInfo(id,EsastType);
        if (!(boolean) map.get("status")) {
            msg.setData("");
            msg.setMessage(map.get("result").toString());
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        Order order = new Order();
        order.setSalesOrderid(orderId);
        order.setSalesStatus(5);
        order.setSalesPostFirm((String) map.get("postFirm"));
        order.setSalesPostNum((String) map.get("postNum"));
        order.setOldStatus(2);
        //order.set
        int flag = adminOrderService.updateOrderDeliver(order);
        if (flag < 1){
            msg.setData("");
            msg.setMessage("修改订单状态失败");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        Order or = new Order();
        or =  adminOrderService.getShopOrderByOrderId(orderId);
        Member member = memberService.getMemberByUserOpenId(or.getSalesOpenid());
        if (member == null || 1 == member.getUserStatus() || 0 == member.getUserStatus()){   //未关注或者取消关注的，将发送手机短信
            logger.info("短信通知："+ or.getSalesOpenid() +" 用户的订单已发货");
            String phone = or.getSalesAddressTel();
            codeService.informShipping(phone,INFORM_SHIPPING);
        }else if(2 == member.getUserStatus()){      //已关注的用户推送信息到公众号
            logger.info("公众号推送物流信息： "+ or.getSalesOpenid() +" 用户的订单已发货");
            //消息内容
            String data = ResultInfo.ORDERPACKAGETEMP;
            data = data.replaceFirst("firstValueOrder", ResultInfo.SHIPMENTMESSAGE)
                    .replaceFirst("orderIdValueOrder", orderId)
                    .replaceFirst("orderValuePackageId", SendMessageUtil.hashmap.get(map.get("postFirm")) + ":" + map.get("postNum"))
                    .replaceFirst("orderRemarkValue", ResultInfo.INTOSHOP);
            sendMessageUtil.sendTemplateMessageToOpenid(data, or.getSalesOpenid(), ResultInfo.PAGE_SHIPMENT + orderId, 2);
        }

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

    /**
     * 订单详细信息
     *
     * @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())); // 订单状态描述，中文
            if (order.getSalesStatus() == 2) {
                // 给百胜推送信息
                try {
                    MQMessage message = new MQMessage();
                    message.setServiceToMessage(orderId);
                    message.setServiceOtherMessage("efast.trade.detail.get");
                    message.setServiceIsSend(2);            // 没有推送的信息
                    message.setServiceStatus(1);            // 推送成功
                    message.setServiceType(1);                // 添加订单信息
                    message.setServiceHandlerObjectName("efastOrderServiceImpl");
                    message.setServiceHandlerMethodName("selectEfastSendOrderInfo");
                    mQservice.insertMQMessage(message);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else if (order.getSalesStatus() == 8) {
                // 给百胜推送信息
                try {
                    MQMessage message = new MQMessage();
                    message.setServiceToMessage(orderId);
                    message.setServiceOtherMessage("efast.order.return.info.fetch");
                    message.setServiceIsSend(2);            // 没有推送的信息
                    message.setServiceStatus(1);            // 推送成功
                    message.setServiceType(1);                // 添加订单信息
                    message.setServiceHandlerObjectName("efastOrderServiceImpl");
                    message.setServiceHandlerMethodName("selectEfastReturnOrderInfo");
                    mQservice.insertMQMessage(message);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            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");
        Order order = new Order();
        String orderStatus = request.getParameter("orderStatus");

        //url需要进行拼接，拼接的内容是页面上的时间条件
        StringBuffer url = new StringBuffer("/admin/order/selectShopOrderByOrderId?orderStatus=" + actionDto.getOrderStatus());

        // 判断是否输入数据
        if (!(actionDto.getText() == null || actionDto.getText().isEmpty())) {
            url.append("&text=" + actionDto.getText());
        }
        //分页并带条件查询接收参数
        String beginTime = request.getParameter("beginDate");
        String endTime = request.getParameter("endDate");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");


        String salesAddressTel = request.getParameter("salesAddressTel");
        String salesAddressName = request.getParameter("salesAddressName");
        String salesAddressInfo = request.getParameter("salesAddressInfo");
        if (salesAddressTel != null && !"".equals(salesAddressTel)) {
            order.setSalesAddressTel(salesAddressTel);
            mv.addObject("salesAddressTel", salesAddressTel);
            url.append("&salesAddressTel=" + salesAddressTel);
        }
        if (salesAddressName != null && !"".equals(salesAddressName)) {
            order.setSalesAddressName(salesAddressName);
            mv.addObject("salesAddressName", salesAddressName);
            url.append("&salesAddressName=" + salesAddressName);
        }
        if (salesAddressInfo != null && !"".equals(salesAddressInfo)) {
            order.setSalesAddressInfo(salesAddressInfo);
            mv.addObject("salesAddressInfo", salesAddressInfo);
            url.append("&salesAddressInfo=" + salesAddressInfo);
        }

        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.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);
        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(0).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: // 已支付、待发货（管理员的操作为：确认发货）

                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
                    }
                    //给用户发送消息-已发货的通知


                    //消息内容
                    String data = ResultInfo.ORDERPACKAGETEMP;
                    data = data.replaceFirst("firstValueOrder", ResultInfo.SHIPMENTMESSAGE)
                            .replaceFirst("orderIdValueOrder", orderId)
                            .replaceFirst("orderValuePackageId", SendMessageUtil.hashmap.get(actionDto.getPostFirm()) + ":" + actionDto.getPostNum())
                            .replaceFirst("orderRemarkValue", ResultInfo.INTOSHOP);
                    sendMessageUtil.sendTemplateMessageToOpenid(data, currentOrder.getSalesOpenid(), ResultInfo.PAGE_SHIPMENT + orderId, 2);

                    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, "驳回退款成功!", "驳回退款成功，订单进入待发货状态!"));
                        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);
                        //根据orderId查询订单所有信息
                        Order orderInfo = adminOrderService.getShopOrderByOrderId(orderId);
                        Member member = new Member();
                        //判断该订单是否用过余额支付，如果有，则退款后该支付的余额会退回到用户余额中
                        if (orderInfo != null && orderInfo.getBalancePayAmount() != null) {
                            member.setUserOpenid(orderInfo.getSalesOpenid());
                            member.setUserIncome(orderInfo.getBalancePayAmount());
                            adminOrderService.updateUserByUserId(member);
                            //将数据存入日志中
                            CashLog cashLog = new CashLog();
                            cashLog.setCashLogsOpenid(orderInfo.getSalesOpenid());
                            cashLog.setCashLogsOrderid(orderId);
                            cashLog.setCashLogsNum(orderInfo.getBalancePayAmount());
                            cashLog.setCashLogsType(1);
                            cashLog.setCashLogsIntroduction("退款");
                            cashLog.setCashLogsResType(5);
                            cashLog.setCashLogsCreateDate(new Date());
                            adminOrderService.addCashLog(cashLog);
                        }
                        rebackServices.updateStatus(rabackInfo);
                        mv.addObject("msgObj", new MessageDto(true, "订单退款成功", "恭喜您!订单退款成功，订单将封存!"));
                        updateRebate(order, 3);
                        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()));
                if (adminOrderService.updateOrderStatusByOrderId(order)) {
                    if (orderUtil.orderStatusIntToOrderStatusString(7).equals(actionDto.getToOrderStatus())) {
                        mv.addObject("msgObj", new MessageDto(true, "订单申请退货成功", "恭喜您！同意订单：" + orderId + "退货，等待收到货物后确认退货!"));
                    } else {
                        mv.addObject("msgObj", new MessageDto(true, "成功驳回订单退货", "订单：" + 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);

                    //根据orderId查询订单所有信息
                    Order orderInfo = adminOrderService.getShopOrderByOrderId(orderId);
                    Member memberInfo = new Member();
                    //判断该订单是否用过余额支付，如果有，则退款后该支付的余额会退回到用户余额中
                    if (orderInfo != null && orderInfo.getBalancePayAmount() != null) {
                        memberInfo.setUserOpenid(orderInfo.getSalesOpenid());
                        memberInfo.setUserIncome(orderInfo.getBalancePayAmount());
                        adminOrderService.updateUserByUserId(memberInfo);
                        //将数据存入日志中
                        CashLog cashLog = new CashLog();
                        cashLog.setCashLogsOpenid(orderInfo.getSalesOpenid());
                        cashLog.setCashLogsOrderid(orderId);
                        cashLog.setCashLogsNum(orderInfo.getBalancePayAmount());
                        cashLog.setCashLogsType(1);
                        cashLog.setCashLogsIntroduction("退货");
                        cashLog.setCashLogsResType(5);
                        cashLog.setCashLogsCreateDate(new Date());
                        adminOrderService.addCashLog(cashLog);
                    }

                    mv.addObject("msgObj", new MessageDto(true, "确认订单退货成功", "恭喜您！同意订单：" + orderId + "退货，订单关闭!"));
                    updateRebate(order, 3);
                    try {
                        MQMessage message = new MQMessage();
                        message.setServiceToMessage(orderId);
                        message.setServiceOtherMessage(currentOrder.getSalesPostFirm() + "-" + currentOrder.getSalesPostNum());
                        message.setServiceIsSend(2);            // 没有推送的信息
                        message.setServiceStatus(1);            // 推送成功
                        message.setServiceType(1);                // 添加订单信息
                        message.setServiceHandlerObjectName("efastOrderServiceImpl");
                        message.setServiceHandlerMethodName("returnOrderInfoToEfast");
                        mQservice.insertMQMessage(message);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    //推送金额变动消息
                    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.getConfig("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  插入返利到百胜失败==============");
                    }
                    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 + "换货，请收货后录入物流信息并同意换货!"));
                    } else {
                        mv.addObject("msgObj", new MessageDto(true, "驳回换货成功", "您已驳回订单：" + orderId + "换货，订单状态改为已发货!"));
                    }
                    return mv;
                } else {
                    mv.addObject("msgObj", new MessageDto(false, "对不起，取消订单失败", "对不起，取消订单失败，请稍后重试！"));
                    return mv;
                }
            default: // 报错

                mv.addObject("msgObj", new MessageDto(false, "对不起，操作有误", "对不起，您刚才的操作流程有误!"));
                return mv;
        }

        return mv;
    }

    /**
     * 修改返利表的返现状态
     *
     * @param order
     * @param status
     */
    public void updateRebate(Order order, int status) {
        RebackInfo rabackInfo = new RebackInfo();
        rabackInfo.setOrderId(order.getSalesOrderid());
        rabackInfo.setStatus(status);
        LoadRewardTaskService.updateStatus(rabackInfo);
    }

    /**
     * 订单备注
     *
     * @throws IOException
     */
    @RequestMapping(value = "/remark/{id}", produces = {"application/json;charset=UTF-8"})
    @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\":\"备注失败，请稍后重试!\"}";
        }
    }
}
