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());
                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);
                        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);

                        }
                        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");

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

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

        //订单详情信息
        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 artiQty = itemJson.getString("artiQty");
            String saleAmt = itemJson.getString("saleAmt");

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

            item.setGoodsNo(artiCode);
            item.setGoodsPrice(new BigDecimal(saleAmt));
            item.setGoodsAmount(new BigDecimal(artiQty));
            item.setGoodsSumFee(new BigDecimal(saleAmt).multiply(new BigDecimal(artiQty)));
            itemList.add(item);
        }

        //订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setMemberMobile(mTel);
        orderInfo.setMultiChannelId(storeMutilId);
        orderInfo.setMultiChannelOrderId(Long.valueOf(tranid));
        orderInfo.setOtherDiscounts(new BigDecimal(discount));
        orderInfo.setFinishTime(tranDate);
        orderInfo.setOrderFee(new BigDecimal(sumSaleAmt));
        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);
        }
    }
}
    @Override
    public ServiceMessage insertOrderInfoFromStore(OrderInfo orderInfo ,List<OrderItem> itemList,String deptName) {

        Member paramsMember = new Member();
        paramsMember.setMobile(orderInfo.getMemberMobile());
        try {
            ServiceMessage<Member> memResult = memberService.getMemberByMem(paramsMember);
            if (!memResult.getStatus().equals(MsgStatus.NORMAL)){
                return super.returnNoResult("没有查询到用户信息");
            }
            Member member = memResult.getResult();

            OrderInfo orderInfoByMulti = orderInfoMapper.getOrderInfoByMulti(orderInfo);

            if(null != orderInfoByMulti){
                return super.returnException("该订单信息已存在");
            }

            //订单表保存
            orderInfo.setMemberId(member.getMemberId());
            orderInfo.setIsPaid("Y");
            orderInfo.setPaymentMode("HDFK");
            orderInfo.setOrderState(26);
            orderInfo.setOrderOutState(31);

            //计算订单价格
            BigDecimal orderFee = new BigDecimal(0.00);
            for (OrderItem item : itemList) {
                orderFee = orderFee.add(item.getGoodsPrice().multiply(item.getGoodsAmount()));
            }

            orderInfo.setOrderFee(orderFee);
            orderInfo.setPaidFee(orderFee);

            orderInfo.setReturnType("points");

            //订单返还积分
            MemberFreedomRepModel jfFreedomModel = shopcartFreedomService.getMemberFreedomJf(member.getMemberId());
            BigDecimal pointsGetScale = new BigDecimal(1);
            List<MemberRankFreedomLogRepModel> freedomLogList = new ArrayList<MemberRankFreedomLogRepModel>();
            // 判断是否有会员积分特权
            if (jfFreedomModel != null) {
                pointsGetScale = new BigDecimal(jfFreedomModel.getValue());
                // 特权使用日志
                MemberRankFreedomLogRepModel freedomLog = new MemberRankFreedomLogRepModel();
                // 会员ID
                freedomLog.setMemberId(member.getMemberId());
                // 角色ID
                freedomLog.setRoleId(jfFreedomModel.getRoleId());
                // 特权ID
                freedomLog.setFreedomId(jfFreedomModel.getId());
                // 使用次数
                freedomLog.setUseNum(1L);
                // 金额
//                freedomLog.setMoney();
                // 周期时长
                freedomLog.setGoOnLong(jfFreedomModel.getGoOnLong());
                // 增加特价的使用日志
                freedomLogList.add(freedomLog);

            }

            shopcartFreedomService.saveFreedomLog(freedomLogList);

            BigDecimal points = new BigDecimal(0);
            points = orderFee.divide(new BigDecimal(2),0,BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(5));
            points = points.multiply(pointsGetScale).setScale(0, BigDecimal.ROUND_DOWN);

            orderInfo.setReturnValue(points.toString());

            orderInfoMapper.saveOrderCommit(orderInfo);
            orderInfoMapper.update(orderInfo);
            //订单详情信息保存
            Long orderId = orderInfo.getOrderId();
            for (OrderItem item : itemList) {
                ServiceMessage<Goods> goodsResult = goodsService.getGoodsByNo(item.getGoodsNo());
                if(!goodsResult.getStatus().equals(MsgStatus.NORMAL)){
                    return super.returnException("未查询到该商品信息");
                }
                Goods goods = goodsResult.getResult();

                Goods goodsInfo = goodsService.getGoodsInfoById(goods.getGoodsId());

                item.setOrderId(orderId);
                item.setGoodsType("general");
                item.setGoodsId(goods.getGoodsId());
                item.setGoodsNo(goods.getGoodsNo());
                item.setGoodsName(goods.getGoodsName());
                item.setGoodsUnit(goodsInfo.getUnitName());
                item.setGoodsCostPrice(goods.getCostPrice());
                item.setGoodsOldPrice(goods.getMarketPrice());
                iOrderItemService.saveCommitOrderItem(item);
            }

            //当前订单所需返积分额度
            points = new BigDecimal(orderInfo.getReturnValue());
            MemberPointsHis pointsHis = new MemberPointsHis();
            pointsHis.setAddTime(DateUtils.nowTime());
            pointsHis.setChangeType("29");
            pointsHis.setChangeNotes("门店消费");
            pointsHis.setChangeTime(DateUtils.nowTime());
            pointsHis.setEditTime(DateUtils.nowTime());
            pointsHis.setMemberId(member.getMemberId());
            pointsHis.setPoints(points.intValue());
            pointsHis.setOrderId(orderId);
            memberPointHisService.changeMemberPointsHis(pointsHis);

            //订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderId);
            orderLog.setOrderStateId(26);
            orderLog.setLogContent("门店消费(" + deptName + ")");
            orderLog.setLogTime(orderInfo.getFinishTime());
            iOrderLogService.save(orderLog);

            return super.returnResult(MsgStatus.NORMAL,"success");
        }catch (Exception e){
            logger.error(e);
            return super.returnException("添加数据失败");
        }

    }
    <insert id="saveOrderCommit" parameterType="OrderInfo">
        <selectKey resultType="long" keyProperty="orderId" order="BEFORE">
            SELECT order_info_seq.nextval AS order_id from dual
        </selectKey>
        insert into order_info (order_id,
        member_id,
        order_state,
        order_out_state,
        limit_date,
        sku_fee,
        delivery_fee,
        order_fee,
        order_pay_fee,
        order_msg,
        commit_time,
        sku_weights,
        receive_user,
        province_id,
        city_id,
        area_id,
        receive_address,
        receive_full_address,
        receive_post,
        receive_tel,
        receive_mobile,
        receive_email,
        payment_mode,
        receive_date_type,
        receive_time_type,
        url_from_no,
        multi_channel_id,
        other_discounts,
        order_points,
        order_new
        <if test="orderVouchers != null">
            ,order_vouchers
        </if>
        <if test="discountFee != null">
            ,discount_fee
        </if>
        <if test="logisticCompanyId != null">
            ,logistic_company_id
        </if>
        <if test="allUsedPromoteRuleIds != null">
            ,promote_rule_ids
        </if>
        <if test="returnType != null">
            ,return_type
        </if>
        <if test="returnValue != null">
            ,return_value
        </if>
        <if test="isPaid != null">
            ,is_paid
        </if>
        <if test="paidTime != null">
            ,paid_time
        </if>
        <if test="couponNo != null">
            ,coupon_no
        </if>
        <if test="couponTypeUsId != null">
            ,coupon_type_us_id
        </if>
        <if test="isTc != null">
            ,is_tc
        </if>
        <if test="invoiceType != null">
            ,INVOICE_TYPE
        </if>
        <if test="invoiceContentType != null">
            ,INVOICE_CONTENT_TYPE
        </if>
        <if test="invoiceTitle != null">
            ,INVOICE_TITLE
        </if>
        <if test="invoiceContent != null">
            ,INVOICE_CONTENT
        </if>
        <if test="addUserId != null">
            ,ADD_USER_ID
        </if>
        <if test="addTime != null">
            ,ADD_TIME
        </if>
        <if test="editUserId != null">
            ,EDIT_USER_ID
        </if>
        <if test="editTime != null">
            ,EDIT_TIME
        </if>

        <if test="receiverCardno != null">
              ,RECEIVER_CARDNO
        </if>
        <if test="goodsSeller != null">
            ,GOODS_SELLER
        </if>
        <if test="memberAddressId != null">
            ,MEMBER_ADDRESS_ID
        </if>
        <if test="realDeliveryFee != null">
            ,REAL_DELIVERY_FEE
        </if>
        <if test="taxFee != null">
            ,TAX_FEE
        </if>
        <if test="realTaxFee != null">
            ,REAL_TAX_FEE
        </if>
        <if test="stockId != null">
            ,STOCK_ID
        </if>
        <if test="stockNo != null">
            ,STOCK_NO
        </if>
        )
        values (#{orderId,jdbcType=DECIMAL},
        #{memberId,jdbcType=DECIMAL},
        (select code_id from sys_code where
        code_type_no = 'order_state' and code_no
        = 'commit' and is_delete =
        'N'),
        (select code_id from sys_code where code_type_no = 'order_state'
        and code_no
        = 'commit' and is_delete = 'N'),
        null,
        #{skuFee,jdbcType=DECIMAL},
        #{deliveryFee,jdbcType=DECIMAL},
        #{orderFee,jdbcType=DECIMAL},
        #{orderPayFee,jdbcType=DECIMAL},
        #{orderMsg,jdbcType=VARCHAR},
        #{commitTime,jdbcType=VARCHAR},
        #{skuWeights,jdbcType=DECIMAL},
        #{receiveUser,jdbcType=VARCHAR},
        #{provinceId,jdbcType=DECIMAL},
        #{cityId,jdbcType=DECIMAL},
        #{areaId,jdbcType=DECIMAL},
        #{receiveAddress,jdbcType=VARCHAR},
        #{receiveFullAddress,jdbcType=VARCHAR},
        #{receivePost,jdbcType=VARCHAR},
        #{receiveTel,jdbcType=VARCHAR},
        #{receiveMobile,jdbcType=VARCHAR},
        #{receiveEmail,jdbcType=VARCHAR},
        #{paymentMode,jdbcType=VARCHAR},
        #{receiveDateType,jdbcType=VARCHAR},
        #{receiveTimeType,jdbcType=VARCHAR},
        #{urlFromNo,jdbcType=VARCHAR},
        #{multiChannelId,jdbcType=DECIMAL},
        #{otherDiscounts,jdbcType=DECIMAL},
        #{orderPoints,jdbcType=DECIMAL},
        () from order_info ord where ord.member_id = #{memberId})
        <if test="orderVouchers != null">
            ,#{orderVouchers,jdbcType=DECIMAL}
        </if>
        <if test="discountFee != null">
            ,#{discountFee,jdbcType=DECIMAL}
        </if>
        <if test="logisticCompanyId != null">
            ,#{logisticCompanyId,jdbcType=DECIMAL}
        </if>
        <if test="allUsedPromoteRuleIds != null">
            ,#{allUsedPromoteRuleIds,jdbcType=VARCHAR}
        </if>
        <if test="returnType != null">
            ,#{returnType,jdbcType=VARCHAR}
        </if>
        <if test="returnValue != null">
            ,#{returnValue,jdbcType=VARCHAR}
        </if>
        <if test="isPaid != null">
            ,#{isPaid,jdbcType=VARCHAR}
        </if>
        <if test="paidTime != null">
            ,#{paidTime,jdbcType=VARCHAR}
        </if>
        <if test="couponNo != null">
            ,#{couponNo,jdbcType=VARCHAR}
        </if>
        <if test="couponTypeUsId != null">
            ,#{couponTypeUsId,jdbcType=DECIMAL}
        </if>
        <if test="isTc != null">
            ,#{isTc,jdbcType=VARCHAR}
        </if>
        <if test="invoiceType != null">
            ,#{invoiceType,jdbcType=VARCHAR}
        </if>
        <if test="invoiceContentType != null">
            ,#{invoiceContentType,jdbcType=VARCHAR}
        </if>
        <if test="invoiceTitle != null">
            ,#{invoiceTitle,jdbcType=VARCHAR}
        </if>
        <if test="invoiceContent != null">
            ,#{invoiceContent,jdbcType=VARCHAR}
        </if>
        <if test="addUserId != null">
            ,#{addUserId,jdbcType=DECIMAL}
        </if>
        <if test="addTime != null">
            ,#{addTime,jdbcType=VARCHAR}
        </if>
        <if test="editUserId != null">
            ,#{editUserId,jdbcType=DECIMAL}
        </if>
        <if test="editTime != null">
            ,#{editTime,jdbcType=VARCHAR}
        </if>

        <if test="receiverCardno != null">
            ,#{receiverCardno,jdbcType=VARCHAR}
        </if>
        <if test="goodsSeller != null">
            ,#{goodsSeller,jdbcType=DECIMAL}
        </if>
        <if test="memberAddressId != null">
            ,#{memberAddressId,jdbcType=DECIMAL}
        </if>
        <if test="realDeliveryFee != null">
            ,#{realDeliveryFee,jdbcType=DECIMAL}
        </if>
        <if test="taxFee != null">
            ,#{taxFee,jdbcType=DECIMAL}
        </if>
        <if test="realTaxFee != null">
            ,#{realTaxFee,jdbcType=DECIMAL}
        </if>
        <if test="stockId != null">
            ,#{stockId,jdbcType=DECIMAL}
        </if>
        <if test="stockNo != null">
            ,#{stockNo,jdbcType=VARCHAR}
        </if>
        )
    </insert>

