package com.slodon.b2b2c.controller.goods.seller;

import com.slodon.b2b2c.aop.VendorLogger;
import com.slodon.b2b2c.core.constant.GoodsCategoryConst;
import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.constant.GoodsPlatformConst;
import com.slodon.b2b2c.core.constant.StoreConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.*;
import com.slodon.b2b2c.goods.dto.GoodsPlatformImportDTO;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.goods.example.GoodsPlatformExample;
import com.slodon.b2b2c.goods.example.GoodsPlatformPictureExample;
import com.slodon.b2b2c.goods.example.ProductPlatformExample;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.goods.pojo.GoodsPlatform;
import com.slodon.b2b2c.goods.pojo.GoodsPlatformPicture;
import com.slodon.b2b2c.goods.pojo.ProductPlatform;
import com.slodon.b2b2c.model.goods.*;
import com.slodon.b2b2c.model.seller.StoreBindCategoryModel;
import com.slodon.b2b2c.seller.example.StoreBindCategoryExample;
import com.slodon.b2b2c.seller.pojo.StoreBindCategory;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.vo.goods.GoodsPlatformVO;
import com.slodon.b2b2c.vo.goods.SellerGoodsPlatformDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "seller-商品资料库导入")
@RestController
@Slf4j
@RequestMapping("v3/goods/seller/goods/platform")
public class SellerGoodsPlatformController extends BaseController {

    @Resource
    private GoodsPlatformModel goodsPlatformModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private ProductPlatformModel productPlatformModel;
    @Resource
    private GoodsPlatformPictureModel goodsPlatformPictureModel;
    @Resource
    private GoodsSellerModel goodsSellerModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private StoreBindCategoryModel storeBindCategoryModel;

    @ApiOperation("商品库列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "brandName", value = "品牌名称", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "query"),
            @ApiImplicitParam(name = "isVirtualGoods", value = "是否是虚拟商品：1-实物商品；2-虚拟商品", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<GoodsPlatformVO>> getList(HttpServletRequest request, String goodsName, String brandName,
                                                       Integer isVirtualGoods, Integer categoryId) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsPlatformExample example = new GoodsPlatformExample();
        example.setGoodsNameLike(goodsName);
        example.setBrandNameLike(brandName);
        example.setIsVirtualGoods(isVirtualGoods);
        example.setState(GoodsPlatformConst.GOODS_STATE_2);
        if (!StringUtil.isNullOrZero(categoryId)) {
            //查询商品分类信息
            GoodsCategory goodsCategory = goodsCategoryModel.getGoodsCategoryByCategoryId(categoryId);
            AssertUtil.notNull(goodsCategory, "获取分类信息为空");
            if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_1) {
                example.setCategoryId1(categoryId);
            } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_2) {
                example.setCategoryId2(categoryId);
            } else if (goodsCategory.getGrade() == GoodsCategoryConst.CATEGORY_GRADE_3) {
                example.setCategoryId3(categoryId);
            }
        }
        //入驻店铺过滤掉不属于自己店铺分类的商品
        if (vendor.getStore().getIsOwnStore().equals(StoreConst.NO_OWN_STORE)) {
            StringBuilder categoryIds = new StringBuilder();
            StoreBindCategoryExample storeBindCategoryExample = new StoreBindCategoryExample();
            storeBindCategoryExample.setStoreId(vendor.getStoreId());
            List<StoreBindCategory> storeBindCategoryList = storeBindCategoryModel.getStoreBindCategoryList(storeBindCategoryExample, null);
            if (!CollectionUtils.isEmpty(storeBindCategoryList)) {
                storeBindCategoryList.forEach(storeBindCategory -> {
                    categoryIds.append(",").append(storeBindCategory.getGoodsCategoryId3());
                });
                example.setCategoryId3In(categoryIds.toString().substring(1));
            } else {
                //任意一个不存在的值
                example.setCategoryId3In("-1");
            }
        }
        //过滤掉属于自己店铺的商品
        example.setStoreIdNotEquals(vendor.getStoreId());
        example.setQueryStoreGoods("notNull");
        List<GoodsPlatform> list = goodsPlatformModel.getGoodsPlatformList(example, pager);
        List<GoodsPlatformVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(goods -> {
                vos.add(new GoodsPlatformVO(goods));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platformGoodsId", value = "平台库商品Id", required = true)
    })
    @GetMapping("detail")
    public JsonResult<SellerGoodsPlatformDetailVO> detail(HttpServletRequest request, @RequestParam(value = "platformGoodsId") Long platformGoodsId) {
        //查询商品信息
        GoodsPlatform goodsPlatform = goodsPlatformModel.getGoodsPlatformByPlatformGoodsId(platformGoodsId);
        AssertUtil.notNull(goodsPlatform, "商品不存在，请重试！");

        SellerGoodsPlatformDetailVO detailVO = new SellerGoodsPlatformDetailVO(goodsPlatform);

        //正常的货品
        ProductPlatformExample productExample = new ProductPlatformExample();
        productExample.setPlatformGoodsId(platformGoodsId);
        productExample.setState(GoodsConst.PRODUCT_STATE_1);
        productExample.setOrderBy("platform_product_id asc");
        List<ProductPlatform> productPlatformList = productPlatformModel.getProductPlatformList(productExample, null);
        AssertUtil.notEmpty(productPlatformList, "商品不存在");
        //最低价和最高价
        BigDecimal minPrice = new BigDecimal(Integer.MAX_VALUE);
        BigDecimal maxPrice = BigDecimal.ZERO;
        List<SellerGoodsPlatformDetailVO.SellerProductPlatformVO> productList = new ArrayList<>();
        for (ProductPlatform productPlatform : productPlatformList) {
            BigDecimal price = productPlatform.getProductPrice();
            if (minPrice.compareTo(price) > 0) {
                minPrice = price;
            }
            if (maxPrice.compareTo(price) < 0) {
                maxPrice = price;
            }
            productList.add(new SellerGoodsPlatformDetailVO.SellerProductPlatformVO(productPlatform));
        }
        detailVO.setMinPrice(minPrice);
        //最低价和最高价相等时只返回最低价
        if (minPrice.compareTo(maxPrice) == 0) {
            detailVO.setMaxPrice(null);
        } else {
            detailVO.setMaxPrice(maxPrice);
        }
        detailVO.setProductList(productList);

        //查询商品图片
        GoodsPlatformPictureExample goodsPictureExample = new GoodsPlatformPictureExample();
        goodsPictureExample.setPlatformGoodsId(platformGoodsId);
        goodsPictureExample.setOrderBy("is_main asc, picture_id asc");
        List<GoodsPlatformPicture> goodsPictureList = goodsPlatformPictureModel.getGoodsPlatformPictureList(goodsPictureExample, null);
        AssertUtil.notEmpty(goodsPictureList, "商品图片不存在");
        List<String> imageList = new ArrayList<>();
        goodsPictureList.forEach(goodsPlatformPicture -> {
            imageList.add(FileUrlUtil.getFileUrl(goodsPlatformPicture.getImagePath(), null));
        });
        detailVO.setImageList(imageList);
        return SldResponse.success(detailVO);
    }

