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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.product.entity.Product;
import com.czg.product.entity.ProductStockFlow;
import com.czg.product.service.ProductStockFlowService;
import com.czg.sa.StpKit;
import com.czg.service.product.mapper.ConsInfoMapper;
import com.czg.service.product.mapper.ProductMapper;
import com.czg.service.product.mapper.ProductStockFlowMapper;
import com.czg.service.product.util.WxAccountUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 商品库存流水服务实现类
 *
 * @author tankaikai
 * @since 2025-03-14 15:45
 */
@Service
@Slf4j
public class ProductStockFlowServiceImpl extends ServiceImpl<ProductStockFlowMapper, ProductStockFlow> implements ProductStockFlowService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ConsInfoMapper consInfoMapper;
    @Resource
    private WxAccountUtil wxAccountUtil;

    @Override
    public void saveFlow(ProductStockFlow entity) {
        mapper.insert(entity);
        Long shopId = entity.getShopId();
        BigDecimal afterNumber = entity.getAfterNumber();
        Product product = productMapper.selectOneById(entity.getProductId());
        String shopName = "";
        try {
            shopName = StpKit.USER.getShopName();
        } catch (Exception e) {
            log.error("获取店铺名称失败");
        }
        if (StrUtil.isEmpty(shopName)) {
            shopName = productMapper.getShopName(shopId);
        }
        BigDecimal warnLine = Convert.toBigDecimal(product.getWarnLine());
        // 库存小于警告值，发送消息提醒
        if (NumberUtil.isLess(afterNumber, warnLine)) {
            List<String> openIdList = consInfoMapper.findOpenIdList(shopId, "pro");
            if (CollUtil.isEmpty(openIdList)) {
                return;
            }
            String productName = StrUtil.sub(product.getName(), 0, 10).concat("...");
            String conName = StrUtil.format("{}数量<预警值{}", productName, warnLine);
            String finalShopName = shopName;
            ThreadUtil.execAsync(() -> {
                openIdList.parallelStream().forEach(openId -> {
                    wxAccountUtil.sendStockMsg(finalShopName, conName, afterNumber, openId);
                });
            });
        }
    }
}
