json 项目应用

package com.founder.ec.dec.action;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

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

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.founder.ec.cms.model.Channel;
import com.founder.ec.cms.model.Website;
import com.founder.ec.dec.service.ChannelService;

@Controller
public class ChannelAction {

    @Autowired
    private ChannelService channelService;

    /**
     * 根据渠道id获取渠道详情
     * @param channelId 渠道id
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/getChannelInfo")
    public void getChannelInfo(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        JSONObject json=new JSONObject();
        try{
            request.setCharacterEncoding("utf-8");
            Long channelId=Long.parseLong(request.getParameter("channelId"));

            if(channelId==null){
                json.put("code", -1);
                json.put("result", "请求参数为空");
                response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
                return ;
            }
            Channel channel = channelService.getChannelDetail(channelId);
            if(channel==null){
                json.put("code", -1);
                json.put("result", "找不到对应数据对象");
                response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
                return;
            }
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("groupId", Long.parseLong(channel.getAlternateField2()));
            map.put("groupName", channel.getGroupName());
            map.put("channelName", channel.getChannelName());
            json.put("code", 0);
            json.put("result",map);
            response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
        }catch(Exception e){
                json.put("code", -1);
                json.put("result", "inner error");
                response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
            e.printStackTrace();
        }

    }

    /**
     * 根据站点id获取站点名
     * @param websiteId 站点id
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/getWebsiteName")
    public void getWebsiteName(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        JSONObject json=new JSONObject();
        try{
            request.setCharacterEncoding("utf-8");
            Long websiteId=Long.parseLong(request.getParameter("websiteId"));

            if(websiteId==null){
                json.put("code", -1);
                json.put("result", "请求参数为空");
                response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
                return;
            }
            Website website = channelService.getWebsiteName(websiteId);
            if(website==null){
                json.put("code", -2);
                json.put("result", "找不到对应数据对象");
                response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
                return;
            }
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("websiteName", website.getAlternateField1());
            json.put("code", 0);
            json.put("result",map);
            response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
        }catch(Exception e){
            json.put("code", -3);
            json.put("result", "inner error");
            response.getWriter().write(URLEncoder.encode(json.toJSONString(),"UTF-8"));
            e.printStackTrace();
        }
    }

}
package com.founder.ec.dec.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.founder.ec.base.action.BaseClassAction;
import com.founder.ec.dec.service.GoodsQueryService;

/**
 * 商品查询接口
 * @author lurongyu
 *
 */
@Controller
public class GoodsQueryAction   extends BaseClassAction {

    @Autowired
    private GoodsQueryService service;

    @RequestMapping("/goodsQuery")
    public  void sendGoodsQuery (HttpServletRequest request, HttpServletResponse response ) throws Exception  {

        response.setContentType("text/html;charset=utf-8");
        String productCodes = request.getParameter("code").toString();
        String imageType = request.getParameter("imageType");
        if (null== request.getParameter("imageType") || "".equals(request.getParameter("imageType").toString())){
            imageType ="thumb";
        }
        String paracode ="";

        Map para = new HashMap ();
        List<Map<String,Object>>  resultList = new ArrayList <Map<String,Object>> ();
        if(request.getParameter("code")!=null && productCodes.length() >0) {
             String[] temps = productCodes.split(",");
             if (temps.length > 10 ){
                 response.getWriter().write("{code:-2,msg:'error ,code最多只能10个!'}");
             }
             for (int i =0; i< temps.length ; i++) {
                 paracode =paracode+ "'"+temps[i]+"',";
             }
            paracode=paracode.substring(0,paracode.length()-1);
            para.put("goodsNos", paracode);
            para.put("imageType", imageType);
            resultList = service.getGoodsQueryMap(para);
            JSONArray jsonArray =  JSONArray.fromObject(resultList);
            response.getWriter().write(jsonArray.toString());
        }else {
            response.getWriter().write("{code:-2,msg:'error ,code未传!'}");
        }

    }

}
// 解析json字符串,转成Model对象
                OrderInfo orderInfo = JSON.parseObject(orderInfoStr,OrderInfo.class);
package com.j1.mai.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.j1.base.dto.ServiceMessage;
import com.j1.base.order.model.ShopcartGoods;
import com.j1.base.order.model.ShopcartModel;
import com.j1.base.type.MsgStatus;
import com.j1.item.model.Goods;
import com.j1.mai.common.Const;
import com.j1.mai.model.common.SoaApiBaseAction;
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.ShopcartGoodsService;
import com.j1.soa.resource.order.api.ShopcartService;

/**
 * 促销相关Action
 *
 * @author qiaoyu
 */
@Controller
@Scope("request")
@RequestMapping("/promote")
public class PromoteAction extends SoaApiBaseAction {
    static Logger LOG = Logger.getLogger(PromoteAction.class);

    @Autowired
    private ShopcartService shopcartService;
    @Autowired
    private ShopcartGoodsService shopcartGoodsService;

