package com.iamberry.wechat.handles.integral;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.integral.IntegralCart;
import com.iamberry.wechat.core.entity.integral.IntegralItem;
import com.iamberry.wechat.core.entity.integral.IntegralOrder;
import com.iamberry.wechat.core.entity.integral.IntegralProduct;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.face.integral.IntegralItemService;
import com.iamberry.wechat.face.integral.IntegralOrderService;
import com.iamberry.wechat.face.integral.IntegralProductService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wechat/integral_order")
public class IntegralOrderHandler {
    private Logger logger = LoggerFactory.getLogger(IntegralOrderHandler.class);

    @Autowired
    private IntegralOrderService integralOrderService;
    @Autowired
    private IntegralItemService integralItemService;
    @Autowired
    private IntegralProductService integralProductService;
    @Autowired
    private MemberService memberService;

    /**
     *积分兑换
     * @param req
     * @return
     */
    @RequestMapping("/add_order")
    @ResponseBody
    public ResultMsg listProduct(HttpServletRequest req,String integralProductId){
        ResultMsg rm=new ResultMsg();
        Member m= WechatUtils.getUserBySession(req);

           /*存放数据*/
        Map<String,Object> reqMap = new HashMap<String,Object>();

        if(integralProductId == null ){
            return new ResultMsg(false,"500","未获取到积分商品，兑换失败",null);
        }
        List<IntegralCart> integralCartList = new ArrayList<>();
        try{
            String[] productId = integralProductId.split("-");
            Integer[] proId = new Integer[productId.length];
            for (int i = 0; i < productId.length; i++) {
                IntegralCart integralCart = new IntegralCart();
                integralCart.setProductId(Integer.valueOf(productId[i]));
                integralCart.setNum(1);
                integralCartList.add(integralCart);
            }
            Map<String,Object> map = integralOrderService.addOrder(m.getUserOpenid(),integralCartList);
        }catch (RuntimeException e){
            logger.info(e.getMessage());
            return new ResultMsg(false,"500","兑换失败,请重试！",null);
        }catch (Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            return new ResultMsg(false,"500","兑换失败,请重试！",null);
        }
        rm.setStatus(true);
        rm.setResultCode(ResultInfo.SUCCESSCODE);
        rm.setMessage(NameUtils.getConfig("兑换成功"));
        return rm;
    }

    /**
     *积分兑换（订单）集合
     * @param req
     * @param pageSize
     * @param pageNO
     * @return
     */
    @RequestMapping("/list_order")
    @ResponseBody
    public ResultMsg listProduct(HttpServletRequest req,IntegralOrder integralOrder,
                                 @RequestParam(value= "pageSize",defaultValue= "10" ,required=false) Integer pageSize,
                                 @RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO){
        ResultMsg rm=new ResultMsg();
        Member m= WechatUtils.getUserBySession(req);
        String openid=m.getUserOpenid();
        if (m == null || openid == null) {
            rm.setMessage(ResultInfo.loginOutError);
            return rm;
        }
        Integer totalNum = 0;

        integralOrder.setIntegralOrderOpenId(m.getUserOpenid());

        // 封装请求数据
        PageRequest<IntegralOrder> pageRequest = new PageRequest<>(integralOrder, pageNO, pageSize, totalNum == 0);
        // 查询订单列表
        PagedResult<IntegralOrder> result = integralOrderService.listIntegralProductPage(pageRequest);

        Member member = memberService.getMemberByUserOpenId(m.getUserOpenid());

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("integralOrder",result.getDataList());
        map.put("integral",member.getUserSurplusIntegral());

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

    /**
     *积分兑换详情
     * @param req
     * @param integralOrderId
     * @return
     */
//    @RequestMapping("/order_desc")
//    @ResponseBody
//    public ResultMsg productDesc(HttpServletRequest req,String integralOrderId) throws  Exception{
//        ResultMsg rm=new ResultMsg();
//        Member m= WechatUtils.getUserBySession(req);
//
//        if(integralOrderId == null || "".equals(integralOrderId)){
//            rm.setStatus(true);
//            rm.setResultCode(ResultInfo.ERRORCODE);
//            rm.setMessage("未获取到积分兑换详情！");
//            return rm;
//        }
//
//        IntegralOrder integralOrder = integralOrderService.getIntegralOrderById(integralOrderId);
//        IntegralItem integralItem = new IntegralItem();
//        integralItem.setIntegralItemOrderId(integralOrderId);
//        List<IntegralItem> integralItemList = integralItemService.getIntegralItemList(integralItem);
//        integralOrder.setIntegralItemList(integralItemList);
//
//        Map<String,Object> map = new HashMap<>();
//
//        rm.setStatus(true);
//        rm.setResultCode(ResultInfo.SUCCESSCODE);
//        rm.setMessage(NameUtils.getConfig("SUCCESSINFO"));
//        rm.setData(map);
//        return rm;
//    }


}
