package com.hotwj.platform.config.driverAnnualAssessmentConfig.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.driverAnnualAssessmentConfig.domain.HotDriverAnnualAssessmentConfig;
import com.hotwj.platform.config.driverAnnualAssessmentConfig.domain.bo.HotDriverAnnualAssessmentConfigBo;
import com.hotwj.platform.config.driverAnnualAssessmentConfig.domain.vo.HotDriverAnnualAssessmentConfigVo;
import com.hotwj.platform.config.driverAnnualAssessmentConfig.mapper.HotDriverAnnualAssessmentConfigMapper;
import com.hotwj.platform.config.driverAnnualAssessmentConfig.service.IHotDriverAnnualAssessmentConfigService;
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-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotDriverAnnualAssessmentConfigServiceImpl implements IHotDriverAnnualAssessmentConfigService {

    private static final long ENABLED_STATUS = 1L;
    private static final long DISABLED_STATUS = 0L;
    private static final long MAX_ENABLED_TOTAL_SCORE = 100L;

    private final HotDriverAnnualAssessmentConfigMapper baseMapper;
    private final ISysCompanyService sysCompanyService;

    /**
     * 查询驾驶员年度考核配置
     *
     * @param id 主键
     * @return 驾驶员年度考核配置
     */
    @Override
    public HotDriverAnnualAssessmentConfigVo 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(HotDriverAnnualAssessmentConfig.class)
                        .eq(HotDriverAnnualAssessmentConfig::getCompanyId, companyId)
        );
        if (count != null && count > 0) {
            throw new ServiceException("当前公司已存在考核配置，请先清除已存在数据");
        }

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

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

        List<HotDriverAnnualAssessmentConfig> newConfigs = new ArrayList<>();
        for (HotDriverAnnualAssessmentConfig cfg : defaultConfigs) {
            HotDriverAnnualAssessmentConfig newCfg = new HotDriverAnnualAssessmentConfig();
            // 复制属性，排除ID和创建时间等
            newCfg.setCompanyId(companyId);
            newCfg.setContent(cfg.getContent());
            newCfg.setScore(cfg.getScore());
            newCfg.setCategory(cfg.getCategory());
            newCfg.setIsDeleted(0L);
            newConfigs.add(newCfg);
        }

        return baseMapper.insertBatch(newConfigs);
    }


    /**
     * 分页查询驾驶员年度考核配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 驾驶员年度考核配置分页列表
     */
    @Override
    public TableDataInfo<HotDriverAnnualAssessmentConfigVo> queryPageList(HotDriverAnnualAssessmentConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotDriverAnnualAssessmentConfig> lqw = buildQueryWrapper(bo);
        Page<HotDriverAnnualAssessmentConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的驾驶员年度考核配置列表
     *
     * @param bo 查询条件
     * @return 驾驶员年度考核配置列表
     */
    @Override
    public List<HotDriverAnnualAssessmentConfigVo> queryList(HotDriverAnnualAssessmentConfigBo bo) {
        LambdaQueryWrapper<HotDriverAnnualAssessmentConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotDriverAnnualAssessmentConfig> buildQueryWrapper(HotDriverAnnualAssessmentConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotDriverAnnualAssessmentConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotDriverAnnualAssessmentConfig::getId);
        lqw.eq(bo.getCompanyId() != null, HotDriverAnnualAssessmentConfig::getCompanyId, bo.getCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotDriverAnnualAssessmentConfig::getContent, bo.getContent());
        lqw.eq(bo.getScore() != null, HotDriverAnnualAssessmentConfig::getScore, bo.getScore());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), HotDriverAnnualAssessmentConfig::getCategory, bo.getCategory());
        lqw.eq(bo.getIsDeleted() != null, HotDriverAnnualAssessmentConfig::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增驾驶员年度考核配置
     *
     * @param bo 驾驶员年度考核配置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotDriverAnnualAssessmentConfigBo bo) {
        HotDriverAnnualAssessmentConfig add = MapstructUtils.convert(bo, HotDriverAnnualAssessmentConfig.class);
        Long companyId = resolveCompanyId(add.getCompanyId());
        add.setCompanyId(companyId);
        applyInsertEnabledRule(add, companyId);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改驾驶员年度考核配置
     *
     * @param bo 驾驶员年度考核配置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotDriverAnnualAssessmentConfigBo bo) {
        HotDriverAnnualAssessmentConfig update = MapstructUtils.convert(bo, HotDriverAnnualAssessmentConfig.class);
        Long companyId = resolveCompanyId(update.getCompanyId());
        update.setCompanyId(companyId);
        validateUpdateEnabledRule(update, companyId);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    private Long resolveCompanyId(Long companyId) {
        if (companyId != null) {
            return companyId;
        }
        Long loginCompanyId = LoginHelper.getCompanyId();
        if (loginCompanyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        return loginCompanyId;
    }

    private void applyInsertEnabledRule(HotDriverAnnualAssessmentConfig entity, Long companyId) {
        Long isEnabled = entity.getIsEnabled();
        if (isEnabled == null || isEnabled != ENABLED_STATUS) {
            if (isEnabled == null) {
                entity.setIsEnabled(DISABLED_STATUS);
            }
            return;
        }
        long enabledTotalScore = getEnabledTotalScore(companyId, null) + safeScore(entity.getScore());
        if (enabledTotalScore > MAX_ENABLED_TOTAL_SCORE) {
            entity.setIsEnabled(DISABLED_STATUS);
        }
    }

    private void validateUpdateEnabledRule(HotDriverAnnualAssessmentConfig entity, Long companyId) {
        if (entity.getIsEnabled() == null || entity.getIsEnabled() != ENABLED_STATUS) {
            return;
        }
        long enabledTotalScore = getEnabledTotalScore(companyId, entity.getId()) + safeScore(entity.getScore());
        if (enabledTotalScore > MAX_ENABLED_TOTAL_SCORE) {
            throw new ServiceException("启用失败：当前启用项总分值不能超过100分");
        }
    }

    private long getEnabledTotalScore(Long companyId, Long excludeId) {
        LambdaQueryWrapper<HotDriverAnnualAssessmentConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotDriverAnnualAssessmentConfig::getCompanyId, companyId);
        lqw.eq(HotDriverAnnualAssessmentConfig::getIsEnabled, ENABLED_STATUS);
        lqw.ne(excludeId != null, HotDriverAnnualAssessmentConfig::getId, excludeId);
        List<HotDriverAnnualAssessmentConfig> enabledConfigs = baseMapper.selectList(lqw);
        return enabledConfigs.stream()
                .map(HotDriverAnnualAssessmentConfig::getScore)
                .filter(score -> score != null)
                .mapToLong(Long::longValue)
                .sum();
    }

    private long safeScore(Long score) {
        return score == null ? 0L : score;
    }

    /**
     * 校验并批量删除驾驶员年度考核配置信息
     *
     * @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(HotDriverAnnualAssessmentConfig.class)
                        .eq(HotDriverAnnualAssessmentConfig::getCompanyId, companyId)
        ) > 0;
    }
}