    @RequestMapping("/promoteList")
    public void promoteList(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul) {
        ShopcartModel shopcartParam = new ShopcartModel();
        shopcartParam.setContentNo(contentNo);
        shopcartParam.setMemberKey(memberKey);
        shopcartParam.setMul(mul);
        JSONObject resultObj = new JSONObject();
        try {
            // 获取购物车信息
            ServiceMessage<ShopcartModel> shopcartResult = shopcartService
                    .shopcartIndex(shopcartParam);
            if (shopcartResult.getStatus() != MsgStatus.NORMAL) {
                setResultInfo(shopcartResult.getStatus().getCode(),
                        shopcartResult.getMessage());
                return;
            }

            ShopcartModel shopcartModel = shopcartResult.getResult();

            if (shopcartModel == null) {
                setResultInfo(MsgStatus.NO_RESULT.getCode(),
                        ResultMsg.Common.QUERY_NO_RESULT);
                return;
            }

            List<Map<String, Object>> groups = shopcartModel.getShopcartGroup();

            List<Map<String, Object>> giftGroups = new ArrayList<Map<String, Object>>(), hgGroups = new ArrayList<Map<String, Object>>();

            for (Map<String, Object> group : groups) {
                if (group.get("groupType") == null)
                    continue;
                // 促销不满足条件, 前端不进行展示
                if (group.get("isTrue") != null && !group.get("isTrue").equals("Y"))
                    continue;
                if (group.get("groupType").equals(Const.GroupType.GIFT)) {
                    if (group.get("goodsGiftList") == null)
                        continue;
                    if (!group.get("goodsGiftList").getClass()
                            .isAssignableFrom(ArrayList.class))
                        continue;
                    // 过滤掉赠品列表为空的group, 为空时表示赠优惠券, 暂时不展示
                    if (((ArrayList<?>) group.get("goodsGiftList")).size() == 0)
                        continue;
                    giftGroups.add(group);
                } else if (group.get("groupType").equals(Const.GroupType.HG)) {
                    hgGroups.add(group);
                }
            }
            resultObj.put("giftList", giftGroups);
            resultObj.put("hgList", hgGroups);
            setResultInfo(MsgStatus.NORMAL.getCode(), ResultMsg.Common.OK);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_LIST_FAILURE);
        } finally {
            _result.setObjData(resultObj);
            write(request, response);
        }
    }

