JSON 解析(门店)

package com.j1.mai.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import com.j1.base.order.model.*;
import com.j1.mai.dto.base.Goods;
import com.j1.mai.util.JsonUtils;
import com.j1.model.User;
import com.j1.pay.model.oracle.OrderPaymentLog;
import com.j1.pay.model.oracle.OrderPaymentTypeList;
import com.j1.soa.common.MemberKeyUtils;
import com.j1.soa.resource.cms.api.PageIndexImgService;
import com.j1.soa.resource.item.api.GoodsDetailService;

import com.j1.soa.resource.pay.oracle.api.OrderPaymentLogService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.j1.base.dto.ServiceMessage;
import com.j1.base.page.Page;
import com.j1.base.type.MsgStatus;
import com.j1.base.type.PageIndexType;
import com.j1.base.type.SiteType;
import com.j1.cms.model.PageIndexImg;
import com.j1.mai.common.Const;
import com.j1.mai.model.common.SoaApiBaseAction;
import com.j1.mai.service.CheckMemberKeyService;
import com.j1.mai.util.NumericUtil;
import com.j1.mai.util.StringUtil;
import com.j1.soa.common.ResultMsg;
import com.j1.soa.resource.order.api.LogisticCompanyService;
import com.j1.soa.resource.order.api.OrderInfoService;
import com.j1.soa.resource.order.api.OrderItemService;
import com.j1.soa.resource.order.api.OrderLogService;
import com.j1.soa.resource.pay.api.PayQueryService;

/**
 * SOA 订单 HTTP 接口
 *
 * @author qiaoyu
 */
@Controller
@Scope("request")
@RequestMapping("/order")
public class OrderAction extends SoaApiBaseAction {

    static final Logger LOG = Logger.getLogger(OrderAction.class);

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderLogService orderLogService;
    @Autowired
    private LogisticCompanyService logisticCompanyService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private GoodsDetailService goodsDetailService;
    @Autowired
    private PayQueryService payQueryService;
    @Autowired
    private CheckMemberKeyService checkMemberKeyService;
    @Autowired
    private PageIndexImgService pageIndexImgService;

