package com.sckw.order.serivce;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.order.dao.KwoTradeOrderGoodsUnitMapper;
import com.sckw.order.model.KwoTradeOrderGoodsUnit;
import com.sckw.order.model.vo.res.GoodsUnitDetailRes;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @desc 交易订单商品信息-单位换算
 * @author zk
 * @date 2023/12/4 0004
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KwoTradeOrderGoodsUnitService {

    private final KwoTradeOrderGoodsUnitMapper goodsUnitMapper;

    /**
     * @param units 单位换算信息
     * @desc 批量新增
     * @author zk
     * @date 2023/12/4
     **/
    public int insertBatch(List<KwoTradeOrderGoodsUnit> units) {
        AtomicInteger count = new AtomicInteger();
        if (CollectionUtils.isNotEmpty(units)) {
            units.forEach(e -> {
                count.addAndGet(goodsUnitMapper.insert(e));
            });
        }

        return count.get();
    }

    /**
     * @param orderId 订单信息ID
     * @desc 批量更新
     * @author zk
     * @date 2023/12/4
     **/
    public void delByOrderId(Long orderId) {
        LambdaUpdateWrapper<KwoTradeOrderGoodsUnit> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(KwoTradeOrderGoodsUnit::getTOrderId, orderId).eq(KwoTradeOrderGoodsUnit::getDelFlag, Global.NO)
                .set(KwoTradeOrderGoodsUnit::getDelFlag, Global.YES);
        goodsUnitMapper.update(null, wrapper);
    }

    /**
     * @param orderId 订单信息ID
     * @desc 查询商品单位换算信息
     * @author zk
     * @date 2023/12/4
     **/
    public List<GoodsUnitDetailRes> findGoodsUnitDetail(Long orderId) {
        List<GoodsUnitDetailRes> units = new ArrayList<>();
        List<KwoTradeOrderGoodsUnit> assistUnit = goodsUnitMapper.findGoodsUnit(new HashMap<>(Global.NUMERICAL_SIXTEEN){{put("tOrderId", orderId);}});
        if (CollectionUtils.isNotEmpty(assistUnit)) {
            assistUnit.forEach(e -> {
                GoodsUnitDetailRes unit = BeanUtils.copyProperties(e, GoodsUnitDetailRes.class);
                units.add(unit);
            });
        }
        return units;
    }

    /**
     * @param tOrderId 贸易订单
     * @param unit 单位
     * @desc 查询交易订单商品信息-单位换算
     * @author zk
     * @date 2023/12/8
     **/
    public KwoTradeOrderGoodsUnit findByIdAndUnit(Long tOrderId, String unit) {
        return goodsUnitMapper.findByIdAndUnit(tOrderId, unit);
    }

    /**
     * @param params 辅助单位信息
     * @desc 更新
     * @author zk
     * @date 2023/12/8
     **/
    public int updateById(KwoTradeOrderGoodsUnit params){
        return goodsUnitMapper.updateById(params);
    }

}