    /**
     * 获取加价购选项
     *
     * @param request
     * @param response
     * @param contentNo   识别码
     * @param memberKey   会员识别码
     * @param mul         来源
     * @param promoteType 促销类型
     * @param promoteId   根据 promoteType对应促销ID或商品ID
     * @date 02/12/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/hgOption")
    public void hgOption(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "promoteType", required = false) String promoteType,
            @RequestParam(value = "promoteId", required = false) String promoteId) {
        // START PARAMETER VALIDATION
        if (StringUtil.isEmpty(promoteType)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_TYPE_EMPTY).write(request,
                    response);
            return;
        }

        if (!promoteType.equals(Const.Promote.HG_GOODS_TYPE)
                && !promoteType.equals(Const.Promote.HG_RULE_TYPE)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_TYPE_WRONG).write(request,
                    response);
            return;
        }

        Long itemId = NumericUtil.parseLong(promoteId);

        if (itemId == null) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_ID_WRONG).write(request,
                    response);
            return;
        }
        // END PARAMETER VALIDATION

        ShopcartModel shopcartParam = new ShopcartModel();
        shopcartParam.setContentNo(contentNo);
        shopcartParam.setMemberKey(memberKey);
        shopcartParam.setMul(mul);

        JSONObject resultObj = new JSONObject();
        try {
            // 获取购物车信息
            ServiceMessage<ShopcartModel> shopcartResult = shopcartService
                    .shopcartIndex(shopcartParam);
            if (shopcartResult.getStatus() != MsgStatus.NORMAL) {
                setResultInfo(shopcartResult.getStatus().getCode(),
                        shopcartResult.getMessage());
                return;
            }

            ShopcartModel shopcartModel = shopcartResult.getResult();

            if (shopcartModel == null) {
                setResultInfo(MsgStatus.NO_RESULT.getCode(),
                        ResultMsg.Common.QUERY_NO_RESULT);
                return;
            }

            // Goods promote
            if (promoteType.equals(Const.Promote.HG_GOODS_TYPE)) {
                for (Goods goods : shopcartModel.getGoodsList()) {
                    if (goods.getGoodsId().longValue() != itemId.longValue())
                        continue;

                    resultObj.put(Const.ResultKey.PROMOTE_ITEM_LIST,
                            goods.getItemNameList());
                    resultObj.put(
                            Const.ResultKey.RULE_ITEM_ID,
                            goods.getRuleItemId() == null ? "0" : goods
                                    .getRuleItemId());
                    setResultInfo(MsgStatus.NORMAL.getCode(),
                            ResultMsg.Common.OK);
                    return;
                }
            } else { // Combination promote
                for (Map<String, Object> promoteItem : shopcartModel
                        .getShopcartGroup()) {
                    if (Long.valueOf(
                            String.valueOf(promoteItem.get("promoteRuleId")))
                            .longValue() != itemId.longValue())
                        continue;

                    resultObj.put(Const.ResultKey.PROMOTE_ITEM_LIST,
                            promoteItem.get("promoteItemList"));
                    resultObj.put(Const.ResultKey.RULE_ITEM_ID,
                            promoteItem.get("ruleItemId") == null ? "0"
                                    : promoteItem.get("ruleItemId"));
                    setResultInfo(MsgStatus.NORMAL.getCode(),
                            ResultMsg.Common.OK);
                    return;
                }
            }

            setResultInfo(MsgStatus.NO_RESULT.getCode(),
                    ResultMsg.PromoteAction.HG_NOT_FOUND);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(),
                    ResultMsg.PromoteAction.HG_LIST_FAILURE);
        } finally {
            _result.setObjData(resultObj);
            write(request, response);
        }
    }

    /**
     * 获取加价购/赠品商品列表
     *
     * @param request
     * @param response
     * @param contentNo
     * @param memberKey
     * @param mul
     * @param promoteType
     * @param promoteId
     * @param promoteItemId
     * @date 02/12/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/hgGoods")
    public void hgGoods(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "promoteType", required = false) String promoteType,
            @RequestParam(value = "promoteId", required = false) String promoteId,
            @RequestParam(value = "promoteItemId", required = false) String promoteItemId) {
        // START PARAMETER VALIDATION
        if (StringUtil.isEmpty(promoteType)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_TYPE_EMPTY).write(request,
                    response);
            return;
        }

        if (!promoteType.equals(Const.Promote.HG_GOODS_TYPE)
                && !promoteType.equals(Const.Promote.HG_RULE_TYPE)) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_TYPE_WRONG).write(request,
                    response);
            return;
        }

        Long itemId = NumericUtil.parseLong(promoteId);

        if (itemId == null) {
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(),
                    ResultMsg.PromoteAction.PROMOTE_ID_WRONG).write(request,
                    response);
            return;
        }
        // END PARAMETER VALIDATION

        ShopcartModel shopcartParam = new ShopcartModel();
        shopcartParam.setContentNo(contentNo);
        shopcartParam.setMemberKey(memberKey);
        shopcartParam.setMul(mul);

        JSONObject resultObj = new JSONObject();
        try {
            // 获取购物车信息
            ServiceMessage<ShopcartModel> shopcartResult = shopcartService
                    .shopcartIndex(shopcartParam);
            if (shopcartResult.getStatus() != MsgStatus.NORMAL) {
                setResultInfo(shopcartResult.getStatus().getCode(),
                        shopcartResult.getMessage());
                return;
            }

            ShopcartModel shopcartModel = shopcartResult.getResult();
            // Goods promote
            if (promoteType.equals(Const.Promote.HG_GOODS_TYPE)) {
                for (Goods goods : shopcartModel.getGoodsList()) {
                    if (goods.getGoodsId().longValue() != itemId.longValue())
                        continue;

                    // promoteItemId 不为空,加价购选项商品
                    if (StringUtil.isNotEmpty(promoteItemId)) {
                        List<Map<String, Object>> itemList = goods
                                .getItemNameList();
                        for (Map<String, Object> item : itemList) {
                            if (!item.get("itemId").toString()
                                    .equals(promoteItemId))
                                continue;

                            resultObj.put("goodstList", item.get("goodstList"));
                            resultObj.put("maxCount", item.get("hgCount") == null ? 0 : item.get("hgCount"));
                            setResultInfo(MsgStatus.NORMAL.getCode(),
                                    ResultMsg.Common.OK);
                            return;
                        }
                    } else { // promoteItemId 为空,赠品商品
                        resultObj.put("goodstList", goods.getGoodsGiftList());
                        resultObj.put("maxCount", goods.getGiftMaxCount() == null ? 0 : goods.getGiftMaxCount());
                        setResultInfo(MsgStatus.NORMAL.getCode(),
                                ResultMsg.Common.OK);
                        return;
                    }
                }
            } else { // Combination promote
                for (Map<String, Object> promoteItem : shopcartModel
                        .getShopcartGroup()) {
                    if (Long.valueOf(
                            String.valueOf(promoteItem.get("promoteRuleId")))
                            .longValue() != itemId.longValue())
                        continue;
                    // promoteItemId 不为空,加价购选项商品
                    if (StringUtil.isNotEmpty(promoteItemId)) {
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> itemList = (List<Map<String, Object>>) promoteItem
                                .get("promoteItemList");
                        for (Map<String, Object> item : itemList) {
                            if (!item.get("itemId").toString()
                                    .equals(promoteItemId))
                                continue;

                            resultObj.put("goodstList", item.get("goodstList"));
                            resultObj.put("maxCount", item.get("hgCount") == null ? 0 : item.get("hgCount"));
                            setResultInfo(MsgStatus.NORMAL.getCode(),
                                    ResultMsg.Common.OK);
                            return;
                        }
                    } else { // promoteItemId 为空,赠品商品
                        resultObj.put("goodstList",
                                promoteItem.get("goodsGiftList"));
                        resultObj.put("maxCount", promoteItem.get("giftCount") == null ? 0 : promoteItem.get("giftCount"));
                        setResultInfo(MsgStatus.NORMAL.getCode(),
                                ResultMsg.Common.OK);
                        return;
                    }
                }
            }

            setResultInfo(MsgStatus.NO_RESULT.getCode(),
                    ResultMsg.PromoteAction.HG_NOT_FOUND);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(),
                    ResultMsg.PromoteAction.HG_LIST_FAILURE);
        } finally {
            _result.setObjData(resultObj);
            write(request, response);
        }
    }

    /**
     * 选择加价购/赠品商品
     *
     * @param request
     * @param response
     * @param contentNo
     * @param memberKey
     * @param mul
     * @param promoteType
     * @param promoteId
     * @param promoteItemId
     * @param goodsIds
     * @date 02/12/14
     * @author qiaoyu
     * @version 1.0
     */
    @RequestMapping("/choose")
    public void choose(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "promoteType", required = false) String promoteType,
            @RequestParam(value = "promoteId", required = false) String promoteId,
            @RequestParam(value = "promoteItemId", required = false) String promoteItemId,
            @RequestParam(value = "goodsIds", required = false) String goodsIds) {
        ShopcartGoods shopcartGoods = new ShopcartGoods();
        shopcartGoods.setMul(mul);
        shopcartGoods.setContentNo(contentNo);
        shopcartGoods.setMemberKey(memberKey);
        shopcartGoods.setPromoteType(promoteType);
        if (promoteId != null && !"0".equals(promoteId)) {
            shopcartGoods.setPromoteId(NumericUtil.parseLong(promoteId));
        }
        shopcartGoods.setPromoteItemId(NumericUtil.parseLong(promoteItemId));
        shopcartGoods.setGoodsIds(goodsIds);

        ServiceMessage<String> chooseResult = null;
        try {
            chooseResult = shopcartGoodsService
                    .promoteUpdateGoods(shopcartGoods);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResultInfo(chooseResult,
                    ResultMsg.PromoteAction.CHOOSE_FAILURE).write(request,
                    response);
        }
    }

    /**
     * 删除加价购/赠品选项
     *
     * @param request
     * @param response
     * @param contentNo
     * @param memberKey
     * @param mul
     * @param promoteType
     * @param promoteItemId
     * @param promoteId
     */
    @RequestMapping("/del")
    public void del(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "promoteType", required = false) String promoteType,
            @RequestParam(value = "promoteItemId", required = false) String promoteItemId,
            @RequestParam(value = "promoteId", required = false) String promoteId) {
        ShopcartGoods shopcartGoods = new ShopcartGoods();
        shopcartGoods.setContentNo(contentNo);
        shopcartGoods.setMemberKey(memberKey);
        shopcartGoods.setMul(mul);
        shopcartGoods.setPromoteType(promoteType);
        shopcartGoods.setPromoteId(NumericUtil.parseLong(promoteId));
        shopcartGoods.setPromoteItemId(NumericUtil.parseLong(promoteItemId));

        ServiceMessage<String> delResult = null;
        try {
            delResult = shopcartGoodsService.promoteRemoveGoods(shopcartGoods);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this.setResult(delResult, ResultMsg.PromoteAction.DEL_FAILURE)
                    .write(request, response);
        }
    }

    /**
     * 根据促销id、促销详情id以及商品id获取赠品
     *
     * @param request
     * @param response
     * @param promoteRuleId
     * @param ruleItemId
     * @param goodsId
     */
    @RequestMapping("/hgGoodsNew")
    public void giftGoods(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "contentNo", required = false) String contentNo,
            @RequestParam(value = "memberKey", required = false) String memberKey,
            @RequestParam(value = "mul", required = false) String mul,
            @RequestParam(value = "promoteRuleId", required = false) String promoteRuleId,
            @RequestParam(value = "ruleItemId", required = false) String ruleItemId,
            @RequestParam(value = "promoteGiftType", required = false) String promoteGiftType,
            @RequestParam(value = "goodsIdAndProductId", required = false) String goodsIdAndProductId){

        ShopcartModel shopcartParam = new ShopcartModel();
        shopcartParam.setContentNo(contentNo);
        shopcartParam.setMemberKey(memberKey);
        shopcartParam.setMul(mul);

        JSONObject resultData = new JSONObject();

        ServiceMessage<ShopcartModel> initResult = null;

        try {
            initResult = shopcartService.shopcartIndex(shopcartParam);

             if (initResult.getStatus() != MsgStatus.NORMAL) {
                 setResultInfo(initResult.getStatus().getCode(),
                         initResult.getMessage());
                 return;
             }

             if(initResult==null||"".equals(initResult)){
                 setResultInfo("-1","购物车为空");
                 return;
             }

             ShopcartModel shopcartModel= initResult.getResult();
             JSONObject shopcartJson = JSONObject.fromObject(shopcartModel);
             Object shopcartGroup = shopcartJson.get("shopcartGroup");
             if(shopcartGroup==null||"".equals(shopcartGroup)){
                 setResultInfo("-1","未查询到促销信息");
                 return;
             }

             //1 : 非单品 正品,组赠品
             JSONArray shopcartArray = JSONArray.fromObject(shopcartGroup);
             if(promoteGiftType.equals("1")){ //1 : 非单品 正品,组赠品
                 Map<String,String> returnMap = new HashMap<String,String>();
                 for (Object shopcart : shopcartArray) {
                    JSONObject shopcartGroupJson = JSONObject.fromObject(shopcart);
                    String _promoteRuleId = StringUtil.getTrimString(shopcartGroupJson.get("promoteRuleId"));
                    String itemId = StringUtil.getTrimString(shopcartGroupJson.get("ruleItemId"));
                    if(_promoteRuleId.equals(promoteRuleId)){
                        Object goodsGiftList = shopcartGroupJson.get("goodsGiftList");//赠品
                        Object promoteItemList = shopcartGroupJson.get("promoteItemList");//加价购
                        if(goodsGiftList!=null&&!"".equals(goodsGiftList)){
                            if(itemId.equals(ruleItemId)){
                                JSONArray goodsGiftArray = JSONArray.fromObject(goodsGiftList);
                                resultData.put("shopcart", shopcart);
                            }
                        }else if(promoteItemList!=null&&!"".equals(promoteItemList)){
                            JSONArray promoteItemArray = JSONArray.fromObject(promoteItemList);
                            for (Object promoteItem : promoteItemArray) {
                                JSONObject promoteItemJson = JSONObject.fromObject(promoteItem);
                                String itemId2 = StringUtil.getTrimString(promoteItemJson.get("itemId"));
                                if(itemId2.equals(ruleItemId)){
                                    resultData.put("promoteItem", promoteItem);
                                }
                            }
                        }
                    }
                 }
             }else{ //1 : 单品 正品
                for (Object shopcart : shopcartArray) {
                    JSONObject shopcartOne = JSONObject.fromObject(shopcart);
                    Object goodList = shopcartOne.get("goodsList");
                    JSONArray goodsArray = JSONArray.fromObject(goodList);
                    for (Object good : goodsArray) {
                        JSONObject goodJson = JSONObject.fromObject(good);
                        String goodsId = goodJson.getString("goodsId");
                        String productId = goodJson.getString("productId");
                        String str = goodsId+","+productId;
                        if(goodsIdAndProductId.equals(str)){
                            if(promoteGiftType.equals("2")){
                                Object goodsGiftList =goodJson.get("goodsGiftList");
                                if(goodsGiftList!=null&&!"".equals(goodsGiftList)){
                                    JSONArray goodsGiftArray = JSONArray.fromObject(goodsGiftList);
                                    resultData.put("goodsGiftList", goodsGiftArray);
                                }
                            }else if(promoteGiftType.equals("3")){
                                Object goodsList =goodJson.get("goodstList");
                                if(goodsList!=null&&!"".equals(goodsList)){
                                    JSONArray goodArray = JSONArray.fromObject(goodsList);
                                    resultData.put("goodsList", goodArray);
                                }
                            }
                        }
                    }
                }
             }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            this._result.setObjData(resultData);
            this.write(request, response);
        }
    }

}
package com.j1.mai.action;