OrderAction的更多相关文章

  1. SSH实战 · 唯唯乐购项目(中)

    用户模块 三:一级分类的查询 创建一级分类表并导入基本数据 CREATE TABLE `category` (   `cid` int(11) NOT NULL AUTO_INCREMENT,   ` ...

  2. PHPUnit笔记

    PHPUnit是一个面向PHP程序员的测试框架,这是一个xUnit的体系结构的单元测试框架. 复杂的项目,通过单元测试能够快速排查bug,有效减少bug的产生.简单的项目,使用php自带的var_du ...

  3. Spring框架IOC容器和AOP解析

    主要分析点: 一.Spring开源框架的简介  二.Spring下IOC容器和DI(依赖注入Dependency injection) 三.Spring下面向切面编程(AOP)和事务管理配置  一.S ...

  4. 基于 Annotation 拦截的 Spring AOP 权限验证方法

    基于 Annotation 拦截的 Spring AOP 权限验证方法 转自:http://www.ibm.com/developerworks/cn/java/j-lo-springaopfilte ...

  5. action 方法的访问

    Action中的方法的访问: 访问Action的中的方法,默认情况下只能访问execute方法.那么多次请求就不能提交到一个Action.能不能一个模块的多次请求提交到一个Action中? * 需要使 ...

  6. SpringMvc_快速入门,深入分析

    目录  一.前言二.spring mvc 核心类与接口三.spring mvc 核心流程图 四.spring mvc DispatcherServlet说明 五.spring mvc 父子上下文的说明 ...

  7. Spring MVC 教程,快速入门,深入分析

    http://elf8848.iteye.com/blog/875830/ Spring MVC 教程,快速入门,深入分析 博客分类: SPRING Spring MVC 教程快速入门  资源下载: ...

  8. JavaWeb项目开发案例精粹-第6章报价管理系统-05Action层

    0. <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC &quo ...

  9. JavaWeb项目开发案例精粹-第6章报价管理系统-002辅助类及配置文件

    1. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www ...

随机推荐

  1. Ubuntu11.10与r8168网卡不兼容导致网络时断时续的问题

    安装了ubuntu11.10之后,感觉上网啥的很不稳定,ssh连接内网机器也是一条命令卡半天,检查了各方面的原因,网络没有什么问题,最后才发现是网卡驱动的问题,网上搜了一下是由于linux(ubunt ...

  2. libthrift0.9.0解析(三)之TProtocol&TTransport

       以上是transport和protocol的类图和结构图. transport封装了底层的传输通道,主要有read/write.open/close等基本的读写方法,而且都是对于二进制数据. p ...

  3. UIScrollView 滚动停止的时候一次调用此方法

    //拖动返回选中的索引 当滚动视图停止时的时候 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ CGFloat wid ...

  4. 利用js得到某个范围内的整数随机数

    Math.random()方法可以返回(0,1)之间的随机数,不包括0和1. 套用公式:Math.floor(Math.random()*可能的值的总数+第一个可能的值) 如得到(3,9]之间的随机数 ...

  5. QQ原创表情添加

    有时候与QQ好友聊天时会收到一些自己比较喜欢的原创表情,如果我们想把这些QQ不支持直接保存的原创表情保存到电脑上该怎么做呢?我们以原创表情图片为例简单介绍一下. 首先,先建立一个存放表情图片的文件夹. ...

  6. memcache的使用

    什么是memcache? Memcache是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨大的hash表,它能够用来存储各种格式的数据,包括图像.视频.文件以及数据库检索的结果等. ...

  7. [布局]bootstrap基本标签总结2

    缩略图 <div class="container"> <div class="row"> <div class="co ...

  8. Ubuntu 下对ADT 添加别名(alias)

    1:~$ vim .bashrc 2:在打开的.bashrc文件中加入: alias adt='./adt-bundle-linux-x86-20130729/eclipse/eclipse' 3:保 ...

  9. 在keil中使用printf()函数的要点

    在keil中printf默认是向串口中发送数据的,所以,如果应用该函数,必须先初始化串口,否则可能引起死机的情况,并且在printf之前应该先将TI置位,摘抄原因如下: 1.printf函数是调用pu ...

  10. 检测IIS应用程序池对象 回收

    function RecycleYourAppPool([string] $poolName){ Import-Module WebAdministration #获取所有Application Po ...