package com.cweb.controller.Goods;

import com.alipay.api.domain.Shop;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.GoodsDetail;
import com.hai.entity.GoodsShoppingCart;
import com.hai.entity.GoodsSku;
import com.hai.goods.model.ShoppingCartModel;
import com.hai.goods.service.GoodsDetailService;
import com.hai.goods.service.GoodsSkuService;
import com.hai.goods.service.ShoppingCartService;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

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

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private GoodsDetailService goodsDetailService;

    @Resource
    private GoodsSkuService goodsSkuService;

    @Resource
    private ShoppingCartService shoppingCartService;

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

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

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

            map.put("userId", userInfoModel.getHighUser().getId());

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

            List<ShoppingCartModel> shoppingCartModels = new ArrayList<>();

            for (GoodsShoppingCart shoppingCart : list) {

                ShoppingCartModel shoppingCartModel = new ShoppingCartModel();

                BeanUtils.copyProperties(shoppingCart, shoppingCartModel);

                GoodsSku sku = goodsSkuService.findGoodsSkuById(Long.valueOf(shoppingCart.getSku()));
                shoppingCartModel.setSkuName(sku.getName());

                GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(shoppingCart.getGoodsId());

                if (goodsDetail.getStatus() !=  1) {
                    shoppingCartModel.setLoseEfficacy(true);
                }

                if (sku.getStock() < Integer.parseInt(shoppingCart.getNum())) {
                    shoppingCartModel.setNum(String.valueOf(sku.getStock()));
                }

                shoppingCartModels.add(shoppingCartModel);

                }

            return ResponseMsgUtil.success(shoppingCartModels);

        } 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, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (shoppingCart == null ||
                    shoppingCart.getGoodsId() == null ||
                    shoppingCart.getSku() == null ||
                    shoppingCart.getNum() == null
            ) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(shoppingCart.getGoodsId());
            GoodsSku sku = goodsSkuService.findGoodsSkuById(Long.valueOf(shoppingCart.getSku()));

            if (goodsDetail == null || sku == null) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "添加商品不存在");
            }

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

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

            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("goodsId", shoppingCart.getGoodsId());
            map.put("sku", shoppingCart.getSku());

            GoodsShoppingCart goodsShoppingCart = shoppingCartService.findShoppingCartByMap(map);

            if (goodsShoppingCart == null) {

                shoppingCart.setUserId(userInfoModel.getHighUser().getId());
                shoppingCart.setTitle(goodsDetail.getName());
                shoppingCart.setImg(sku.getShowImg());
                shoppingCart.setOriginalPrice(sku.getOriginalPrice());
                shoppingCart.setLoseEfficacy(false);
                shoppingCart.setWhetherCheck(true);
                shoppingCart.setPrice(sku.getPrice());
                shoppingCart.setCreateTime(new Date());
                shoppingCart.setUpdateTime(new Date());

                shoppingCartService.insertShoppingCart(shoppingCart);
            } else {
                int num = Integer.parseInt(shoppingCart.getNum()) + Integer.parseInt(goodsShoppingCart.getNum());
                goodsShoppingCart.setNum(Integer.toString(num));
                shoppingCartService.updateShoppingCart(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, HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

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

            for (String id : idArray) {

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

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

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


                shoppingCartService.deleteShoppingCart(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) String num
            , HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            GoodsShoppingCart shoppingCart = shoppingCartService.findShoppingCartById(id);

            GoodsSku sku = goodsSkuService.findGoodsSkuById(Long.valueOf(shoppingCart.getSku()));

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

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

            shoppingCart.setNum(num);
            shoppingCart.setUpdateTime(new Date());
            shoppingCartService.updateShoppingCart(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) Boolean whetherCheck
            , HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

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

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

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

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

                shoppingCart.setWhetherCheck(whetherCheck);
                shoppingCart.setUpdateTime(new Date());
                shoppingCartService.updateShoppingCart(shoppingCart);
            }



            return ResponseMsgUtil.success("成功");

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

}