import java.math.BigDecimal;
import java.util.List;

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

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.j1.base.dto.ServiceMessage;
import com.j1.base.order.dto.CouponsAssignParam;
import com.j1.base.order.model.EcCoupons;
import com.j1.base.order.model.FreeCoupon;
import com.j1.base.order.model.FreePromoteGoods;
import com.j1.base.order.model.ShopcartGoods;
import com.j1.base.page.Page;
import com.j1.base.page.PageRequest;
import com.j1.base.page.Pageable;
import com.j1.base.type.MsgStatus;
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.member.model.Member;
import com.j1.member.model.MemberPointsHis;
import com.j1.member.model.MemberPointsSetting;
import com.j1.soa.common.ResultMsg;
import com.j1.soa.resource.member.api.MemberPointHisService;
import com.j1.soa.resource.member.api.MemberService;
import com.j1.soa.resource.order.api.EcCouponsService;
import com.j1.soa.resource.order.api.FreeCouponService;
import com.j1.soa.resource.order.api.FreePromoteGoodsService;
import com.j1.soa.resource.order.api.ShopcartGoodsService;

/**
 * 上海健一网大药房连锁经营有限公司
 *
 * @Title: ShakeAction.java
 * @Package com.j1.mai.action
 * @Description: 摇一摇
 * @author guguangming
 * @date 2015年11月24日 上午11:25:27
 * @version V1.0
 */
