package com.cyksj.service.shop.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.shop.YhShopGoodsSkuMapper;
import com.cyksj.mapper.shop.YhShopMapper;
import com.cyksj.mapper.shop.YhShopSkuSysTakeDownRecordMapper;
import com.cyksj.model.dto.YhShopSkuDownInfo;
import com.cyksj.model.entity.YhShop;
import com.cyksj.model.entity.YhShopGoodsSku;
import com.cyksj.model.entity.YhShopSkuSysTakeDownRecord;
import com.cyksj.service.shop.YhShopGoodsSkuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zwhui
 * @date 2023/9/14 17:44
 */
@Service
@RequiredArgsConstructor
public class YhShopGoodsSkuServiceImpl extends ServiceImpl<YhShopGoodsSkuMapper, YhShopGoodsSku> implements YhShopGoodsSkuService {

    private final GoodsDonSkuMapper goodsDonSkuMapper;

    private final YhShopMapper yhShopMapper;

    private final YhShopSkuSysTakeDownRecordMapper yhShopSkuSysTakeDownRecordMapper;
    @Override
    public void saveGoods(List<Long> goodsIds, Long userId) {
        YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
                .eq(YhShop::getUserId, userId).last("limit 1"));
        if (yhShop == null) {
            throw BusinessRuntimeException.getInstance("您的店铺不存在");
        }
        List<YhShopGoodsSku> skuShops = goodsDonSkuMapper.selectSkuShops(goodsIds);
        skuShops.forEach(skuShop->{
            skuShop.setYhsId(yhShop.getId());
            skuShop.setUserId(userId);
        });
        this.saveOrUpdateBatch(skuShops);
    }

    @Override
    public List<YhShopSkuDownInfo> yhShopSkuSysStatusDownInfo(long userId) {
        List<YhShopSkuDownInfo> infos = yhShopMapper.getYhShopSkuSysStatusDownInfo(userId);
        return infos;
    }

    @Override
    public void deleteSkuDownInfo(long userId) {
        Integer selectCount = yhShopSkuSysTakeDownRecordMapper.selectCount(Wrappers.lambdaQuery(YhShopSkuSysTakeDownRecord.class)
                .eq(YhShopSkuSysTakeDownRecord::getUserId, userId)
                .eq(YhShopSkuSysTakeDownRecord::getDeleted, 1));
        if (selectCount > 0) {
            yhShopSkuSysTakeDownRecordMapper.update(null, Wrappers.lambdaUpdate(YhShopSkuSysTakeDownRecord.class)
                    .set(YhShopSkuSysTakeDownRecord::getDeleted, 0)
                    .eq(YhShopSkuSysTakeDownRecord::getUserId, userId)
                    .eq(YhShopSkuSysTakeDownRecord::getDeleted, 1));
        }
    }
}
