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

import com.slodon.b2b2c.aop.OperationLogger;
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.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.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.goods.dto.GoodsPlatformDTO;
import com.slodon.b2b2c.goods.dto.GoodsPlatformInsertDTO;
import com.slodon.b2b2c.goods.example.*;
import com.slodon.b2b2c.goods.pojo.*;
import com.slodon.b2b2c.model.goods.*;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.vo.goods.GoodsPlatformDetailVO;
import com.slodon.b2b2c.vo.goods.GoodsPlatformVO;
import com.slodon.b2b2c.vo.goods.StoreGoodsVO;
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.amqp.rabbit.core.RabbitTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

@Api(tags = "admin-商品库管理")
@RestController
@Slf4j
@RequestMapping("v3/goods/admin/goods/platform")
public class AdminGoodsPlatformController extends BaseController {

    @Resource
    private GoodsPlatformModel goodsPlatformModel;
    @Resource
    private ProductPlatformModel productPlatformModel;
    @Resource
    private GoodsPlatformPictureModel goodsPlatformPictureModel;
    @Resource
    private GoodsPlatformBindReserveNameModel goodsPlatformBindReserveNameModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private GoodsCategoryModel goodsCategoryModel;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @ApiOperation("商品库列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "brandName", value = "品牌名称", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：1-待刊登；2-已刊登；3-已下架", 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 state, Integer isVirtualGoods, Integer categoryId) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsPlatformExample example = new GoodsPlatformExample();
        example.setGoodsNameLike(goodsName);
        example.setBrandNameLike(brandName);
        example.setIsVirtualGoods(isVirtualGoods);
        if (!StringUtil.isNullOrZero(state)) {
            example.setState(state);
        } else {
            //默认显示已刊登商品
            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);
            }
        }
        example.setStateNotEquals(GoodsPlatformConst.GOODS_STATE_4);
        List<GoodsPlatform> list = goodsPlatformModel.getGoodsPlatformList(example, pager);
        List<GoodsPlatformVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(goodsPlatform -> {
                GoodsPlatformVO vo = new GoodsPlatformVO(goodsPlatform);
                //查询货品列表
                ProductPlatformExample productExample = new ProductPlatformExample();
                productExample.setPlatformGoodsId(goodsPlatform.getPlatformGoodsId());
                productExample.setStateIn(GoodsConst.PRODUCT_STATE_1 + "," + GoodsConst.PRODUCT_STATE_2);
                List<ProductPlatform> productList = productPlatformModel.getProductPlatformList(productExample, null);
                AssertUtil.notEmpty(productList, "商品不存在");
                List<GoodsPlatformVO.ProductPlatformVO> productVOS = new ArrayList<>();
                productList.forEach(productPlatform -> {
                    productVOS.add(new GoodsPlatformVO.ProductPlatformVO(productPlatform));
                });
                vo.setProductList(productVOS);
                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

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

        //正常和禁用的货品
        ProductPlatformExample productExample = new ProductPlatformExample();
        productExample.setPlatformGoodsId(platformGoodsId);
        productExample.setStateIn(GoodsConst.PRODUCT_STATE_1 + "," + GoodsConst.PRODUCT_STATE_2);
        productExample.setOrderBy("platform_product_id asc");
        List<ProductPlatform> productList = productPlatformModel.getProductPlatformList(productExample, null);

        //查询商品图片
        GoodsPlatformPictureExample goodsPictureExample = new GoodsPlatformPictureExample();
        goodsPictureExample.setPlatformGoodsId(platformGoodsId);
        goodsPictureExample.setOrderBy("picture_id asc");
        List<GoodsPlatformPicture> goodsPictureList = goodsPlatformPictureModel.getGoodsPlatformPictureList(goodsPictureExample, null);

        GoodsPlatformDetailVO detailVO = new GoodsPlatformDetailVO(goodsPlatform, goodsPictureList, productList);
        //查询虚拟商品用户预留信息
        GoodsPlatformBindReserveNameExample example = new GoodsPlatformBindReserveNameExample();
        example.setPlatformGoodsId(platformGoodsId);
        example.setOrderBy("reserve_name_id asc");
        List<GoodsPlatformBindReserveName> reserveNameList = goodsPlatformBindReserveNameModel.getGoodsPlatformBindReserveNameList(example, null);
        detailVO.setReserveList(reserveNameList);
        return SldResponse.success(detailVO);
    }

    @ApiOperation("店铺商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "brandName", value = "品牌名称", paramType = "query"),
            @ApiImplicitParam(name = "storeName", value = "店铺名称", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("storeGoodsList")
    public JsonResult<PageVO<StoreGoodsVO>> storeGoodsList(HttpServletRequest request, String goodsName, String brandName, String storeName, Integer categoryId) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        GoodsExample example = new GoodsExample();
        example.setGoodsNameLike(goodsName);
        example.setBrandNameLike(brandName);
        example.setStoreNameLike(storeName);
        example.setState(GoodsConst.GOODS_STATE_UPPER);
        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);
            }
        }
        example.setQueryPlatformGoods("notNull");
        List<Goods> list = goodsModel.getGoodsList(example, pager);
        List<StoreGoodsVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(goods -> {
                vos.add(new StoreGoodsVO(goods));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("店铺商品导入")
    @OperationLogger(option = "店铺商品导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsIds", value = "商品id集合，用英文逗号隔开", required = true)
    })
    @PostMapping("storeGoodsImport")
    public JsonResult<Integer> storeGoodsImport(HttpServletRequest request, String goodsIds) {
        // 验证参数是否为空
        AssertUtil.notFormatIds(goodsIds, "商品id格式错误,请重试");

        Admin admin = UserUtil.getUser(request, Admin.class);

        goodsPlatformModel.storeGoodsImport(goodsIds, admin);
        return SldResponse.success("导入成功");
    }

    @ApiOperation("发布商品")
    @OperationLogger(option = "发布商品")
    @PostMapping("add")
    public JsonResult<Integer> addGoods(HttpServletRequest request, @RequestBody GoodsPlatformDTO goodsPlatformDTO) {
        Admin admin = UserUtil.getUser(request, Admin.class);

        //参数校验
        this.publishCheck(goodsPlatformDTO);
        //构造入库dto
        GoodsPlatformInsertDTO insertDTO = new GoodsPlatformInsertDTO(goodsPlatformDTO);

        goodsPlatformModel.saveGoods(insertDTO, admin.getAdminId());
        return SldResponse.success("发布商品成功");
    }

    @ApiOperation("编辑商品")
    @OperationLogger(option = "编辑商品")
    @PostMapping("edit")
    public JsonResult editGoods(HttpServletRequest request, @RequestBody GoodsPlatformDTO goodsPlatformDTO) {
        AssertUtil.notNullOrZero(goodsPlatformDTO.getPlatformGoodsId(), "请选择要编辑的商品");

        Admin admin = UserUtil.getUser(request, Admin.class);

        //查询数据库中的商品
        GoodsPlatform goodsPlatformDb = goodsPlatformModel.getGoodsPlatformByPlatformGoodsId(goodsPlatformDTO.getPlatformGoodsId());
        AssertUtil.notNull(goodsPlatformDb, "商品不存在");
        AssertUtil.isTrue(!goodsPlatformDTO.getIsVirtualGoods().equals(goodsPlatformDb.getIsVirtualGoods()), "商品类型不能修改");

        //参数校验
        this.publishCheck(goodsPlatformDTO);
        //构造入库dto
        GoodsPlatformInsertDTO insertDTO = new GoodsPlatformInsertDTO(goodsPlatformDTO);
        goodsPlatformModel.editGoods(insertDTO, goodsPlatformDb, admin.getAdminId());
        return SldResponse.success("编辑商品成功");
    }

    @ApiOperation("商品刊登")
    @OperationLogger(option = "商品刊登")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platformGoodsIds", value = "平台库商品id集合,用英文逗号隔开", required = true)
    })
    @PostMapping("publish")
    public JsonResult publish(HttpServletRequest request, String platformGoodsIds) {
        //验证参数是否为空
        AssertUtil.notFormatIds(platformGoodsIds, "商品id格式错误,请重试");

        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsPlatform goodsPlatform = new GoodsPlatform();
        goodsPlatform.setState(GoodsPlatformConst.GOODS_STATE_2);
        goodsPlatform.setUpdateTime(new Date());
        GoodsPlatformExample example = new GoodsPlatformExample();
        example.setPlatformGoodsIdIn(platformGoodsIds);
        goodsPlatformModel.updateGoodsPlatformByExample(goodsPlatform, example);
        return SldResponse.success("商品刊登成功");
    }

    @ApiOperation("商品下架")
    @OperationLogger(option = "商品下架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platformGoodsIds", value = "平台库商品id集合,用英文逗号隔开", required = true),
            @ApiImplicitParam(name = "offlineReason", value = "下架原因", required = true)
    })
    @PostMapping("lockup")
    public JsonResult lockup(HttpServletRequest request, String platformGoodsIds, String offlineReason) {
        //验证参数是否为空
        AssertUtil.notFormatIds(platformGoodsIds, "商品id格式错误,请重试");
        AssertUtil.notEmpty(offlineReason, "下架原因不能为空，请重试！");

        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsPlatform goodsPlatform = new GoodsPlatform();
        goodsPlatform.setState(GoodsPlatformConst.GOODS_STATE_3);
        goodsPlatform.setOfflineReason(offlineReason);
        goodsPlatform.setUpdateTime(new Date());
        GoodsPlatformExample example = new GoodsPlatformExample();
        example.setPlatformGoodsIdIn(platformGoodsIds);
        goodsPlatformModel.updateGoodsPlatformByExample(goodsPlatform, example);
        return SldResponse.success("商品下架成功");
    }

    @ApiOperation("商品删除")
    @OperationLogger(option = "商品删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platformGoodsIds", value = "平台库商品id集合,用英文逗号隔开", required = true)
    })
    @PostMapping("deleteGoods")
    public JsonResult deleteGoods(HttpServletRequest request, String platformGoodsIds) {
        //验证参数是否为空
        AssertUtil.notFormatIds(platformGoodsIds, "商品id格式错误,请重试");

        Admin admin = UserUtil.getUser(request, Admin.class);

        GoodsPlatform goodsPlatform = new GoodsPlatform();
        goodsPlatform.setState(GoodsPlatformConst.GOODS_STATE_4);
        goodsPlatform.setUpdateTime(new Date());
        GoodsPlatformExample example = new GoodsPlatformExample();
        example.setPlatformGoodsIdIn(platformGoodsIds);
        goodsPlatformModel.updateGoodsPlatformByExample(goodsPlatform, example);
        return SldResponse.success("商品删除成功");
    }

    /**
     * 发布编辑商品参数校验
     *
     * @param paramDTO
     */
    private void publishCheck(GoodsPlatformDTO paramDTO) {
        AssertUtil.notEmpty(paramDTO.getGoodsName(), "请填写商品名称");
        AssertUtil.notNullOrZero(paramDTO.getCategoryId3(), "请选择商品分类");

        //多规格校验
        if (!CollectionUtils.isEmpty(paramDTO.getSpecInfoList())) {
            paramDTO.getSpecInfoList().forEach(specInfo -> {
                AssertUtil.notEmpty(specInfo.getSpecValueList(), "规格：" + specInfo.getSpecName() + "未添加规格值");
                if (specInfo.getIsMainSpec() == GoodsConst.IS_MAIN_SPEC_YES) {
                    //主规格，规格值图片必传
                    specInfo.getSpecValueList().forEach(specValueInfo -> {
                        AssertUtil.notEmpty(specValueInfo.getImageList(), "请上传主规格图片");
                    });
                }
            });
        }
    }
}