@Controller
@Scope("request")
@RequestMapping("/mall")
public class PointsMall extends SoaApiBaseAction {

    static final Logger           LOG = Logger.getLogger(PointsMall.class);
    @Autowired
    private CheckMemberKeyService checkMemberKeyService;
    @Autowired
    private MemberService         memberService;
    @Autowired
    FreeCouponService             freeCouponService;
    @Autowired
    FreePromoteGoodsService       freePromoteGoodsService;
    @Autowired
    private EcCouponsService      ecCouponsService;
    @Autowired
    private MemberPointHisService memberPointHisService;
    @Autowired
    private ShopcartGoodsService  shopcartGoodsService;

    /**
     * @author guguangming
     * @date 2016年1月11日 下午4:07:08
     * @Title: toFreeCouponMain
     * @Description: 积分兑换优惠券界面
     * @param request
     * @param response
     * @param memberKey
     * @param currentPage
     * @throws
     */
    @RequestMapping("/toFreeCouponMain")
    public void toFreeCouponMain(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "memberKey", required = false) String memberKey, @RequestParam(value = "currentPage", required = false) String currentPage) {
        // 1、判断参数
        if (StringUtil.isEmpty(memberKey) || StringUtil.isEmpty(currentPage)) {
            logger.error(":" + request.getRequestURL() + "?" + request.getQueryString());
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(), "缺少参数!").write(request, response);
            return;
        }
        // 2、获取会员信息
        try {
            Member queryParam = new Member();
            queryParam.setMemberKey(memberKey);
            ServiceMessage<Member> memberResult = memberService.selectByPrimaryKey(queryParam);
            if (memberResult.getStatus() != MsgStatus.NORMAL) {
                logger.error(memberResult.getStatus().getCode() + ":" + memberResult.getMessage());
                this.setResultInfo(memberResult.getStatus().getCode(), "请登录");
                return;
            }
            _result.put("loginName", memberResult.getResult().getLoginName());
            _result.put("currentPoints", memberResult.getResult().getCurrentPoints());// 可用积分
            // 3、获取可用的积分兑换优惠券活动
            Pageable<FreeCoupon> pageable = new PageRequest<FreeCoupon>(StringUtil.toInt(currentPage, 1), 20, new FreeCoupon());
            ServiceMessage<Page<FreeCoupon>> resultFreeCoupon = freeCouponService.queryEnableFreeCouponPage(pageable);
            if (resultFreeCoupon.getStatus() != MsgStatus.NORMAL) {
                this.setResultInfo(resultFreeCoupon.getStatus().getCode(), resultFreeCoupon.getMessage());
                return;
            }
            _result.put("totalPage", resultFreeCoupon.getResult().getTotalPage());
            _result.put("listFreeCoupon", resultFreeCoupon.getResult().getData());// 可用积分
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(), ResultMsg.PointsMall.TO_FREE_COUPON_MAIN_FAILURE);
        } finally {
            write(request, response);
        }

    }
