package com.hotwj.platform.resourceManagement.vehicleInsurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.resourceManagement.vehicleInsurance.domain.HotVehicleInsurance;
import com.hotwj.platform.resourceManagement.vehicleInsurance.domain.bo.HotVehicleInsuranceBo;
import com.hotwj.platform.resourceManagement.vehicleInsurance.domain.vo.HotVehicleInsuranceVo;
import com.hotwj.platform.resourceManagement.vehicleInsurance.mapper.HotVehicleInsuranceMapper;
import com.hotwj.platform.resourceManagement.vehicleInsurance.service.IHotVehicleInsuranceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 车辆保险信息Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleInsuranceServiceImpl implements IHotVehicleInsuranceService {

    private final HotVehicleInsuranceMapper baseMapper;

    /**
     * 查询车辆保险信息
     *
     * @param id 主键
     * @return 车辆保险信息
     */
    @Override
    public HotVehicleInsuranceVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆保险信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆保险信息分页列表
     */
    @Override
    public TableDataInfo<HotVehicleInsuranceVo> queryPageList(HotVehicleInsuranceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleInsurance> lqw = buildQueryWrapper(bo);
        Page<HotVehicleInsuranceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆保险信息列表
     *
     * @param bo 查询条件
     * @return 车辆保险信息列表
     */
    @Override
    public List<HotVehicleInsuranceVo> queryList(HotVehicleInsuranceBo bo) {
        LambdaQueryWrapper<HotVehicleInsurance> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleInsurance> buildQueryWrapper(HotVehicleInsuranceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleInsurance> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotVehicleInsurance::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleInsurance::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleInsurance::getVehicleId, bo.getVehicleId());
        lqw.eq(StringUtils.isNotBlank(bo.getInsuranceType()), HotVehicleInsurance::getInsuranceType, bo.getInsuranceType());
        lqw.eq(StringUtils.isNotBlank(bo.getInsurerName()), HotVehicleInsurance::getInsurerName, bo.getInsurerName());
        lqw.eq(bo.getPremiumAmount() != null, HotVehicleInsurance::getPremiumAmount, bo.getPremiumAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelPerson()), HotVehicleInsurance::getChannelPerson, bo.getChannelPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelPhone()), HotVehicleInsurance::getChannelPhone, bo.getChannelPhone());
        lqw.eq(bo.getStartDate() != null, HotVehicleInsurance::getStartDate, bo.getStartDate());
        lqw.eq(bo.getEndDate() != null, HotVehicleInsurance::getEndDate, bo.getEndDate());
        lqw.eq(bo.getIsArchived() != null, HotVehicleInsurance::getIsArchived, bo.getIsArchived());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrls()), HotVehicleInsurance::getImageUrls, bo.getImageUrls());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleInsurance::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增车辆保险信息
     *
     * @param bo 车辆保险信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleInsuranceBo bo) {
        HotVehicleInsurance add = MapstructUtils.convert(bo, HotVehicleInsurance.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改车辆保险信息
     *
     * @param bo 车辆保险信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotVehicleInsuranceBo bo) {
        // 检查是否已归档
        HotVehicleInsurance old = baseMapper.selectById(bo.getId());
        if (old != null && Integer.valueOf(1).equals(old.getIsArchived())) {
            throw new ServiceException("该保险记录已归档，无法修改");
        }
        
        HotVehicleInsurance update = MapstructUtils.convert(bo, HotVehicleInsurance.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleInsurance entity) {
        // 校验日期：起保日期不能晚于终保日期
        if (entity.getStartDate() != null && entity.getEndDate() != null) {
            if (entity.getStartDate().after(entity.getEndDate())) {
                throw new IllegalArgumentException("起保日期不能晚于终保日期");
            }
        }
    }

    /**
     * 校验并批量删除车辆保险信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 检查是否已归档
            if (ids != null && !ids.isEmpty()) {
                List<HotVehicleInsurance> list = baseMapper.selectBatchIds(ids);
                for (HotVehicleInsurance insurance : list) {
                    if (Integer.valueOf(1).equals(insurance.getIsArchived())) {
                        throw new ServiceException("存在已归档的保险记录，无法删除");
                    }
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