    @ApiOperation("商品导入")
    @VendorLogger(option = "商品导入")
    @PostMapping("goodsImport")
    public JsonResult<Integer> goodsImport(HttpServletRequest request, GoodsPlatformImportDTO platformImportDTO) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        GoodsExample example = new GoodsExample();
        example.setStoreId(vendor.getStoreId());
        example.setPlatformGoodsId(platformImportDTO.getPlatformGoodsId());
        example.setStateNotEquals(GoodsConst.GOODS_STATE_DELETE);
        Integer count = goodsModel.getGoodsCount(example);
        AssertUtil.isTrue(count > 0, "店铺已有该平台库的商品");

        //查询平台库商品信息
        GoodsPlatform goodsPlatformDb = goodsPlatformModel.getGoodsPlatformByPlatformGoodsId(platformImportDTO.getPlatformGoodsId());
        AssertUtil.notNull(goodsPlatformDb, "商品不存在，请重试！");
        if (goodsPlatformDb.getIsVirtualGoods() == GoodsConst.IS_VIRTUAL_GOODS_1) {
            AssertUtil.isTrue(platformImportDTO.getFreightFee() == null
                    && StringUtil.isNullOrZero(platformImportDTO.getFreightId()), "请设置统一运费或选择运费模板");
        }

        //查询平台库货品信息
        ProductPlatformExample productExample = new ProductPlatformExample();
        productExample.setPlatformGoodsId(platformImportDTO.getPlatformGoodsId());
        productExample.setStateNotEquals(GoodsConst.PRODUCT_STATE_0);
        productExample.setOrderBy("platform_product_id asc");
        List<ProductPlatform> productPlatformList = productPlatformModel.getProductPlatformList(productExample, null);
        AssertUtil.notEmpty(productPlatformList, "商品不存在");

        goodsSellerModel.goodsPlatformImport(platformImportDTO, goodsPlatformDb, productPlatformList, vendor);
        return SldResponse.success("添加成功");
    }
}
