package com.liquidnet.service.goblin.controller.manage;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.PagedResult;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsActionParam;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsAddParam;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsEditSkuParam;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsFilterParam;
import com.liquidnet.service.goblin.dto.manage.vo.GoblinStoreMgtGoodsInfoVo;
import com.liquidnet.service.goblin.dto.manage.vo.GoblinStoreMgtGoodsListVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsInfoVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSkuInfoVo;
import com.liquidnet.service.goblin.service.manage.IGoblinstoreMgtGoodsService;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@ApiSupport(order = 149003)
@Api(tags = "商品管理")
@Slf4j
@Validated
@RestController
@RequestMapping("store/mgt/goods")
public class GoblinStoreMgtGoodsController {
    @Autowired
    IGoblinstoreMgtGoodsService goblinstoreMgtGoodsService;
    @Autowired
    GoblinRedisUtils goblinRedisUtils;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "SPU列表")
    @PostMapping("list")
    public ResponseDto<PagedResult<GoblinStoreMgtGoodsListVo>> list(@Valid @RequestBody GoblinStoreMgtGoodsFilterParam storeMgtGoodsFilterParam) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:SPU列表:[GoblinStoreMgtGoodsFilterParam={}]", JsonUtils.toJson(storeMgtGoodsFilterParam));
        }
        return ResponseDto.success(goblinstoreMgtGoodsService.goodsList(storeMgtGoodsFilterParam));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "SPU导出")
    @PostMapping("export")
    public void export(@Valid @RequestBody GoblinStoreMgtGoodsFilterParam storeMgtGoodsFilterParam) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:SPU导出:[GoblinStoreMgtGoodsFilterParam={}]", JsonUtils.toJson(storeMgtGoodsFilterParam));
        }
        log.info("商品管理:SPU导出...");
        // TODO: 2021/12/28 zhanggb
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "SPU管理")
    @PostMapping("operate")
    public ResponseDto<Object> action(@Valid @RequestBody GoblinStoreMgtGoodsActionParam storeMgtGoodsActionParam) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:管理SPU:[GoblinStoreMgtGoodsActionParam={}]", JsonUtils.toJson(storeMgtGoodsActionParam));
        }
        // TODO: 2021/12/28 zhanggb 逻辑校验

        switch (storeMgtGoodsActionParam.getAction()) {
            case "ONSHELVES":
                goblinstoreMgtGoodsService.goodsOnshelves(storeMgtGoodsActionParam);
                break;
            case "UNSHELVE":
                goblinstoreMgtGoodsService.goodsUnshelves(storeMgtGoodsActionParam);
                break;
            case "REMOVE":
                goblinstoreMgtGoodsService.goodsRemove(storeMgtGoodsActionParam);
                break;
            default:
                log.warn("Invalid operation[action={}]", storeMgtGoodsActionParam.getAction());
                return ResponseDto.failure(ErrorMapping.get("149001"));
        }
        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "SPU添加")
    @PutMapping("add")
    public ResponseDto<Object> add(@Valid @RequestBody GoblinStoreMgtGoodsAddParam storeMgtGoodsAddParam) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:添加SPU:[GoblinStoreMgtGoodsAddParam={}]", JsonUtils.toJson(storeMgtGoodsAddParam));
        }
        goblinstoreMgtGoodsService.goodsAdd(storeMgtGoodsAddParam);
        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "SPU详情")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "spuId", value = "商品ID"),
    })
    @GetMapping("info")
    public ResponseDto<GoblinStoreMgtGoodsInfoVo> info(String spuId) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:SPU详情:[spuId={}]", spuId);
        }
        return ResponseDto.success(goblinstoreMgtGoodsService.goodsInfo(spuId));
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "商品编辑:SPU编辑", notes = "只修改商品信息，不包含规格相关信息")
    @PostMapping("edit_spu")
    public ResponseDto<Object> editSpu(@Valid @RequestBody GoblinStoreMgtGoodsAddParam storeMgtGoodsAddParam) {
        if (StringUtils.isBlank(storeMgtGoodsAddParam.getStoreId())) {
            return ResponseDto.failure(ErrorMapping.get("149002"));
        }
        if (StringUtils.isBlank(storeMgtGoodsAddParam.getSpuId()) || null == goblinRedisUtils.getGoodsInfoVo(storeMgtGoodsAddParam.getSpuId())) {
            return ResponseDto.failure(ErrorMapping.get("149010"));
        }
        if (log.isDebugEnabled()) {
            log.debug("商品管理:商品编辑:编辑SPU:[GoblinStoreMgtGoodsAddParam={}]", JsonUtils.toJson(storeMgtGoodsAddParam));
        }
        return ResponseDto.success(goblinstoreMgtGoodsService.goodsEditSpu(storeMgtGoodsAddParam));
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "商品编辑:SKU编辑", notes = "只修改单品信息，不包含商品信息")
    @PostMapping("edit_sku")
    public ResponseDto<Object> editSku(@Valid @RequestBody GoblinStoreMgtGoodsEditSkuParam storeMgtGoodsEditSkuParam) {
        if (StringUtils.isBlank(storeMgtGoodsEditSkuParam.getStoreId())) {
            return ResponseDto.failure(ErrorMapping.get("149002"));
        }
        GoblinGoodsSkuInfoVo goodsSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(storeMgtGoodsEditSkuParam.getSkuId());
        if (StringUtils.isBlank(storeMgtGoodsEditSkuParam.getSkuId()) || null == goodsSkuInfoVo) {
            return ResponseDto.failure(ErrorMapping.get("149011"));
        }
        GoblinGoodsInfoVo goodsInfoVo = goblinRedisUtils.getGoodsInfoVo(goodsSkuInfoVo.getSpuId());
        // TODO: 2022/1/5 zhanggb +分类-ISBN校验

        if (log.isDebugEnabled()) {
            log.debug("商品管理:商品编辑:编辑SKU:[GoblinStoreMgtGoodsEditSkuParam={}]", JsonUtils.toJson(storeMgtGoodsEditSkuParam));
        }
        storeMgtGoodsEditSkuParam.setStock(goodsSkuInfoVo.getStock());
        storeMgtGoodsEditSkuParam.setSkuStock(goodsSkuInfoVo.getSkuStock());
        String skuId = storeMgtGoodsEditSkuParam.getSkuId();
        Integer operStock = storeMgtGoodsEditSkuParam.getOperStock();
        if (null != operStock && operStock != 0) {// 处理库存
            int operStockVal = Math.abs(operStock);
            Integer stock = goodsSkuInfoVo.getSkuStock();// 总库存
            Integer skuStock = goodsSkuInfoVo.getSkuStock();// SKU总库存

            int rtSkuStock = goblinRedisUtils.getSkuStock(null, skuId);// 当前剩余库存
            if (operStock < 0 && rtSkuStock >= operStockVal) {// SKU实时库存充足时允许扣减
                if (goblinRedisUtils.decrSkuStock(null, skuId, operStockVal) < 0) {// 过程中库存不足时，回滚库存，编辑无效
                    goblinRedisUtils.incrSkuStock(null, skuId, operStockVal);
                    return ResponseDto.failure(ErrorMapping.get("149012"));
                } else {
                    storeMgtGoodsEditSkuParam.setSkuStock(skuStock - operStockVal);
                    storeMgtGoodsEditSkuParam.setStock(stock - operStockVal);
                }
            } else if (operStock > 0) {// 增加
                goblinRedisUtils.incrSkuStock(null, skuId, operStockVal);
                storeMgtGoodsEditSkuParam.setSkuStock(skuStock + operStockVal);
                storeMgtGoodsEditSkuParam.setStock(stock + operStockVal);
            }
        }
        if (goblinstoreMgtGoodsService.goodsEditSku(storeMgtGoodsEditSkuParam)) {
            return ResponseDto.success(goblinRedisUtils.getGoodsSkuInfoVo(storeMgtGoodsEditSkuParam.getSkuId()));
        } else {
            if (null != operStock && operStock != 0) {// 处理库存:回滚
                int operStockVal = Math.abs(operStock);
                if (operStock > 0) {// 增加的减回去
                    goblinRedisUtils.decrSkuStock(null, skuId, operStockVal);
                } else {// 扣减的加回去
                    goblinRedisUtils.incrSkuStock(null, skuId, operStockVal);
                }
            }
            return ResponseDto.failure(ErrorMapping.get("149013"));
        }
    }

    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "商品编辑:SKU添加")
    @PutMapping("edit_sku/add")
    public ResponseDto<Object> editSkuAdd(@Valid @RequestBody GoblinStoreMgtGoodsEditSkuParam storeMgtGoodsEditSkuParam) {
        if (log.isDebugEnabled()) {
            log.debug("商品管理:商品编辑:编辑SKU:[GoblinStoreMgtGoodsEditSkuParam={}]", JsonUtils.toJson(storeMgtGoodsEditSkuParam));
        }

        goblinstoreMgtGoodsService.goodsEditSkuAdd(storeMgtGoodsEditSkuParam);
        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "商品编辑:SKU删除")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "storeId", value = "店铺ID"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "skuId", value = "单品ID"),
    })
    @PostMapping("edit_sku/del")
    public ResponseDto<Object> editSkuDel(@NotBlank(message = "店铺ID不能为空") String storeId,
                                          @NotBlank(message = "单品ID不能为空") String skuId) {
        return ResponseDto.success(goblinstoreMgtGoodsService.goodsEditSkuDel(skuId));
    }

    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "商品编辑:SKU批改")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "storeId", value = "店铺ID"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "spuId", value = "商品ID"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "batField", value = "批量修改属性"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "batFieldVal", value = "批量修改属性值"),
    })
    @PostMapping("edit_sku/bat")
    public ResponseDto<Object> editSkuBat(@NotBlank(message = "店铺ID不能为空") String storeId,
                                          @NotBlank(message = "商品ID不能为空") String spuId,
                                          @NotBlank(message = "批量修改属性不能为空") String batField,
                                          @NotBlank(message = "批量修改属性值不能为空") String batFieldVal) {
        return ResponseDto.success(goblinstoreMgtGoodsService.goodsEditSkuBat(spuId, batField, batFieldVal));
    }
}
