
package com.tmerclub.cloud.multishop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.product.feign.SpuFeignClient;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.product.constant.SalesType;
import com.tmerclub.cloud.common.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.multishop.mapper.ShopSubstituteSalesMapper;
import com.tmerclub.cloud.multishop.model.ShopSubstituteSales;
import com.tmerclub.cloud.multishop.service.ShopSubstituteSalesService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 代销设置表
 *
 * @author lhd
 * @date 2022-06-22 17:09:12
 */
@Service
public class ShopSubstituteSalesServiceImpl implements ShopSubstituteSalesService {

    @Autowired
    private ShopSubstituteSalesMapper shopSubstituteSalesMapper;

    @DubboReference
    private SpuFeignClient spuFeignClient;

    @Override
    public PageVO<ShopSubstituteSalesVO> page(PageDTO pageDTO) {
        return PageUtil.doPage(pageDTO, () -> shopSubstituteSalesMapper.list());
    }

    @Override
    @Cacheable(cacheNames = CacheNames.SHOP_SUBSTITUTE_SALES_KEY, key = "#shopId")
    public ShopSubstituteSalesVO getByShopSubstituteSalesId(Long shopId) {
        return shopSubstituteSalesMapper.getByShopSubstituteSalesId(shopId);
    }

    @Override
    public void save(ShopSubstituteSales shopSubstituteSales) {
        shopSubstituteSalesMapper.save(shopSubstituteSales);
    }

    @Override
    public void update(ShopSubstituteSales shopSubstituteSales) {
        int count = shopSubstituteSalesMapper.update(shopSubstituteSales);
        RedisUtil.del(CacheNames.SHOP_SUBSTITUTE_SALES_KEY + CacheNames.UNION + shopSubstituteSales.getShopId());
        if (count > 0) {
            //手动设价改成智能设价， 已导入的商品的价格要做更新；智能设价改成手动设价  已导入的商品价格不用更新；
            if (Objects.equals(shopSubstituteSales.getSalesType(), SalesType.SMART_PRICE.value())) {
                spuFeignClient.updateManualPriceCommissionSpuPrice(shopSubstituteSales.getShopId());
            }
        }
    }

    @Override
    public void deleteById(Long shopSubstituteSalesId) {
        shopSubstituteSalesMapper.deleteById(shopSubstituteSalesId);
    }

    @Override
    public List<ShopSubstituteSalesVO> listByShopIds(List<Long> shopIds) {
        if (CollUtil.isEmpty(shopIds)) {
            return new ArrayList<>(0);
        }
        return shopSubstituteSalesMapper.listByShopIds(shopIds);
    }

}