    /**
     * 查询订单列表
     *
     * @param request
     * @param response
     * @param mul
     *            来源
     * @param orderState
     *            订单状态
     * @param pageNum
     *            页数
     * @param pageSize
     *            每页条数
     * @date 25/11/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/list")
    public void list(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderState", required = false) String orderState,
            @RequestParam(value = "pageNum", required = false) String pageNum,
            @RequestParam(value = "goodsSeller", required = false) String goodsSeller,
            @RequestParam(value = "pageSize", required = false) String pageSize) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        if (StringUtil.isEmpty(memberKey)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.Common.MEMBER_KEY_EMPTY).write(request, response);
            return;
        }
        // PARAMTER VALIDATION END

        OrderInfo queryParams = new OrderInfo();
        queryParams.setMemberKey(memberKey);
        queryParams.setMul(mul);
        queryParams.setOrderStateStr(orderState);
        queryParams.setIsTc("ALL");
        if(null != goodsSeller&& !"".equals(goodsSeller))
         queryParams.setGoodsSeller(goodsSeller);

        ServiceMessage<Page<OrderInfo>> orderResult = null;
        try {
            orderResult = orderInfoService.getWebOrderInfoByListPage(
                    NumericUtil.parseInt(pageNum, 1),
                    NumericUtil.parseInt(pageSize, 10), queryParams);

            JSONObject resultObj = new JSONObject();

            if (orderResult.getStatus() == MsgStatus.NORMAL) {           //通过接口拿到数据
                resultObj = JSONObject.fromObject(orderResult.getResult());          //data的json格式数据
                JSONArray data = resultObj.getJSONArray("data"), afterSetDate = new JSONArray();
                //遍历集合
                for (int i = 0; i < data.size(); i++) {
                    JSONObject orderInfo = data.getJSONObject(i);

                    OrderItem itemQueryParams = new OrderItem();
                    itemQueryParams.setMul(mul);
                    itemQueryParams.setMemberKey(memberKey);
                    itemQueryParams.setOrderId(orderInfo.getLong("orderId"));
                    itemQueryParams.setIsTc("ALL");
                    // 嵌入商品图片列表
                    ServiceMessage<List<OrderItem>> orderItemResult = orderItemService
                            .getWebOrderInfoPicByList(itemQueryParams);
                    if (orderItemResult.getStatus() == MsgStatus.NORMAL) {
                        BigDecimal orderGoodsCount = new BigDecimal(0);            //定义jsonArry
                        JSONArray goodsList = new JSONArray();
                        for (OrderItem orderItem : orderItemResult.getResult()) {             //取值
                            JSONObject itemGoods = new JSONObject();              //赋值
                            itemGoods.put("imageUrl",
                                    orderItem.getProImageUrl());
                            itemGoods
                                    .put("productId", orderItem.getProductId());
                            itemGoods.put("goodsId", orderItem.getGoodsId());
                            itemGoods.put("drugPrescriptionType", orderItem.getDrugPrescriptionType());
                            orderGoodsCount = orderGoodsCount.add(orderItem.getGoodsAmount());                  //将取出的数据放到定义的集合中
                            goodsList.add(itemGoods);

                        }                 //json格式的数据展示
                        orderInfo.put("orderGoodsCount", orderGoodsCount);
                        orderInfo.put("goodsList", goodsList);
                    }

                    OrderInfo logisticsParam = new OrderInfo();
                    logisticsParam.setOrderId(orderInfo.getLong("orderId"));
                    logisticsParam.setMul(mul);
                    logisticsParam.setMemberKey(memberKey);

                    ServiceMessage<List<LogisticCompany>> logisticsResult = logisticCompanyService
                            .queryLogisticCompany(logisticsParam);
                    if (logisticsResult.getStatus() == MsgStatus.NORMAL) {
                        orderInfo.put("logisticCompanys",
                                logisticsResult.getResult());
                    }
                    /**
                     * 18已退款;19退货完成;20退货中;21已出库;22配货中;(23已收货;23该状态现在没有用到)
                     * 24缺货中;25已取消;26已完成;27已发货;28已审核;29已提交
                     * 根据isPaid 拆分29已提交,29已支付。
                     * 根据orderButs存在canEval 拆分26已完成,26已收货
                     */
                    int orderStateNum = orderInfo.getInt("orderState");
                    String isPaid = orderInfo.getString("isPaid");
                    List<String> orderButs = orderInfo.getJSONArray("orderButs");
                    String codeValue = getOrderStatus(orderStateNum, isPaid, orderButs);
                    orderInfo.put("codeValue", codeValue);
                    afterSetDate.add(orderInfo);
                }          //最后的封装
                resultObj.put("data", afterSetDate);

                Map<String, String> orderStatMap = this.getOrderStatistics(memberKey, mul, goodsSeller);
                resultObj.put("orderStatistics", orderStatMap);
                // for (OrderInfo orderInfo : orderResult.getResult()) {
                // OrderItem itemQueryParams = new OrderItem();
                // itemQueryParams.setMul(mul);
                // itemQueryParams.setMemberKey(memberKey);
                // itemQueryParams.setOrderId(orderInfo.getOrderId());
                //
                // // 嵌入商品图片列表
                // ServiceMessage<List<OrderItem>> orderItemResult =
                // orderItemService
                // .getWebOrderInfoPicByList(itemQueryParams);
                // if (orderItemResult.getStatus() == MsgStatus.NORMAL) {
                // List<String> goodsImageList = new ArrayList<String>();
                // for (OrderItem orderItem : orderItemResult.getResult()) {
                // goodsImageList.add(orderItem.getProImageUrl());
                // }
                // orderInfo.setGoodsImageList(goodsImageList);
                // }
                // }
                  //返回给前台
                _result.setObjData(resultObj);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResultInfo(orderResult,
                    ResultMsg.OrderActionMsg.LIST_FAILRE).write(request,
                    response);
        }
    }
    private Map<String, String> getOrderStatistics(String memberKey, String mul, String orderGoodsSeller) {
        // 查询订单数量
        Map<String, String> orderNumList = new HashMap<String, String>();
        int noPaidNum = 0, noShippingNum = 0, noReceiveNum = 0, noCommentNum = 0;

        OrderInfo orderNumParam = new OrderInfo();
        orderNumParam.setMemberKey(memberKey);
        orderNumParam.setMul(mul);
        orderNumParam.setOrderStateStr(Const.OrderState.NO_PAID);
        orderNumParam.setGoodsSeller(orderGoodsSeller);
        try {
            // 待付款订单数
            ServiceMessage<Integer> noPaidResult = orderInfoService
                    .getWebOrderInfoByListCount(orderNumParam);
            if (noPaidResult.getStatus() == MsgStatus.NORMAL)
                noPaidNum = noPaidResult.getResult();
        } catch (Exception e) {
            LOG.error("OrderAction@getOrderStatistics 待付款订单数 " + e.getMessage(), e);
        }

        try {
            orderNumParam.setOrderStateStr(Const.OrderState.NO_SHIPPING);
            // 待发货订单数
            ServiceMessage<Integer> noShippingResult = orderInfoService
                    .getWebOrderInfoByListCount(orderNumParam);
            if (noShippingResult.getStatus() == MsgStatus.NORMAL)
                noShippingNum = noShippingResult.getResult();

            orderNumParam.setOrderStateStr(Const.OrderState.NO_RECEIVE);

        } catch (Exception e) {
            LOG.error("OrderAction@getOrderStatistics 待发货订单数 " + e.getMessage(), e);
        }

        try {
        // 待收货订单数
        ServiceMessage<Integer> noReceiveResult = orderInfoService
                .getWebOrderInfoByListCount(orderNumParam);
        if (noReceiveResult.getStatus() == MsgStatus.NORMAL)
            noReceiveNum = noReceiveResult.getResult();

        orderNumParam.setOrderStateStr(Const.OrderState.NO_COMMENT);

        } catch (Exception e) {
            LOG.error("OrderAction@getOrderStatistics 待收货订单数 " + e.getMessage(), e);
        }

        try {
            // 待评价订单数
            ServiceMessage<Integer> noCommentResult = orderInfoService
                    .getWebOrderInfoByListCount(orderNumParam);
            if (noCommentResult.getStatus() == MsgStatus.NORMAL)
                noCommentNum = noCommentResult.getResult();
        } catch (Exception e) {
            LOG.error("OrderAction@getOrderStatistics 待评价订单数 " + e.getMessage(), e);
        }
        orderNumList.put("noPaid", String.valueOf(noPaidNum));
        orderNumList.put("noShipping", String.valueOf(noShippingNum));
        orderNumList.put("noReceive", String.valueOf(noReceiveNum));
        orderNumList.put("noComment", String.valueOf(noCommentNum));

        return orderNumList;
    }
    private Map<String, String> getCRCOrderStatistics(String memberKey, String mul) {
        return getOrderStatistics(memberKey, mul,"2");// CRCare order type
    }
    /**
     * 查询订单详情
     *
     * @param request
     * @param response
     * @param mul
     *            来源
     * @param orderId
     *            订单ID
     * @date 26/11/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/detail")
    public void detail(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        if (StringUtil.isEmpty(memberKey)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.Common.MEMBER_KEY_EMPTY).write(request, response);
            return;
        }

        if (StringUtil.isEmpty(orderId) || !StringUtil.isNumeric(orderId)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.OrderActionMsg.ORDER_ID_EMPTY).write(request,
                    response);
            return;
        }
        // PARAMTER VALIDATION END

        OrderInfo queryParams = new OrderInfo();
        queryParams.setMemberKey(memberKey);
        queryParams.setMul(mul);
        queryParams.setOrderId(NumericUtil.parseLong(orderId));
        queryParams.setIsTc("ALL");
        ServiceMessage<Page<OrderInfo>> orderResult = null;
        try {
            orderResult = orderInfoService.getWebOrderInfoByListPage(1, 10,
                    queryParams);
            if (orderResult.getStatus() == MsgStatus.NORMAL) {
                if (orderResult.getResult().getTotalCount() == 0) {
                    this.setResultInfo(MsgStatus.NO_RESULT.getCode(),
                            ResultMsg.OrderActionMsg.ORDER_NOT_EXISTS);
                    return;
                }

                OrderInfo orderInfo = orderResult.getResult().getData().get(0);

                //订单状态
                Integer orderState = orderInfo.getOrderState();
                String isPaid = orderInfo.getIsPaid();
                List<String> orderButs = orderInfo.getOrderButs();
                    String orderStatus = getOrderStatus(orderState, isPaid, orderButs!=null?orderButs:new  ArrayList<String>());
                    orderInfo.setCodeValue(orderStatus);
                _result.setObjData(orderInfo);

                //订单状态的集合
                List<String> orderStatusList = getOrderStatusList(orderState);
                if(orderInfo.getPaymentMode().equals("HDFK")){
                    orderStatusList.remove("已支付");
                }
                _result.put("orderStatusList",orderStatusList);

                // 订单物流列表
                OrderInfo logisticsParam = new OrderInfo();
                logisticsParam.setOrderId(NumericUtil.parseLong(orderId));
                logisticsParam.setMul(mul);
                logisticsParam.setMemberKey(memberKey);

                ServiceMessage<List<LogisticCompany>> logisticsResult = logisticCompanyService
                        .queryLogisticCompany(orderInfo);
                if (logisticsResult.getStatus() == MsgStatus.NORMAL
                        && logisticsResult.getResult() != null) {
                    _result.put("logisticCompanys", logisticsResult.getResult());
                }

                //3.71   新增物流详情
                OrderInfo orderInfo1=new OrderInfo();
                orderInfo1.setOrderId(NumericUtil.parseLong(orderId));
                ServiceMessage<List<Logistics>> serviceMessage =  logisticCompanyService.queryLogistics(orderInfo1);
                List<LogisticsInfo> logisticsInfos = sortLogisticInfo(serviceMessage);
                this.setResultInfo(serviceMessage.getStatus().getCode(),
                        serviceMessage.getMessage());
//                _result.put("result",serviceMessage.getResult());
                _result.put("lastLogisticsInfo",logisticsInfos);

                // 订单商品列表
                OrderItem orderItemQueryParams = new OrderItem();
                orderItemQueryParams.setMemberKey(memberKey);
                orderItemQueryParams.setOrderId(queryParams.getOrderId());
                orderItemQueryParams.setIsTc("ALL");

                ServiceMessage<List<OrderItem>> orderItemResult = orderItemService
                        .getWebOrderInfoPicByList(orderItemQueryParams);
                if (orderItemResult.getStatus() == MsgStatus.NORMAL) {
                    _result.put("goodsList", orderItemResult.getResult());
                }
                setResultInfo(orderResult.getStatus().getCode(),
                        orderResult.getMessage());
            }
            setResultInfo(orderResult,
                    ResultMsg.OrderActionMsg.LIST_FAILRE);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            write(request, response);
        }
    }

    /**
     * 查询订单包裹物流
     *
     * @param request
     * @param response
     * @param mul
     *            来源
     * @param orderId
     *            订单ID
     * @date 28/11/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/logistics")
    public void logistics(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(NumericUtil.parseLong(orderId));
        orderInfo.setMul(mul);
        orderInfo.setMemberKey(memberKey);

        ServiceMessage<List<LogisticCompany>> logisticsResult = null;
        try {
            logisticsResult = logisticCompanyService
                    .queryLogisticCompany(orderInfo);
            if (logisticsResult.getStatus() == MsgStatus.NORMAL
                    && logisticsResult.getResult() != null) {
                _result.put("logisticCompanys",
                        logisticsResult.getResult());
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResultInfo(logisticsResult,
                    ResultMsg.OrderActionMsg.LOGISTICS_FAILURE).write(request,
                    response);
        }
    }

    /**
     * 获取物流详情
     *
     * @param request
     * @param response
     * @param memberKey
     * @param mul
     * @param orderId
     * @param orderShippingNo
     */
    @RequestMapping("/shipping")
    public void shipping(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId,
            @RequestParam(value = "orderShippingNo", required = false) String orderShippingNo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(NumericUtil.parseLong(orderId));
        orderInfo.setMul(mul);
        orderInfo.setMemberKey(memberKey);
        orderInfo.setIsTc("ALL");
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        try {
            // 查询订单详情
            ServiceMessage<Page<OrderInfo>> orderResult = orderInfoService
                    .getWebOrderInfoByListPage(1, 1, orderInfo);

            // 订单
            if (orderResult.getStatus() != MsgStatus.NORMAL) {
                setResultInfo(orderResult.getStatus().getCode(),
                        orderResult.getMessage());
                return;
            }

            // 查询订单条数超过1条(按照ID查应该)
            if (orderResult.getResult().getTotalCount() > 1) {
                setResultInfo(MsgStatus.EXCEPTION.getCode(),
                        ResultMsg.OrderActionMsg.EXPECT_SIZE);
                return;
            }
            List<OrderInfo> orderInfos =orderResult.getResult().getData();
            _result.put("orderInfo", orderInfos!=null&&orderInfos.size()>0?orderInfos.get(0):"");

            ServiceMessage<List<LogisticCompany>> logisticsResult = logisticCompanyService
                    .queryLogisticCompany(orderInfo);

            LogisticCompany matchedLogisticCompany = null;
            if (logisticsResult.getStatus() == MsgStatus.NORMAL) {
                for (LogisticCompany logisticCompany : logisticsResult
                        .getResult()) {
                    if (logisticCompany.getOrderShippingNo().equals(
                            orderShippingNo)) {
                        matchedLogisticCompany = logisticCompany;
                        break;
                    }
                }
            }

            // 运单号查询不到
            if (matchedLogisticCompany == null) {
                setResultInfo(MsgStatus.NO_RESULT.getCode(),
                        ResultMsg.Common.QUERY_NO_RESULT);
                return;
            }

            _result.put("logisticCompany", matchedLogisticCompany);
            setResultInfo(MsgStatus.NORMAL.getCode(), ResultMsg.Common.OK);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            write(request, response);
        }
    }

    /**
     * 取消订单
     *
     * @param request
     * @param response
     * @param mul
     *            来源
     * @param orderId
     *            订单ID
     * @date 28/11/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/cancel")
    public void cancel(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(NumericUtil.parseLong(orderId));
        orderInfo.setMemberKey(memberKey);
        orderInfo.setMul(mul);

        ServiceMessage<String> cancelResult = null;
        try {
            cancelResult = orderInfoService.rollBackOrder(orderInfo);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResult(cancelResult,
                    ResultMsg.OrderActionMsg.CANCEL_FAILURE).write(request,
                    response);
        }
    }

    /**
     * 订单确认
     *
     * @param request
     * @param response
     * @param memberKey
     * @param mul
     * @param orderId
     */
    @RequestMapping("/confirm")
    public void confirm(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(NumericUtil.parseLong(orderId));
        orderInfo.setMemberKey(memberKey);
        orderInfo.setMul(mul);

        ServiceMessage<String> confirmResult = null;
        try {
            confirmResult = orderInfoService.orderFinish(orderInfo);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResult(confirmResult,
                    ResultMsg.OrderActionMsg.CONFIRM_FAILURE).write(request,
                    response);
        }
    }

    /**
     * 查询订单日志
     *
     * @param request
     * @param response
     * @param mul
     *            来源
     * @param orderId
     *            订单ID
     * @date 28/11/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/log")
    public void log(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (null == request.getParameter("createSource")
                || (null != request.getParameter("createSource") && !request
                        .getParameter("createSource").equals("app"))) {
            String code = checkMemberKeyService.getCode(memberKey);
            if (code.equals("-99")) {
                this.setResultInfo(code, "请登录!").write(request, response);
                return;
            }
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setMemberKey(memberKey);
        orderInfo.setOrderId(NumericUtil.parseLong(orderId));
        orderInfo.setMul(mul);

        ServiceMessage<List<OrderLog>> logResult = null;
        try {
            logResult = orderLogService.getPublicLogByOrderId(orderInfo);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            _result.put("logs", logResult.getResult());
            this.setResultInfo(logResult, ResultMsg.OrderActionMsg.LOG_FAILURE)
                    .write(request, response);
        }
    }

    /**
     * 支付完成后获取订单信息
     *
     * @param request
     * @param response
     * @param memberKey
     * @param mul
     * @param orderId
     */
    @RequestMapping("/afterPay")
    public void afterPay(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId", required = false) String orderId) {
        if (StringUtil.isEmpty(memberKey)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.Common.MEMBER_KEY_EMPTY).write(request, response);

            return;
        }

        if (StringUtil.isEmpty(orderId)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.OrderActionMsg.ORDER_ID_EMPTY).write(request,
                    response);
            return;
        }
        // PARAMTER VALIDATION END
        OrderInfo queryParams = new OrderInfo();
        queryParams.setMemberKey(memberKey);
        queryParams.setMul(mul);
        queryParams.setOrderId(NumericUtil.parseLong(orderId));
        queryParams.setIsTc("ALL");
        ServiceMessage<Page<OrderInfo>> orderResult = null;
        try {
            orderResult = orderInfoService.getWebOrderInfoByListPage(1, 10,
                    queryParams);
            if (orderResult.getStatus() == MsgStatus.NORMAL) {
                if (orderResult.getResult().getTotalCount() == 0) {
                    this.setResultInfo(MsgStatus.NO_RESULT.getCode(),
                            ResultMsg.OrderActionMsg.ORDER_NOT_EXISTS);
                    return;
                }

                OrderInfo orderInfo = orderResult.getResult().getData().get(0);

                int returnPoints = 0;
                // 获取订单赠送积分
                if (StringUtil.isNotEmpty(orderInfo.getReturnType())
                        && orderInfo.getReturnType().contains("points")) {
                    returnPoints = NumericUtil.parseInt(orderInfo
                            .getReturnValue().split("/")[0], 0);
                }

                // 包裹数量
                int parcelCount = 1;
                // 订单物流列表
                // OrderInfo logisticsParam = new OrderInfo();
                // logisticsParam.setOrderId(NumericUtil.parseLong(orderId));
                // logisticsParam.setMul(mul);
                // logisticsParam.setMemberKey(memberKey);
                //
                // ServiceMessage<List<LogisticCompany>> logisticsResult =
                // logisticCompanyService
                // .queryLogisticCompany(orderInfo);
                // if (logisticsResult.getStatus() == MsgStatus.NORMAL
                // && logisticsResult.getResult() != null) {
                // parcelCount = logisticsResult.getResult().size();
                // }

                // 商品数量
                int goodsCount = 0;
                // 订单商品列表
                OrderItem orderItemQueryParams = new OrderItem();
                orderItemQueryParams.setMemberKey(memberKey);
                orderItemQueryParams.setOrderId(queryParams.getOrderId());
                orderItemQueryParams.setIsTc("ALL");

                ServiceMessage<List<OrderItem>> orderItemResult = orderItemService
                        .getWebOrderInfoPicByList(orderItemQueryParams);
                if (orderItemResult.getStatus() == MsgStatus.NORMAL) {

                    for (OrderItem orderItem : orderItemResult.getResult()) {
                        goodsCount += orderItem.getGoodsAmount() == null ? 0
                                : orderItem.getGoodsAmount().intValue();

                        // GoodsDetailto.setGoodsId(orderItem.getGoodsId());
                        // goodsDetailDto.setProductId(orderItem.getProductId().intValue());
                        // goodsDetailDtoDto goodsDetailDto = new
                        // GoodsDetailDto();
                        // goodsDetailD.setSiteType(SiteType.MOBILE);

                        // ServiceMessage<GoodsDetailDto> detailResult =
                        // goodsDetailService
                        // .getGoodDetail(goodsDetailDto);
                        // if (detailResult.getStatus() == MsgStatus.NORMAL) {
                        // TODO 根据商品所在仓库计算包裹数量
                        // }
                    }
                }
                String paymentMode = "weixin";
                ServiceMessage<List<OrderPaymentTypeList>> orderPaymentTypeList = payQueryService.getOrderPaymentTypeSingle(orderId);
                if (null != orderPaymentTypeList &&
                        orderPaymentTypeList.getStatus() == MsgStatus.NORMAL) {
                    if (orderPaymentTypeList.getResult() != null
                            && orderPaymentTypeList.getResult().size() > 0) {
                        paymentMode = orderPaymentTypeList.getResult().get(0).getPaymentTypeNo();
                    }
                }

                String ticketTitle = "";// 发票抬头
                ServiceMessage<OrderInfo> orderMessage = orderInfoService.getOrderInfoById(queryParams);
                if (orderMessage.getStatus() == MsgStatus.NORMAL) {
                    ticketTitle = orderMessage.getResult().getInvoiceTitle();
                }

                //更多优惠
                ArrayList<Map<String, String>> bottomList = new ArrayList<Map<String,String>>();
                try {
                    Map<String, String> bottomStroll = new HashMap<String, String>();
                    bottomStroll.put("title", "查看订单");
                    bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111235738351.png");
                    bottomStroll.put("targeUrl", "/mall/orderdetail.html?orderId="+orderId);
                    bottomList.add(bottomStroll);

                    bottomStroll = new HashMap<String, String>();
                    bottomStroll.put("title", "账号充值");
                    bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111301537528.png");
                    bottomStroll.put("targeUrl", "/mall/myAccount.html");
                    bottomList.add(bottomStroll);

                    bottomStroll = new HashMap<String, String>();
                    bottomStroll.put("title", "更多优惠");
                    bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111329080669.png");
                    bottomStroll.put("targeUrl", "");
                    PageIndexImg  pageIndexImg = new PageIndexImg();
                    pageIndexImg.setSiteType(SiteType.MOBILE);
                    pageIndexImg.setImageType(Integer.valueOf(PageIndexType.IMAGE_CAROUSEL_APP.getCode()));
                    ServiceMessage<List<PageIndexImg>> banners = pageIndexImgService.getPageIndexImgList(pageIndexImg);
                    if (banners.getStatus() == MsgStatus.NORMAL) {
                        List<PageIndexImg> bannerList = banners.getResult();
                        if(bannerList.size()>0){
                            String  url = bannerList.get(0).getUrl();
                            bottomStroll.put("targeUrl", url);
                        }
                    }
                    bottomList.add(bottomStroll);
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                }

                _result.put("bottomStrollList", bottomList);
                _result.put("paymentMode", paymentMode);
                _result.put("ticketTitle", ticketTitle);
                _result.put("orderId", orderInfo.getOrderId());
                _result.put("orderPayFee", orderInfo.getOrderFee());
                _result.put("goodsSeller", orderInfo.getGoodsSeller());
                _result.put("returnPoints", returnPoints);
                _result.put("parcelCount", parcelCount);
                _result.put("goodsCount", goodsCount);
                setResultInfo(orderResult.getStatus().getCode(),
                        orderResult.getMessage());
            }
            setResultInfo(orderResult,
                    ResultMsg.OrderActionMsg.LIST_FAILRE);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            write(request, response);
        }
    }

    @RequestMapping("/payInfoCheck")
    public void PayInfocheck(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "orderId",required = false)String orderId
    ){
        if (StringUtil.isEmpty(memberKey)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.Common.MEMBER_KEY_EMPTY).write(request, response);

            return;
        }
        if (StringUtil.isEmpty(orderId)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.OrderActionMsg.ORDER_ID_EMPTY).write(request,
                    response);
            return;
        }
        try {
            Long memberId = MemberKeyUtils.getMemberKey(memberKey);
            OrderInfo orderInfoparam = new OrderInfo();
            orderInfoparam.setOrderId(NumericUtil.parseLong(orderId));
            orderInfoparam.setMemberKey(memberKey);
            orderInfoparam.setMemberId(memberId);
            orderInfoparam.setMul(mul);
            //查询订单信息
            ServiceMessage<OrderInfo> orderInfoById = orderInfoService.getOrderInfoById(orderInfoparam);
            if (orderInfoById.getStatus() != MsgStatus.NORMAL || orderInfoById.getResult() == null) {
                this.setResultInfo("0", "查询订单信息失败");
            }
            OrderInfo orderInfo = orderInfoById.getResult();
            //支付状态,N:未支付,Y:已全额支付,P:部分支付'
            String paidState=orderInfo.getIsPaid();
            String padiMsg=null;
            ArrayList<Map<String, String>> bottomList = new ArrayList<Map<String,String>>();
            if (paidState.equals("Y")||orderInfo.getPaymentMode().equals("HDFK")){
                padiMsg="支付成功!";
                //更多优惠
                Map<String, String> bottomStroll = new HashMap<String, String>();
                bottomStroll.put("title", "查看订单");
                bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111235738351.png");
                bottomStroll.put("targeUrl", "/mall/orderdetail.html?orderId="+orderId);
                bottomList.add(bottomStroll);
                bottomStroll = new HashMap<String, String>();
                bottomStroll.put("title", "账号充值");
                bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111301537528.png");
                bottomStroll.put("targeUrl", "/mall/myAccount.html");
                bottomList.add(bottomStroll);
                bottomStroll = new HashMap<String, String>();
                bottomStroll.put("title", "更多优惠");
                bottomStroll.put("imageUrl", "http://soa.app.j1.com/upload/read/2015/8/27111329080669.png");
                bottomStroll.put("targeUrl", "");
                PageIndexImg  pageIndexImg = new PageIndexImg();
                pageIndexImg.setSiteType(SiteType.MOBILE);
                pageIndexImg.setImageType(Integer.valueOf(PageIndexType.IMAGE_CAROUSEL_APP.getCode()));
                ServiceMessage<List<PageIndexImg>> banners = pageIndexImgService.getPageIndexImgList(pageIndexImg);
                if (banners.getStatus() == MsgStatus.NORMAL) {
                    List<PageIndexImg> bannerList = banners.getResult();
                    if(bannerList.size()>0){
                        String  url = bannerList.get(0).getUrl();
                        bottomStroll.put("targeUrl", url);
                    }
                }
                bottomList.add(bottomStroll);
            }else if (paidState.equals("P")){
                padiMsg="卡内余额不足,支付未完成,您还需要支付余款,请重新选择其他支付方式!";
            }else {
                padiMsg="支付未完成,请重新支付!";
            }
            _result.put("paidState",paidState);
            _result.put("paidMsg",padiMsg);
            float orderFee = orderInfo.getOrderFee().floatValue();
            _result.put("orderFee",orderFee);
            float needPaiFee = orderFee-orderInfo.getPaidFee().floatValue();
            //格式化价格,显示小数点后两位
            DecimalFormat fnum=new DecimalFormat("##0.00");
            String needPayfee = fnum.format(needPaiFee);
            //待支付余额
            _result.put("needPaiFee",needPayfee);
//            _result.put("payTime",orderInfo.getPaidTime());
            _result.put("payModel",orderInfo.getPaymentMode());
            _result.put("goodsSeller",orderInfo.getGoodsSeller());
            if (bottomList.size()>0){
                _result.put("bottomList",bottomList);
            }
            this.setResultInfo("0","查询成功").write(request,response);
        }catch (Exception e){
            LOG.error(e.getMessage());
            this.setResultInfo("1","网路异常,请稍后重试").write(request,response);
        }

    }

    private static List<String> getOrderStatusList(Integer orderState){
        List<String> orderStatusMs=new ArrayList<String>();

        if (orderState==29 ||orderState==28 ||orderState==27||
                orderState==26||orderState==23||
                orderState==22 || orderState==21||orderState==431
                ){
            orderStatusMs.add("已提交");
            orderStatusMs.add("已支付");
            orderStatusMs.add("已审核");
            orderStatusMs.add("配货中");
            orderStatusMs.add("已出库");
            orderStatusMs.add("已发货");
            orderStatusMs.add("已收货");
            orderStatusMs.add("已完成");
        }
        if (orderState==18 || orderState==19||orderState==20){
            orderStatusMs.add("退货中");
            orderStatusMs.add("已退款");
            orderStatusMs.add("退货完成");
        }
        if(orderState==25){
            orderStatusMs.add("已取消");
        }
        if(orderState==24){
            orderStatusMs.add("缺货中");
        }
        return orderStatusMs;
    }

    /**
     * 18已退款;19退货完成;20退货中;21已出库;22配货中;(23已收货;23该状态现在没有用到)
     * 24缺货中;25已取消;26已完成;27已发货;28已审核;29已提交
     * 根据isPaid 拆分29已提交,29已支付。
     * 根据orderButs存在canEval 拆分26已完成,26已收货
     */
    private static String getOrderStatus(Integer orderInt,String isPay,List<String> orderButs){
        String  orderStatus="已提交";
        switch (orderInt) {
        case 29:
            if ("Y" .equals(isPay)) {
                orderStatus="已支付";
            }else {
                orderStatus="已提交";
            }
            break;
        case 28:
            orderStatus="已审核";
            break;
        case 27:
            orderStatus="已发货";
            break;
        case 26:
            if (orderButs.contains("canEval")) {
                orderStatus="已收货";
            }else {
                orderStatus="已完成";
            }
            break;
        case 25:
            orderStatus="已取消";
            break;
        case 24:
            orderStatus="缺货中";
            break;
        case 23:
            orderStatus="已收货";
            break;
        case 22:
            orderStatus="配货中";
            break;
        case 21:
            orderStatus="已出库";
            break;
        case 20:
            orderStatus="退货中";
            break;
        case 19:
            orderStatus="退货完成";
            break;
        case 18:
            orderStatus="已退款";
            break;
        case 431:
            orderStatus="部分发货";
            break;
        }
        return orderStatus;
    }
    private List<LogisticsInfo> sortLogisticInfo(ServiceMessage<List<Logistics>> serviceMessage) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Logistics> result = serviceMessage.getResult();
        ArrayList<LogisticsInfo> list = new ArrayList<LogisticsInfo>();
        for(Logistics logistics: result){
            LogisticsInfo logisticsInfo = logistics.getLogisticsInfos().get(0);
            list.add(logisticsInfo);
        }