/**
 *
 * @author guguangming
 * @date 2016年1月19日 下午4:42:41
 * @Title: toFreePromoteMain
 * @Description:
 * @param request
 * @param response
 * @param memberKey
 * @param currentPage
 * @throws
 */
    @RequestMapping("/toFreePromoteMain")
    public void toFreePromoteMain(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "memberKey", required = false) String memberKey, @RequestParam(value = "currentPage", required = false) String currentPage) {
        // 1、判断参数
        if (StringUtil.isEmpty(memberKey) || StringUtil.isEmpty(currentPage)) {
            logger.error("积分兑换商品:" + request.getRequestURL() + "?" + request.getQueryString());
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(), "缺少参数").write(request, response);
            return;
        }
        try {
            // 2、获取会员信息
            Member queryParam = new Member();
            queryParam.setMemberKey(memberKey);
            ServiceMessage<Member> memberResult = memberService.selectByPrimaryKey(queryParam);
            if (memberResult.getStatus() != MsgStatus.NORMAL) {
                logger.error(memberResult.getStatus().getCode() + ":" + memberResult.getMessage());
                this.setResultInfo(memberResult.getStatus().getCode(), "请登录!");
                return;
            }
            _result.put("loginName", memberResult.getResult().getLoginName());
            _result.put("currentPoints", memberResult.getResult().getCurrentPoints());// 可用积分
            // 3、获取可用的积分兑换优惠券活动
            Pageable<FreePromoteGoods> pageable = new PageRequest<FreePromoteGoods>(StringUtil.toInt(currentPage, 1), 20, new FreePromoteGoods());
            ServiceMessage<Page<FreePromoteGoods>> resultFreePromoteGoods = freePromoteGoodsService.queryFreePromoteGoodsPage(pageable);
            if (resultFreePromoteGoods.getStatus() != MsgStatus.NORMAL) {
                logger.error("toFreePromoteMain:" + resultFreePromoteGoods.getStatus().getCode() + ":" + resultFreePromoteGoods.getMessage());
                this.setResultInfo(resultFreePromoteGoods.getStatus().getCode(), resultFreePromoteGoods.getMessage());
                return;
            }
            _result.put("totalPage", resultFreePromoteGoods.getResult().getTotalPage());
            _result.put("listresultFreePromoteGoods", resultFreePromoteGoods.getResult().getData());// 可用积分
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(), ResultMsg.PointsMall.TO_FREE_PROMOTE_MAIN_FAILURE);
        } finally {
            write(request, response);
        }

    }
