
package com.tmerclub.cloud.product.controller.platform;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.api.feign.SearchSpuFeignClient;
import com.tmerclub.cloud.api.multishop.constant.ShopStatus;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.constant.SpuType;
import com.tmerclub.cloud.common.product.dto.ProductSearchDTO;
import com.tmerclub.cloud.common.product.vo.search.SpuAdminVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.product.dto.SpuTagDTO;
import com.tmerclub.cloud.product.model.SpuTag;
import com.tmerclub.cloud.product.service.SpuService;
import com.tmerclub.cloud.product.service.SpuTagReferenceService;
import com.tmerclub.cloud.product.service.SpuTagService;
import com.tmerclub.cloud.product.vo.SpuTagVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品分组表
 *
 * @author lhd
 * @date 2021-02-20 14:28:10
 */
@RestController("platformSpuTagController")
@RequestMapping("/p/spu_tag")
@Tag(name = "platform-商品分组表")
public class SpuTagController {

    @Autowired
    private SpuTagService spuTagService;

    @Autowired
    private SpuTagReferenceService spuTagReferenceService;


    @DubboReference
    private SearchSpuFeignClient searchSpuFeignClient;

    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;

    @Autowired
    private SpuService spuService;

    @GetMapping("/page")
    @Operation(summary = "获取商品分组表列表", description = "分页获取商品分组表列表")
    public ServerResponseEntity<PageVO<SpuTagVO>> page(@Valid PageDTO pageDTO, SpuTagDTO spuTagDTO) {
        spuTagDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        PageVO<SpuTagVO> spuTagPage = spuTagService.pageByTitle(pageDTO, spuTagDTO);
        return ServerResponseEntity.success(spuTagPage);
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "获取商品分组", description = "根据id获取商品分组")
    public ServerResponseEntity<SpuTagVO> getById(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(spuTagService.getById(id));
    }

    @PostMapping
    @Operation(summary = "保存商品分组表", description = "保存商品分组表")
    public ServerResponseEntity<Void> save(@Valid @RequestBody SpuTagDTO spuTagDTO) {
        spuTagDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        // 查看是否相同的标签
        List<SpuTagVO> list = spuTagService.listByTitle(spuTagDTO);
        if (CollectionUtil.isNotEmpty(list)) {
            // 分组名称已存在，不能添加相同的分组
            throw new LuckException("分组名称已存在，不能添加相同的分组");
        }
        SpuTag spuTag = BeanUtil.map(spuTagDTO, SpuTag.class);
        spuTag.setId(null);
        spuTag.setProdCount(0L);
        spuTagService.save(spuTag);
        spuTagService.removeCacheByShopId(AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新商品分组表", description = "更新商品分组表")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SpuTagDTO spuTagDTO) {
        SpuTag spuTag = BeanUtil.map(spuTagDTO, SpuTag.class);
        spuTagDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        // 查看是否相同的标签
        List<SpuTagVO> list = spuTagService.listByTitle(spuTagDTO);
        if (CollectionUtil.isNotEmpty(list)) {
            // 分组名称已存在，不能添加相同的分组
            throw new LuckException("分组名称已存在，不能添加相同的分组");
        }
        spuTagService.update(spuTag);
        spuTagService.removeCacheByShopId(AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除商品分组表", description = "根据商品分组表id删除商品分组表")
    public ServerResponseEntity<Void> delete(@RequestParam Long id) {
        SpuTagVO spuTagVO = spuTagService.getById(id);
        if (spuTagVO.getIsDefault() != 0) {
            // 默认标签不能删除
            throw new LuckException("默认标签不能删除");
        }
        // 校验分组是否已经使用过
        int count = spuTagReferenceService.countByStatusAndTagId(StatusEnum.ENABLE.value(), id);
        if (count > 0) {
            throw new LuckException("该分组还存在商品，无法进行删除操作");
        }
        spuTagService.deleteById(id);
        spuTagService.removeCacheByShopId(AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    /**
     * 获取没有参与当前分组的商品
     */
    @GetMapping("/get_not_tag_prod_page")
    @Operation(summary = "获取非本分组的商品列表", description = "根据tagId,获取非本分组的商品列表")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> getNotTagProdPage(@Valid PageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        List<Long> spuIds = spuTagReferenceService.spuIdsByTagId(productSearchDTO.getTagId());
        ServerResponseEntity<List<Long>> response = shopDetailFeignClient.getShopIdsByShopStatus(ShopStatus.STOP.value());
        if (!response.isSuccess()) {
            throw new LuckException(response.getMsg());
        }
        List<Long> shopIds = response.getData();
        if (CollUtil.isNotEmpty(shopIds)) {
            List<Long> enableSpuIds = spuService.listSpuIdsByShopIds(shopIds);
            if (CollUtil.isNotEmpty(enableSpuIds)) {
                spuIds.addAll(enableSpuIds);
            }
        }
        if (CollUtil.isNotEmpty(spuIds)) {
            productSearchDTO.setSpuIdsExclude(spuIds);
        }
        productSearchDTO.setSpuStatus(StatusEnum.ENABLE.value());
        productSearchDTO.setSpuType(SpuType.NORMAL.value());
        //过滤掉供应商商品
        productSearchDTO.setIsSupplierType(1);
        productSearchDTO.setTagId(null);
        ServerResponseEntity<EsPageVO<SpuAdminVO>> responseEntity = searchSpuFeignClient.adminPage(productSearchDTO);
        return ServerResponseEntity.success(responseEntity.getData());
    }
}
