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. 原生js实现的放大镜效果

    这是我用原生js写的放大镜效果,与各种各样的框架技术相比,我喜欢使用原生的js,在这里,想和大家一起谈谈原生和框架技术的理解与个人喜好. <!DOCTYPE HTML><html&g ...

  2. 你好,C++(15)四两拨千斤——3.9 指向内存位置的指针

    3.9  指向内存位置的指针 一天,两个变量在街上遇到了: “老兄,你家住哪儿啊?改天找你玩儿去.” “哦,我家在静态存储区的0x0049A024号,你家呢?” “我家在动态存储区的0x0022FF0 ...

  3. UVA 305 Joseph (约瑟夫环 打表)

     Joseph  The Joseph's problem is notoriously known. For those who are not familiar with the original ...

  4. CentOS 6.5上安装Python 2.7.9

    CentOS 6.6自带的是Python 2.6.6,而编译llvm需要Python 2.7以上. checking for python... /usr/bin/python checking fo ...

  5. 手机时间选择插件 Jquery

    // 时间选择 var currYear = (new Date()).getFullYear() var opt_data = { preset: 'date', //日期 theme: 'andr ...

  6. Linux下部署Symfony2对app/cache和app/logs目录的权限设置

    在linux下部署完Symfony2,可能在访问的时候会报app/logs或者app/cache目录没有写权限的错误.在linux下,如果我们在命令行登陆的用户和web应用服务器(apache.ngi ...

  7. Symfony2目录结构说明

    了解框架的目录结构是框架快速入门的一个途径,一个成熟的框架,每个功能模块都被划分存放在不同的目录. Symfony2一级目录结构: ├── app //这目录下包含了,配置文件(应用的配置文件会被im ...

  8. 《python基础教程》笔记之 抽象

    创建函数 记录函数,在函数的开头写下字符串,它就会作为函数的一部分进行存储,这称为文档字符串,如 def square(x): 'Caculates the square of the number ...

  9. C程序设计语言练习题1-18

    练习1-18 编写一个程序,删除每个输入行末尾的空格及制表符,并删除完全是空格的行. 代码如下: #include <stdio.h> // 包含标准库的信息. #define MAXLI ...

  10. 文件磁盘读写类CArchive类

    CArchive类的成员 数据成员 m_pDocument 指向被串行化的CDocument对象 构造函数 Carchive 创建一个Carhcive对象 Abort在不异常的情况下,关闭归档文件 C ...