package com.cweb.controller.goods;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.GoodsMsg;
import com.hfkj.entity.GoodsShoppingCart;
import com.hfkj.entity.GoodsSpecs;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.service.goods.GoodsMsgService;
import com.hfkj.service.goods.GoodsShoppingCartService;
import com.hfkj.service.goods.GoodsSpecsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/shoppingCart")
@Api(value = "购物车")
public class ShoppingCartController {

    Logger log = LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private GoodsMsgService goodsMsgService;

    @Resource
    private GoodsSpecsService goodsSpecsService;

    @Resource
    private GoodsShoppingCartService shoppingCartService;

    @RequestMapping(value = "/getShoppingCartList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询购物车列表")
    public ResponseData getShoppingCartList() {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userSession.getUser().getId());

            List<GoodsShoppingCart> list = shoppingCartService.getList(map);

            Map<String, List<GoodsShoppingCart>> collect = list.stream().collect(Collectors.groupingBy(GoodsShoppingCart::getMerName));

            List<JSONObject> countRecords = collect.keySet().stream().map(key -> {
                JSONObject goodObject = new JSONObject(true);
                goodObject.put("name",key.toUpperCase());
                goodObject.put("list",collect.get(key));
                System.out.println(goodObject);
                return goodObject;
            }).collect(Collectors.toList());

            return ResponseMsgUtil.success(countRecords);

        } catch (Exception e) {
            log.error("GoodsDetailController --> getListUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/insertShoppingCart", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增购物车")
    public ResponseData insertShoppingCart(@RequestBody GoodsShoppingCart shoppingCart) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            if (shoppingCart == null ||
                    shoppingCart.getGoodsId() == null ||
                    shoppingCart.getSpecsId() == null ||
                    shoppingCart.getNum() == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            GoodsMsg goodsMsg = goodsMsgService.queryDetail(shoppingCart.getGoodsId());
            GoodsSpecs specs = goodsSpecsService.queryDetail(shoppingCart.getSpecsId());

            if (goodsMsg == null || specs == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "添加商品不存在");
            }

            if (specs.getStock() < shoppingCart.getNum()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "超过最大库存！");
            }

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userSession.getUser().getId());
            map.put("goodsId", shoppingCart.getGoodsId());
            map.put("specsId", shoppingCart.getSpecsId());

            GoodsShoppingCart goodsShoppingCart = shoppingCartService.queryDetailByMap(map);

            if (goodsShoppingCart == null) {

                shoppingCart.setUserId(userSession.getUser().getId());
                shoppingCart.setTitle(goodsMsg.getTitle());
                shoppingCart.setGoodsType(goodsMsg.getType());
                shoppingCart.setImg(specs.getShowImg());
                shoppingCart.setSpecsId(specs.getId());
                shoppingCart.setSpecsName(specs.getName());
                shoppingCart.setLoseEfficacy(false);
                shoppingCart.setMerId(goodsMsg.getMerId());
                shoppingCart.setMerName(goodsMsg.getMerName());
                shoppingCart.setWhetherCheck(true);
                shoppingCart.setStatus(1);
                shoppingCart.setPrice(specs.getSalePrice());
                shoppingCart.setCreateTime(new Date());
                shoppingCart.setUpdateTime(new Date());

                shoppingCartService.create(shoppingCart);
            } else {
                int num = shoppingCart.getNum() + goodsShoppingCart.getNum();
                goodsShoppingCart.setNum(num);
                shoppingCartService.update(goodsShoppingCart);
            }

            return ResponseMsgUtil.success("成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> insertPrice() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/deleteShoppingCart", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除购物车信息")
    public ResponseData deleteShoppingCart(@RequestParam(value = "ids", required = true) String ids) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            String[] idArray = ids.split(",");

            for (String id : idArray) {

                GoodsShoppingCart shoppingCart = shoppingCartService.queryDetail(Long.valueOf(id));

                if (shoppingCart == null) {
                    log.error("GoodsDetailController -> findGoodsDetailById() error!");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相关信息");
                }

                if (!Objects.equals(userSession.getUser().getId(), shoppingCart.getUserId())) {
                    log.error("GoodsDetailController -> findGoodsDetailById() error!");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户信息错误");
                }


                shoppingCartService.delete(Long.valueOf(id));
            }

            return ResponseMsgUtil.success("删除成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/goodsEditNum", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "商品编辑数量")
    public ResponseData goodsEditNum(
            @RequestParam(value = "id", required = true) Long id,
            @RequestParam(value = "num", required = true) Integer num
    ) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            GoodsShoppingCart shoppingCart = shoppingCartService.queryDetail(id);

            GoodsSpecs specs = goodsSpecsService.queryDetail(shoppingCart.getSpecsId());

            if (!Objects.equals(userSession.getUser().getId(), shoppingCart.getUserId())) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户信息错误");
            }

            if (specs.getStock() < num) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "超过最大库存！");
            }

            shoppingCart.setNum(num);
            shoppingCart.setUpdateTime(new Date());
            shoppingCartService.update(shoppingCart);

            return ResponseMsgUtil.success("增加成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/whetherCheck", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "是否选中")
    public ResponseData whetherCheck(
            @RequestParam(value = "ids", required = true) String ids,
            @RequestParam(value = "whetherCheck", required = true) Integer whetherCheck
    ) {
        try {
            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            String[] idArray = ids.split(",");

            for (String id : idArray) {
                GoodsShoppingCart shoppingCart = shoppingCartService.queryDetail(Long.valueOf(id));

                if (!Objects.equals(userSession.getUser().getId(), shoppingCart.getUserId())) {
                    log.error("GoodsDetailController -> findGoodsDetailById() error!");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户信息错误");
                }

                shoppingCart.setWhetherCheck(whetherCheck == 1);
                shoppingCart.setUpdateTime(new Date());
                shoppingCartService.update(shoppingCart);
            }

            return ResponseMsgUtil.success("成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
