package com.hotwj.platform.config.vehicleThreeInspectConfig.service.impl;

import cn.hutool.core.collection.CollUtil;
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.config.vehicleThreeInspectConfig.domain.HotVehicleThreeInspectConfig;
import com.hotwj.platform.config.vehicleThreeInspectConfig.domain.bo.HotVehicleThreeInspectConfigBo;
import com.hotwj.platform.config.vehicleThreeInspectConfig.domain.vo.HotVehicleThreeInspectConfigVo;
import com.hotwj.platform.config.vehicleThreeInspectConfig.mapper.HotVehicleThreeInspectConfigMapper;
import com.hotwj.platform.config.vehicleThreeInspectConfig.service.IHotVehicleThreeInspectConfigService;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
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.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 车辆三检配置Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleThreeInspectConfigServiceImpl implements IHotVehicleThreeInspectConfigService {

    private final HotVehicleThreeInspectConfigMapper baseMapper;
    private final ISysCompanyService sysCompanyService;

    /**
     * 查询车辆三检配置
     *
     * @param id 主键
     * @return 车辆三检配置
     */
    @Override
    public HotVehicleThreeInspectConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean useDefault() {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }

        SysCompanyVo company = sysCompanyService.queryById(companyId);
        if (company == null) {
            throw new ServiceException("公司不存在");
        }

        // 校验当前公司是否已有配置
        Long count = baseMapper.selectCount(
                Wrappers.lambdaQuery(HotVehicleThreeInspectConfig.class)
                        .eq(HotVehicleThreeInspectConfig::getCompanyId, companyId)
        );
        if (count != null && count > 0) {
            throw new ServiceException("当前公司已存在车辆三检配置，请先清除已存在数据");
        }

        // 获取总部配置 (companyId = 1)
        List<HotVehicleThreeInspectConfig> defaultConfigs = baseMapper.selectList(
                Wrappers.lambdaQuery(HotVehicleThreeInspectConfig.class)
                        .eq(HotVehicleThreeInspectConfig::getCompanyId, 1L)
        );

        if (CollUtil.isEmpty(defaultConfigs)) {
            throw new ServiceException("默认配置不存在，请联系管理员");
        }

        List<HotVehicleThreeInspectConfig> newConfigs = new ArrayList<>();
        for (HotVehicleThreeInspectConfig cfg : defaultConfigs) {
            HotVehicleThreeInspectConfig newCfg = new HotVehicleThreeInspectConfig();
            // 复制属性，排除ID等
            newCfg.setCompanyId(companyId);
            newCfg.setInspectType(cfg.getInspectType());
            newCfg.setTitle(cfg.getTitle());
            newCfg.setNormalText(cfg.getNormalText());
            newCfg.setAbnormalText(cfg.getAbnormalText());
            newCfg.setCode(cfg.getCode());
            newCfg.setIsEnabled(cfg.getIsEnabled());
            newCfg.setIsChecked(cfg.getIsChecked());
            newCfg.setIsDeleted(0L);
            newConfigs.add(newCfg);
        }

        return baseMapper.insertBatch(newConfigs);
    }


    /**
     * 分页查询车辆三检配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆三检配置分页列表
     */
    @Override
    public TableDataInfo<HotVehicleThreeInspectConfigVo> queryPageList(HotVehicleThreeInspectConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqw = buildQueryWrapper(bo);
        Page<HotVehicleThreeInspectConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆三检配置列表
     *
     * @param bo 查询条件
     * @return 车辆三检配置列表
     */
    @Override
    public List<HotVehicleThreeInspectConfigVo> queryList(HotVehicleThreeInspectConfigBo bo) {
        LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<HotVehicleThreeInspectConfigVo> queryByCompanyIdAndIds(Long companyId, java.util.List<Long> ids) {
        if (companyId == null || ids == null || ids.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqw = Wrappers.<HotVehicleThreeInspectConfig>lambdaQuery()
                .eq(HotVehicleThreeInspectConfig::getCompanyId, companyId)
                .in(HotVehicleThreeInspectConfig::getId, ids);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleThreeInspectConfig> buildQueryWrapper(HotVehicleThreeInspectConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotVehicleThreeInspectConfig::getId);
        lqw.eq(bo.getCompanyId() != null, HotVehicleThreeInspectConfig::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getInspectType() != null, HotVehicleThreeInspectConfig::getInspectType, bo.getInspectType());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), HotVehicleThreeInspectConfig::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getNormalText()), HotVehicleThreeInspectConfig::getNormalText, bo.getNormalText());
        lqw.eq(StringUtils.isNotBlank(bo.getAbnormalText()), HotVehicleThreeInspectConfig::getAbnormalText, bo.getAbnormalText());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), HotVehicleThreeInspectConfig::getCode, bo.getCode());
        lqw.eq(bo.getIsEnabled() != null, HotVehicleThreeInspectConfig::getIsEnabled, bo.getIsEnabled());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleThreeInspectConfig::getIsDeleted, bo.getIsDeleted());
        lqw.eq(bo.getIsChecked() != null, HotVehicleThreeInspectConfig::getIsChecked, bo.getIsChecked());
        return lqw;
    }

    /**
     * 新增车辆三检配置
     *
     * @param bo 车辆三检配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotVehicleThreeInspectConfigBo bo) {
        HotVehicleThreeInspectConfig add = MapstructUtils.convert(bo, HotVehicleThreeInspectConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改车辆三检配置
     *
     * @param bo 车辆三检配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotVehicleThreeInspectConfigBo bo) {
        HotVehicleThreeInspectConfig update = MapstructUtils.convert(bo, HotVehicleThreeInspectConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleThreeInspectConfig entity) {
        if (entity.getCompanyId() == null || StringUtils.isBlank(entity.getCode())) {
            return;
        }
        LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotVehicleThreeInspectConfig::getCompanyId, entity.getCompanyId());
        lqw.eq(HotVehicleThreeInspectConfig::getCode, entity.getCode());
        lqw.eq(HotVehicleThreeInspectConfig::getInspectType, entity.getInspectType());
        lqw.eq(HotVehicleThreeInspectConfig::getIsDeleted, 0L);
        if (entity.getId() != null) {
            lqw.ne(HotVehicleThreeInspectConfig::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(lqw);
        if (count != null && count > 0) {
            throw new ServiceException("同一公司下三检项目代码已存在，请修改后重试");
        }
        
        // 校验标题是否重复
        if (StringUtils.isNotBlank(entity.getTitle())) {
            // 去除首尾空格
            String title = entity.getTitle().trim();
            entity.setTitle(title);
            
            LambdaQueryWrapper<HotVehicleThreeInspectConfig> lqwTitle = Wrappers.lambdaQuery();
            lqwTitle.eq(HotVehicleThreeInspectConfig::getCompanyId, entity.getCompanyId());
            lqwTitle.eq(HotVehicleThreeInspectConfig::getTitle, title);
            lqwTitle.eq(HotVehicleThreeInspectConfig::getInspectType, entity.getInspectType());
            lqwTitle.eq(HotVehicleThreeInspectConfig::getIsDeleted, 0L);
            if (entity.getId() != null) {
                lqwTitle.ne(HotVehicleThreeInspectConfig::getId, entity.getId());
            }
            Long countTitle = baseMapper.selectCount(lqwTitle);
            if (countTitle != null && countTitle > 0) {
                throw new ServiceException("同一公司下三检项目名称已存在，请修改后重试");
            }
        }
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean clearAll() {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        // 逻辑删除当前公司所有配置
        return baseMapper.delete(
                Wrappers.lambdaQuery(HotVehicleThreeInspectConfig.class)
                        .eq(HotVehicleThreeInspectConfig::getCompanyId, companyId)
        ) > 0;
    }
}
