package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.maintain.business.domain.ErpExamineVehicleModel;
import com.maintain.business.domain.ErpProjectType;
import com.maintain.business.domain.ErpVehicleModel;
import com.maintain.business.domain.bo.ErpVehicleModelBo;
import com.maintain.business.domain.vo.ErpVehicleModelVo;
import com.maintain.business.mapper.ErpExamineVehicleModelMapper;
import com.maintain.business.mapper.ErpProjectTypeMapper;
import com.maintain.business.mapper.ErpVehicleModelMapper;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.maintain.business.domain.bo.ErpExamineProjectBo;
import com.maintain.business.domain.vo.ErpExamineProjectVo;
import com.maintain.business.domain.ErpExamineProject;
import com.maintain.business.mapper.ErpExamineProjectMapper;
import com.maintain.business.service.IErpExamineProjectService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 检验项目Service业务层处理
 *
 * @author liushuai
 * @date 2025-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpExamineProjectServiceImpl implements IErpExamineProjectService {

    private final ErpExamineProjectMapper baseMapper;
    private final ErpProjectTypeMapper projectTypeMapper;
    private final ErpExamineVehicleModelMapper examineVehicleModelMapper;
    private final ErpVehicleModelMapper vehicleModelMapper;

    /**
     * 查询检验项目
     */
    @Override
    public ErpExamineProjectVo queryById(Long id){
        ErpExamineProjectVo examineProjectVo = baseMapper.selectVoById(id);
        // 获取检验项目与关联车型数据
        LambdaQueryWrapper<ErpExamineVehicleModel> modelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        modelLambdaQueryWrapper.eq(ErpExamineVehicleModel::getExamineId, id);
        List<ErpExamineVehicleModel> vehicleModelList = examineVehicleModelMapper.selectList(modelLambdaQueryWrapper);
        // 根据车型ID列表获取车型数据
        if (!vehicleModelList.isEmpty()) {
            List<Long> vehicleModelIdList = vehicleModelList.stream().map(ErpExamineVehicleModel::getVehicleModelId).collect(Collectors.toList());
            LambdaQueryWrapper<ErpVehicleModel> lqw = new LambdaQueryWrapper<>();
            lqw.in(ErpVehicleModel::getId, vehicleModelIdList);
            List<ErpVehicleModelVo> vehicleModelVoList = vehicleModelMapper.selectVoList(lqw);
            examineProjectVo.setModelList(vehicleModelVoList);
        }
        return examineProjectVo;
    }

    /**
     * 查询检验项目列表
     */
    @Override
    public TableDataInfo<ErpExamineProjectVo> queryPageList(ErpExamineProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpExamineProject> lqw = buildQueryWrapper(bo);
        Page<ErpExamineProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询检验项目列表
     */
    @Override
    public List<ErpExamineProjectVo> queryList(ErpExamineProjectBo bo) {
        LambdaQueryWrapper<ErpExamineProject> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpExamineProject> buildQueryWrapper(ErpExamineProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpExamineProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTypeId() != null, ErpExamineProject::getTypeId, bo.getTypeId());
        lqw.like(StringUtils.isNotBlank(bo.getTypeName()), ErpExamineProject::getTypeName, bo.getTypeName());
        lqw.like(StringUtils.isNotBlank(bo.getExamineCode()), ErpExamineProject::getExamineCode, bo.getExamineCode());
        lqw.like(StringUtils.isNotBlank(bo.getExamineName()), ErpExamineProject::getExamineName, bo.getExamineName());
        lqw.eq(bo.getIsGeneral() != null, ErpExamineProject::getIsGeneral, bo.getIsGeneral());
        lqw.eq(bo.getState() != null, ErpExamineProject::getState, bo.getState());
        lqw.eq(bo.getIsDelete() != null, ErpExamineProject::getIsDelete, bo.getIsDelete());
        return lqw;
    }

    /**
     * 新增检验项目
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpExamineProjectBo bo) {
        ErpExamineProject add = BeanUtil.toBean(bo, ErpExamineProject.class);
        validEntityBeforeSave(add);
        ErpProjectType projectType = projectTypeMapper.selectById(add.getTypeId());
        add.setTypeName(projectType.getTypeName());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 保存适配车型
            List<ErpVehicleModelBo> modelList = bo.getModelList();
            List<ErpExamineVehicleModel> collect = modelList.stream().map(item -> {
                ErpExamineVehicleModel examineVehicleModel = new ErpExamineVehicleModel();
                examineVehicleModel.setExamineId(add.getId());
                examineVehicleModel.setExamineName(add.getExamineName());
                examineVehicleModel.setVehicleModelId(item.getId());
                examineVehicleModel.setVehicleModelCode(item.getCarTypeCode());
                return examineVehicleModel;
            }).collect(Collectors.toList());
            examineVehicleModelMapper.insertBatch(collect);
        }
        return flag;
    }

    /**
     * 修改检验项目
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ErpExamineProjectBo bo) {
        ErpExamineProject update = BeanUtil.toBean(bo, ErpExamineProject.class);
        validEntityBeforeSave(update);
        ErpProjectType projectType = projectTypeMapper.selectById(update.getTypeId());
        update.setTypeName(projectType.getTypeName());
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 删除原有适配车型
            LambdaQueryWrapper<ErpExamineVehicleModel> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ErpExamineVehicleModel::getExamineId, update.getId());
            examineVehicleModelMapper.delete(lqw);
            // 保存适配车型
            List<ErpVehicleModelBo> modelList = bo.getModelList();
            List<ErpExamineVehicleModel> collect = modelList.stream().map(item -> {
                ErpExamineVehicleModel examineVehicleModel = new ErpExamineVehicleModel();
                examineVehicleModel.setExamineId(update.getId());
                examineVehicleModel.setExamineName(update.getExamineName());
                examineVehicleModel.setVehicleModelId(item.getId());
                examineVehicleModel.setVehicleModelCode(item.getCarTypeCode());
                return examineVehicleModel;
            }).collect(Collectors.toList());
            examineVehicleModelMapper.insertBatch(collect);
        }
        return flag;
    }

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

    /**
     * 批量删除检验项目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
