package com.cweb.controller.Goods;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.PageUtil;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonConfig;
import com.hai.entity.*;
import com.hai.goods.model.GoodsModel;
import com.hai.goods.service.GoodsDetailService;
import com.hai.goods.service.GoodsLogisticsService;
import com.hai.goods.service.GoodsSkuService;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighGoodsTypeService;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/goods")
@Api(value = "商品")
public class GoodsController {
    Logger log = LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private GoodsDetailService goodsDetailService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private GoodsLogisticsService logisticsService;

    @Resource
    private HighGoodsTypeService highGoodsTypeService;

    @Resource
    private GoodsSkuService goodsSkuService;

    @RequestMapping(value = "/getListGoodsDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品列表")
    public ResponseData getListGoodsDetail(
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "goodsType", required = false) Long goodsType,
            @RequestParam(value = "price", required = false) Integer price,
            @RequestParam(value = "companyId", required = false) Long companyId,
            @RequestParam(value = "goodsLabel", required = false) String goodsLabel,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {


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

            map.put("title", title);
            map.put("goodsType", goodsType);
            map.put("companyId", companyId);
            map.put("goodsLabel", goodsLabel);
            map.put("status", 1);


            List<GoodsDetail> list = goodsDetailService.getGoodsDetailList(map);

            List<GoodsModel> goodsModels = new ArrayList<>();

            for (GoodsDetail goodsDetail : list) {

                GoodsModel goodsModel = new GoodsModel();

                List<GoodsSku> goodsSku = goodsSkuService.getGoodsSkuList(goodsDetail.getId());
                if (goodsSku.size() > 0) {
                    BigDecimal minPrice = goodsSku.get(0).getPrice();
                    BigDecimal minOriginalPrice = goodsSku.get(0).getOriginalPrice();

                    for (GoodsSku sku : goodsSku) {
                        if (sku.getPrice().compareTo(minPrice) < 0) {
                            minPrice = sku.getPrice();
                            minOriginalPrice = sku.getOriginalPrice();
                        }
                    }
                    BeanUtils.copyProperties(goodsDetail, goodsModel);
                    goodsModel.setOriginalPrice(minOriginalPrice);
                    goodsModel.setPrice(minPrice);
                    goodsModel.setWhetherMultiple(goodsSku.size() != 1);

                    goodsModels.add(goodsModel);

                }
            }

            if (price == 1) {
                goodsModels = goodsModels.stream().sorted(Comparator.comparing(GoodsModel::getPrice)).collect(Collectors.toList());
            }
            if (price == 2) {
                goodsModels = goodsModels.stream().sorted(Comparator.comparing(GoodsModel::getPrice).reversed()).collect(Collectors.toList());
            }


            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, goodsModels.size(), pageSize, new PageInfo<>(goodsModels)));

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


    @RequestMapping(value = "/findGoodsDetailById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品详情")
    public ResponseData findGoodsDetailById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        try {

            GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(id);

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

            GoodsModel goodsModel = new GoodsModel();

            List<GoodsSku> goodsSku = goodsSkuService.getGoodsSkuList(goodsDetail.getId());
            if (goodsSku.size() > 0) {
                BigDecimal minPrice = goodsSku.get(0).getPrice();
                BigDecimal minOriginalPrice = goodsSku.get(0).getOriginalPrice();

                for (GoodsSku sku : goodsSku) {
                    if (sku.getPrice().compareTo(minPrice) < 0) {
                        minPrice = sku.getPrice();
                        minOriginalPrice = sku.getOriginalPrice();
                    }
                }
                BeanUtils.copyProperties(goodsDetail, goodsModel);
                goodsModel.setOriginalPrice(minOriginalPrice);
                goodsModel.setPrice(minPrice);
                goodsModel.setWhetherMultiple(goodsSku.size() != 1);

            }

            return ResponseMsgUtil.success(goodsModel);

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

    @RequestMapping(value = "/findGoodsSkuByGoodsId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品sku")
    public ResponseData findGoodsSkuByGoodsId(
            @RequestParam(value = "goodsId", required = true) Long goodsId
    ) {
        try {

            List<GoodsSku> goodsSkus = goodsSkuService.getGoodsSkuList(goodsId);

            if (goodsSkus.size() == 0) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相关商品规格信息");
            }

            return ResponseMsgUtil.success(goodsSkus);

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

    @RequestMapping(value = "/getGoodsTypeTree", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取商品类型树结构")
    public ResponseData getGoodsTypeTree(@RequestParam(name = "businessType", required = true) Integer businessType) {
        try {

            return ResponseMsgUtil.success(highGoodsTypeService.getGoodsTypeTree(businessType));

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

    @RequestMapping(value = "/getLogisticsMsg", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据快递单号查询物流信息")
    public ResponseData getLogisticsMsg(@RequestParam(name = "orderId", required = false) Long orderId) {
        try {

            return ResponseMsgUtil.success(logisticsService.getLogisticsMsg(orderId));

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


}

