package com.sckw.payment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sckw.core.model.constant.Global;
import com.sckw.payment.dao.KwpLedgerTradeUnitMapper;
import com.sckw.payment.model.KwpLedgerTradeUnit;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author xucaiqin
 * @date 2023-07-13 17:32:40
 */
@Service
@AllArgsConstructor
public class KwpLedgerTradeUnitService {
    private final KwpLedgerTradeUnitMapper tradeUnitMapper;

    /**
     * 保存企业单位信息
     *
     * @param list
     */
    public void saveList(List<KwpLedgerTradeUnit> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (KwpLedgerTradeUnit kwpLedgerTradeUnit : list) {
                tradeUnitMapper.insert(kwpLedgerTradeUnit);
            }
        }
    }

    /**
     * 删除企业关联信息
     *
     * @param tLedgerId
     */
    public void remove(Long tLedgerId) {
        KwpLedgerTradeUnit kwpLedgerTradeUnit = new KwpLedgerTradeUnit();
        kwpLedgerTradeUnit.setDelFlag(Global.DELETED);
        kwpLedgerTradeUnit.setUpdateTime(LocalDateTime.now());
        LambdaUpdateWrapper<KwpLedgerTradeUnit> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(KwpLedgerTradeUnit::getTLedgerId, tLedgerId);
        wrapper.eq(KwpLedgerTradeUnit::getDelFlag, Global.UN_DELETED);
        tradeUnitMapper.update(kwpLedgerTradeUnit, wrapper);
    }

    /**
     * 根据对账单id查询对方企业信息
     *
     * @param id       对账单id
     * @param unitType 对方企业类型
     * @return 不为空
     */
    public KwpLedgerTradeUnit queryCustomerEnt(Long id, Integer unitType) {
        LambdaQueryWrapper<KwpLedgerTradeUnit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwpLedgerTradeUnit::getTLedgerId, id).eq(KwpLedgerTradeUnit::getDelFlag, Global.UN_DELETED).eq(KwpLedgerTradeUnit::getUnitType, unitType).last("limit 1");
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitMapper.selectOne(wrapper);
        if (Objects.isNull(kwpLedgerTradeUnit)) {
            return new KwpLedgerTradeUnit();
        }
        return kwpLedgerTradeUnit;
    }
}