//        System.out.println("最新++++++++++"+list.toString());
        //排序
        for (int i = 0; i <list.size() ; i++) {
            for (int j = i+1; j <list.size() ; j++) {
                boolean flag = df.parse(list.get(i).getLogisticsTime()).before(df.parse(list.get(j).getLogisticsTime()));
                if (flag){
                    LogisticsInfo temp=list.get(i);
                    list.set((i), list.get(j));
                    list.set(j, temp);
                }
            }
        }
//        for (LogisticsInfo s : list) {
//            System.out.println("11111111111111111"+s.toString());
//        }
//        System.out.println("11111111111111"+list.toString());
    return list;
    }

    @RequestMapping("/insertFromStore")
    public void insertFromStore(
            HttpServletRequest request,
            HttpServletResponse response){
        StringBuffer json = new StringBuffer();
        String line = null;
        String orderMsg = "";
        try {
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null) {
                json.append(line);
            }
            orderMsg = json.toString();
        }
        catch(Exception e) {
            logger.error(e);
        }
        if (StringUtil.isEmpty(orderMsg)){
                this.setResultInfo("-1", "params error!").write(request, response);
                return;
        }
        com.alibaba.fastjson.JSONObject jsonObject = null;

        try {
            jsonObject = com.alibaba.fastjson.JSONObject.parseObject(orderMsg);
        } catch (Exception e) {
            this.setResultInfo("-1", "params error!").write(request, response);
            return;
        }

        //门店渠道id
        int storeMutilId = 46;

        String mTel = jsonObject.getString("mTel");
        String tranid = jsonObject.getString("tranid");
        com.alibaba.fastjson.JSONArray artiitem = jsonObject.getJSONArray("artiitem");
        String tranDate = jsonObject.getString("tranDate");
        String discount = jsonObject.getString("discount");
        String deptName = jsonObject.getString("deptName");
        String sumSaleAmt = jsonObject.getString("sumSaleAmt");
        String memberId = jsonObject.getString("memberId");

        if(StringUtil.isEmpty(mTel)||StringUtil.isEmpty(tranid)||StringUtil.isEmpty(tranDate)||StringUtil.isEmpty
                (discount)||StringUtil.isEmpty(deptName)||StringUtil.isEmpty(sumSaleAmt)||StringUtil.isEmpty(memberId)){
            this.setResultInfo("-1", "params error!").write(request, response);
            return;
        }

        List<OrderItem> itemList = new ArrayList<OrderItem>();

        String orderIsTC ="N";

        //订单详情信息
        for (Object o : artiitem) {
            OrderItem item = new OrderItem();
            String jsonStr = com.alibaba.fastjson.JSONObject.toJSONString(o);
            com.alibaba.fastjson.JSONObject itemJson = com.alibaba.fastjson.JSONObject.parseObject(jsonStr);
            String artiCode = itemJson.getString("artiCode");
            String artiName = itemJson.getString("artiName");
            String isCFY = itemJson.getString("isCFY");
            String artiQty = itemJson.getString("artiQty");
            String saleAmt = itemJson.getString("saleAmt");
            String salePrice = itemJson.getString("salePrice");

            if(StringUtil.isEmpty(artiCode)||StringUtil.isEmpty(artiQty)||StringUtil.isEmpty(saleAmt)||StringUtil
                    .isEmpty(salePrice)||StringUtil.isEmpty(artiName)||StringUtil.isEmpty(isCFY)){
                this.setResultInfo("-1", "params error!").write(request, response);
                return;
            }

            if(new BigDecimal(saleAmt).compareTo(new BigDecimal(salePrice).multiply(new BigDecimal(artiQty))) != 0){
                this.setResultInfo("3", "单品金额校验失败").write(request, response);
                return;
            }

            if(!isCFY.equals("0")){
                orderIsTC = "Y";
            }

            item.setGoodsName(artiName);
            item.setGoodsNo(artiCode);
            item.setGoodsPrice(new BigDecimal(salePrice));
            item.setGoodsAmount(new BigDecimal(artiQty));
            item.setGoodsSumFee(new BigDecimal(saleAmt));

            item.setGoodsType("general");
            itemList.add(item);
        }

        //订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setMemberId(Long.valueOf(memberId));
        orderInfo.setMemberMobile(mTel);
        orderInfo.setReceiveMobile(mTel);
        orderInfo.setMultiChannelId(storeMutilId);
        orderInfo.setMultiChannelOrderId(Long.valueOf(tranid));
        orderInfo.setOtherDiscounts(new BigDecimal(discount));
        orderInfo.setFinishTime(tranDate);
        orderInfo.setOrderFee(new BigDecimal(sumSaleAmt));
        orderInfo.setIsTc(orderIsTC);

        ServiceMessage<String> insertResult= null;
        String resultMsg = ResultMsg.Common.OK;
        try {
             insertResult= orderInfoService.insertOrderInfoFromStore(orderInfo,itemList,deptName);
             resultMsg = insertResult.getMessage();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMsg = ResultMsg.OrderActionMsg.INSERT_STORE_FAILURE;
        } finally {
            this.setResult(insertResult,
                    resultMsg).write(request,
                    response);
        }
    }
}
上一篇:async和await用法


下一篇:kotlin 第7个程序(when表达式)