package com.czg.service.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.czg.exception.CzgException;
import com.czg.product.dto.storage.ShopStorageGoodDTO;
import com.czg.product.entity.Product;
import com.czg.product.entity.ShopProdUnit;
import com.czg.product.service.ProductService;
import com.czg.product.service.ShopProdUnitService;
import com.czg.service.product.mapper.ShopStorageGoodMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.product.entity.ShopStorageGood;
import com.czg.product.service.ShopStorageGoodService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import static com.mybatisflex.core.query.QueryMethods.column;

/**
 * 酒品表 服务层实现。
 *
 * @author zs
 * @since 2025-02-26
 */
@Service
public class ShopStorageGoodServiceImpl extends ServiceImpl<ShopStorageGoodMapper, ShopStorageGood> implements ShopStorageGoodService{
    @Resource
    private ProductService productService;
    @Resource
    private ShopProdUnitService shopProdUnitService;

    @Override
    public Boolean edit(Long shopId, ShopStorageGoodDTO shopStorageGoodDTO) {
        ShopStorageGood storageGood = getOne(new QueryWrapper().eq(ShopStorageGood::getShopId, shopId).eq(ShopStorageGood::getId, shopStorageGoodDTO.getId()));
        if (storageGood == null) {
            throw new CzgException("商品不存在");
        }

        BeanUtil.copyProperties(shopStorageGoodDTO, storageGood);
        storageGood.setSource(null);
        return updateById(storageGood);
    }

    @Override
    public Boolean saveInfo(Long shopId, ShopStorageGoodDTO shopStorageGoodDTO) {
        ShopStorageGood shopStorageGood = BeanUtil.copyProperties(shopStorageGoodDTO, ShopStorageGood.class);
        if (shopStorageGoodDTO.getSource() == 1) {
            if (shopStorageGoodDTO.getProdId() == null) {
                throw new CzgException("商品id不为空");
            }
            Product product = productService.getOne(new QueryWrapper().eq(Product::getShopId, shopId).eq(Product::getId, shopStorageGoodDTO.getProdId()));
            if (product == null) {
                throw new CzgException("商品不存在");
            }

            shopStorageGood.setName(product.getName());
            shopStorageGood.setImgUrl(product.getCoverImg());
            ShopProdUnit unit = shopProdUnitService.getOne(new QueryWrapper().eq(ShopProdUnit::getShopId, shopId).eq(ShopProdUnit::getId, product.getUnitId()));
            shopStorageGood.setUnit(unit == null ? "" : unit.getName());
        }
        shopStorageGood.setShopId(shopId);
        return save(shopStorageGood);
    }


}
