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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.domain.HotVehicleAnnualReview;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.domain.bo.HotVehicleAnnualReviewBo;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.domain.vo.HotVehicleAnnualReviewVo;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.mapper.HotVehicleAnnualReviewMapper;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.service.IHotVehicleAnnualReviewService;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.HotVehicle;
import com.hotwj.platform.resourceManagement.vehicleManagement.mapper.HotVehicleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 车辆年审明细Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleAnnualReviewServiceImpl implements IHotVehicleAnnualReviewService {

    private final HotVehicleAnnualReviewMapper baseMapper;
    private final HotVehicleMapper vehicleMapper;

    /**
     * 查询车辆年审明细
     *
     * @param id 主键
     * @return 车辆年审明细
     */
    @Override
    public HotVehicleAnnualReviewVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆年审明细列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆年审明细分页列表
     */
    @Override
    public TableDataInfo<HotVehicleAnnualReviewVo> queryPageList(HotVehicleAnnualReviewBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleAnnualReview> lqw = buildQueryWrapper(bo);
        Page<HotVehicleAnnualReviewVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆年审明细列表
     *
     * @param bo 查询条件
     * @return 车辆年审明细列表
     */
    @Override
    public List<HotVehicleAnnualReviewVo> queryList(HotVehicleAnnualReviewBo bo) {
        LambdaQueryWrapper<HotVehicleAnnualReview> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据车辆ID查询最新的一条年审记录
     *
     * @param vehicleId 车辆ID
     * @return 最新年审记录
     */
    @Override
    public HotVehicleAnnualReviewVo queryLatestByVehicleId(String vehicleId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<HotVehicleAnnualReview>()
            .eq(HotVehicleAnnualReview::getVehicleId, vehicleId)
                .eq(HotVehicleAnnualReview::getIsDeleted, 0L)
            .orderByDesc(HotVehicleAnnualReview::getReviewDate)
            .last("LIMIT 1"));
    }

    @Override
    public HotVehicleAnnualReviewVo queryLatestByVehicleIdAndReviewDateRange(String vehicleId, Date startDate, Date endDate) {
        LambdaQueryWrapper<HotVehicleAnnualReview> lqw = new LambdaQueryWrapper<HotVehicleAnnualReview>()
                .eq(HotVehicleAnnualReview::getVehicleId, vehicleId)
                .eq(HotVehicleAnnualReview::getIsDeleted, 0L)
                .orderByDesc(HotVehicleAnnualReview::getReviewDate)
                .last("LIMIT 1");
        if (startDate != null) {
            lqw.ge(HotVehicleAnnualReview::getReviewDate, startDate);
        }
        if (endDate != null) {
            lqw.le(HotVehicleAnnualReview::getReviewDate, endDate);
        }
        return baseMapper.selectVoOne(lqw);
    }

    private LambdaQueryWrapper<HotVehicleAnnualReview> buildQueryWrapper(HotVehicleAnnualReviewBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleAnnualReview> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotVehicleAnnualReview::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleAnnualReview::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleAnnualReview::getVehicleId, bo.getVehicleId());
        lqw.eq(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleAnnualReview::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getReviewDate() != null, HotVehicleAnnualReview::getReviewDate, bo.getReviewDate());
        lqw.eq(bo.getEvaluationLevel() != null, HotVehicleAnnualReview::getEvaluationLevel, bo.getEvaluationLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrls()), HotVehicleAnnualReview::getImageUrls, bo.getImageUrls());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleAnnualReview::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增车辆年审明细
     *
     * @param bo 车辆年审明细
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(HotVehicleAnnualReviewBo bo) {
        HotVehicleAnnualReview add = MapstructUtils.convert(bo, HotVehicleAnnualReview.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (StringUtils.isNotBlank(bo.getInspectionValidMonth()) && StringUtils.isNotBlank(bo.getVehicleId())) {
                String validMonth = bo.getInspectionValidMonth();
                try {
                    validMonth = DateUtil.format(DateUtil.parse(validMonth), "yyyy-MM");
                } catch (Exception e) {
                    log.warn("Invalid date format: {}", validMonth);
                }
                vehicleMapper.update(null, new LambdaUpdateWrapper<HotVehicle>()
                        .set(HotVehicle::getInspectionValidMonth, validMonth)
                        .eq(HotVehicle::getId, bo.getVehicleId()));
            }
        }
        return flag;
    }

    /**
     * 修改车辆年审明细
     *
     * @param bo 车辆年审明细
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotVehicleAnnualReviewBo bo) {
        HotVehicleAnnualReview update = MapstructUtils.convert(bo, HotVehicleAnnualReview.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleAnnualReview entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除车辆年审明细信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