/**
 *
 * @author guguangming
 * @date 2016年1月19日 下午4:02:04
 * @Title: pointsBuyCoupon
 * @Description: 积分兑换优惠券
 * @param request
 * @param response
 * @param memberKey
 * @param freeCouponId
 * @throws
 */
    @RequestMapping("/pointsBuyCoupon")
    public void pointsBuyCoupon(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "memberKey", required = false) String memberKey, @RequestParam(value = "freeCouponId", required = false) String freeCouponId) {
        // 1、判断参数
        if (StringUtil.isEmpty(memberKey) || StringUtil.isEmpty(freeCouponId)) {
            logger.error("积分兑换优惠券:" + request.getRequestURL() + "?" + request.getQueryString());
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(), "缺少参数").write(request, response);
            return;
        }
        try {
            // 2、获取会员信息
            Member queryParam = new Member();
            queryParam.setMemberKey(memberKey);
            ServiceMessage<Member> memberResult = memberService.selectByPrimaryKey(queryParam);
            if (memberResult.getStatus() != MsgStatus.NORMAL) {
                logger.error(memberResult.getStatus().getCode() + ":" + memberResult.getMessage());
                this.setResultInfo(memberResult.getStatus().getCode(), "请登录!");
                return;
            }
            Member member = memberResult.getResult();
            Long memberId = member.getMemberId();
            // 2、获取当前活动信息
            ServiceMessage<FreeCoupon> freeCouponResult = freeCouponService.queryEnableFreeCouponByFreeCouponId(NumericUtil.parseLong(freeCouponId));
            if (!freeCouponResult.getStatus().equals(MsgStatus.NORMAL)) {
                logger.error("查询活动信息失败:" + freeCouponResult.getMessage());
                if (freeCouponResult.getStatus().equals(MsgStatus.NO_RESULT)) {
                    this.setResultInfo(freeCouponResult.getStatus().getCode(), "没有找到相应的活动,请联系客服!");// 重新定义返回语句用于前台显示
                    return;
                } else {
                    this.setResultInfo(freeCouponResult.getStatus().getCode(), freeCouponResult.getMessage());
                    return;
                }
            }
            FreeCoupon freeCoupon = freeCouponResult.getResult();
            if (member.getCurrentPoints().intValue() >= freeCoupon.getCouponPoints().intValue()) {
                CouponsAssignParam param = new CouponsAssignParam();
                /* 会员id */
                param.setMemberId(memberId);
                /* 批次号 */
                param.setPublishId(freeCoupon.getPublishId());
                /* 领取数量 */
                param.setAssignCouponsCount(1);
                ServiceMessage<List<EcCoupons>> EcCouponsMsg = ecCouponsService.saveCouponsByMemberToPublishId(param);
                if (!EcCouponsMsg.getStatus().equals(MsgStatus.NORMAL)) {
                    logger.error("添加优惠券到用户接口异常:" + EcCouponsMsg.getMessage());
                    if (EcCouponsMsg.getStatus().equals(MsgStatus.NO_RESULT)) {
                        this.setResultInfo(EcCouponsMsg.getStatus().getCode(), "优惠卷已兑换完,请下次再来!");
                        return;
                    } else {
                        this.setResultInfo(EcCouponsMsg.getStatus().getCode(), EcCouponsMsg.getMessage());
                        return;
                    }
                } else {
                    MemberPointsHis memberPointsHis = new MemberPointsHis();
                    memberPointsHis.setMemberId(memberId);
                    memberPointsHis.setPoints(-freeCoupon.getCouponPoints().intValue());
                    memberPointsHis.setChangeNotes("兑换优惠劵");
                    MemberPointsSetting memberPointsSetting = new MemberPointsSetting();
                    memberPointsSetting.setPointsType("coupon_points");// 积分兑换使用
                    ServiceMessage<MemberPointsHis> msg = memberPointHisService.changePointsNoRankId(memberPointsHis, memberPointsSetting);
                    if (!msg.getStatus().equals(MsgStatus.NORMAL)) {
                        logger.error("调取扣除积分接口失败 getMessage():" + msg.getMessage() + "memberId:" + memberId);
                        this.setResultInfo(EcCouponsMsg.getStatus().getCode(), EcCouponsMsg.getMessage());
                        return;
                    } else {
                        _result.put("currentPoints", member.getCurrentPoints() - freeCoupon.getCouponPoints().intValue());
                        return;
                    }
                }
            } else {
                this.setResultInfo("4", "剩余积分不足");
                return;
            }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(), ResultMsg.PointsMall.POINTS_BUY_COUPON__FAILURE);
        } finally {
            write(request, response);
        }

    }

    /**
     * @author guguangming
     * @date 2016年1月13日 下午1:56:20
     * @Title: pointsBuyFreePromoteGoods
     * @Description: 积分兑换商品
     * @param request
     * @param response
     * @param memberKey
     * @param multiId 43--app免费频道,44--M站免费频道
     * @param mul
     * @param contentNo
     * @throws
     */
    @RequestMapping("/pointsBuyFreePromoteGoods")
    public void pointsBuyFreePromoteGoods(HttpServletRequest request, HttpServletResponse response,
                                          @RequestParam(value = "memberKey", required = false) String memberKey,
                                          @RequestParam(value = "freeGoodsId", required = false) String freeGoodsId,
                                          @RequestParam(value = "multiId", required = false) String multiId,
                                          @RequestParam(value = "mul", required = false) String mul,
                                          @RequestParam(value = "contentNo", required = false) String contentNo) {
        // 1、判断参数
        if (StringUtil.isEmpty(memberKey) || StringUtil.isEmpty(freeGoodsId) || StringUtil.isEmpty(multiId) || StringUtil.isEmpty(mul) || StringUtil.isEmpty(contentNo)) {
            logger.error("积分兑换商品:" + request.getRequestURL() + "?" + request.getQueryString());
            this.setResultInfo(MsgStatus.PARAMS_ERROR.getCode(), "缺少参数").write(request, response);
            return;
        }
        try {
            // 1、获取会员信息
            // 2、获取会员信息
            FreePromoteGoods freePromoteGoods = new FreePromoteGoods();
            Member queryParam = new Member();
            queryParam.setMemberKey(memberKey);
            ServiceMessage<Member> memberResult = memberService.selectByPrimaryKey(queryParam);
            if (memberResult.getStatus() != MsgStatus.NORMAL) {
                logger.error(memberResult.getStatus().getCode() + ":" + memberResult.getMessage());
                this.setResultInfo(memberResult.getStatus().getCode(), "请登录!");
                return;
            }
            Member member = memberResult.getResult();
            Long memberId = member.getMemberId();

            ServiceMessage<FreePromoteGoods> resFreePromoteGoods = freePromoteGoodsService.queryEnableFreeGoodsByFreeGoodsId(NumericUtil.parseLong(freeGoodsId));
            if (!resFreePromoteGoods.getStatus().equals(MsgStatus.NORMAL)) {
                logger.error("根据id查询在活动日期内的商品:" + resFreePromoteGoods.getMessage());
                if (resFreePromoteGoods.getStatus().equals(MsgStatus.NO_RESULT)) {
                    this.setResultInfo(resFreePromoteGoods.getStatus().getCode(), "该商品兑换活动已结束");
                    return;
                } else {
                    this.setResultInfo(resFreePromoteGoods.getStatus().getCode(), resFreePromoteGoods.getMessage());
                    return;
                }
            } else {
                freePromoteGoods = resFreePromoteGoods.getResult();
                if (freePromoteGoods.getFreeAmount().compareTo(new BigDecimal(1)) == -1) {
                    this.setResultInfo("4", "该商品已兑换完");
                    return;
                }
            }
            int goodsPoints= Integer.parseInt(freePromoteGoods.getGoodsPoints());
            if(goodsPoints>member.getCurrentPoints()){
                this.setResultInfo("5", "当前积分不足");
                return;
            }
            // 2、获取当前活动信息
            ShopcartGoods shopcartGoodsParam = new ShopcartGoods();
            shopcartGoodsParam.setMemberKey(member.getMemberKey());
            shopcartGoodsParam.setContentNo(contentNo);
            shopcartGoodsParam.setGoodsId(NumericUtil.parseLong(freeGoodsId));
            // 来源渠道
            shopcartGoodsParam.setMultiId(Integer.parseInt(multiId));
            shopcartGoodsParam.setMul(mul);
            // 多规格ID
            shopcartGoodsParam.setSkuId(0L);
            // 数量
            shopcartGoodsParam.setAmount(new BigDecimal(1));
            // add加/sub减/update修改/select修改选中
            shopcartGoodsParam.setType("add");
            // 是否选中Y/N
            shopcartGoodsParam.setIsSelected("Y");

            ServiceMessage<String> shopCartMsg = shopcartGoodsService.shopcartUpdateGoods(shopcartGoodsParam);
            if (!shopCartMsg.getStatus().equals(MsgStatus.NORMAL)) {
                this.setResultInfo(shopCartMsg.getStatus().getCode(), shopCartMsg.getMessage());
            } else {
                this.setResultInfo("0", "成功加入购物车");
            }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            setResultInfo(MsgStatus.EXCEPTION.getCode(), ResultMsg.PointsMall.POINTS_BUY_COUPON__FAILURE);
        } finally {
            write(request, response);
        }

    }

}
上一篇:work staff


下一篇:Windows 配置 Aria2 及 Web 管理面板教程