package com.yd.csf.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.csf.feign.request.premiumreconciliation.ApiPremiumReconciliationPageRequest;
import com.yd.csf.feign.response.premiumreconciliation.ApiPremiumReconciliationPageResponse;
import com.yd.csf.service.dto.PremiumReconciliationDto;
import com.yd.csf.service.model.PremiumReconciliation;
import com.yd.csf.service.dao.PremiumReconciliationMapper;
import com.yd.csf.service.model.Variable;
import com.yd.csf.service.service.IPremiumReconciliationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 保费对账记录表 服务实现类
 * </p>
 *
 * @author zxm
 * @since 2025-12-26
 */
@Service
public class PremiumReconciliationServiceImpl extends ServiceImpl<PremiumReconciliationMapper, PremiumReconciliation> implements IPremiumReconciliationService {

    @Override
    public IPage<ApiPremiumReconciliationPageResponse> page(Page<ApiPremiumReconciliationPageResponse> page,
                                                            ApiPremiumReconciliationPageRequest request) {
        return baseMapper.page(page,request);
    }

    @Override
    public PremiumReconciliation queryOne(String premiumReconciliationBizId) {
        return this.getOne(new LambdaQueryWrapper<PremiumReconciliation>()
                .eq(PremiumReconciliation::getPremiumReconciliationBizId,premiumReconciliationBizId).last(" limit 1 "));
    }

    @Override
    public List<PremiumReconciliation> queryList(PremiumReconciliationDto dto) {
        List<PremiumReconciliation> list = baseMapper.selectList(new LambdaQueryWrapper<PremiumReconciliation>()
                .eq(StringUtils.isNotBlank(dto.getPremiumReconciliationBizId()) && !dto.getIsExcludeMy(),PremiumReconciliation::getPremiumReconciliationBizId,dto.getPremiumReconciliationBizId())
                .eq(StringUtils.isNotBlank(dto.getCurrentIssueNumber()),PremiumReconciliation::getCurrentIssueNumber,dto.getCurrentIssueNumber())
                .ne(dto.getIsExcludeMy(),PremiumReconciliation::getPremiumReconciliationBizId,dto.getPremiumReconciliationBizId())
        );
        return list;
    }

    /**
     * 根据保单号查询最新创建时间的对账记录
     * @param policyNo
     * @return
     */
    @Override
    public PremiumReconciliation queryLatestOneByPolicyNo(String policyNo) {
        return this.getOne(new LambdaQueryWrapper<PremiumReconciliation>()
                .eq(PremiumReconciliation::getPolicyNo,policyNo)
                .orderByDesc(PremiumReconciliation::getCreateTime)
                .last(" limit 1 ")
        );
    }

}
