package org.dromara.progress.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.facility.domain.FacPercentageFacility;
import org.dromara.facility.service.IFacPercentageFacilityService;
import org.dromara.progress.constant.PgsProgressCategoryConstant;
import org.dromara.progress.domain.PgsProgressCategory;
import org.dromara.progress.domain.PgsProgressCategoryTemplate;
import org.dromara.progress.domain.dto.progresscategory.PgsProgressCategoryCreateReq;
import org.dromara.progress.domain.dto.progresscategory.PgsProgressCategoryQueryReq;
import org.dromara.progress.domain.dto.progresscategory.PgsProgressCategoryUpdateReq;
import org.dromara.progress.domain.enums.PgsProgressUnitTypeEnum;
import org.dromara.progress.domain.vo.progresscategory.PgsProgressCategoryVo;
import org.dromara.progress.mapper.PgsProgressCategoryMapper;
import org.dromara.progress.service.IPgsProgressCategoryService;
import org.dromara.progress.service.IPgsProgressCategoryTemplateService;
import org.dromara.utils.BigDecimalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 进度类别Service业务层处理
 *
 * @author lcj
 * @date 2025-05-26
 */
@Service
public class PgsProgressCategoryServiceImpl extends ServiceImpl<PgsProgressCategoryMapper, PgsProgressCategory>
    implements IPgsProgressCategoryService {

    @Resource
    private IPgsProgressCategoryTemplateService pgsProgressCategoryTemplateService;

    @Resource
    private IFacPercentageFacilityService percentageFacilityService;

    /**
     * 查询进度类别
     *
     * @param id 主键
     * @return 进度类别
     */
    @Override
    public PgsProgressCategoryVo queryById(Long id) {
        PgsProgressCategory progressCategory = this.getById(id);
        if (progressCategory == null) {
            throw new ServiceException("进度类别信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(progressCategory);
    }

    /**
     * 查询符合条件的进度类别列表
     *
     * @param req 查询条件
     * @return 进度类别列表
     */
    @Override
    public List<PgsProgressCategoryVo> queryList(PgsProgressCategoryQueryReq req) {
        List<PgsProgressCategory> list = this.list(this.buildQueryWrapper(req));
        return this.getVoList(list);
    }

    /**
     * 新增进度类别
     *
     * @param req 进度类别
     * @return 新增进度类别id
     */
    @Override
    public Long insertByBo(PgsProgressCategoryCreateReq req) {
        // 将实体类和 DTO 进行转换
        PgsProgressCategory progressCategory = new PgsProgressCategory();
        BeanUtils.copyProperties(req, progressCategory);
        // 数据校验
        validEntityBeforeSave(progressCategory);
        // 写入数据库
        boolean result = this.save(progressCategory);
        if (!result) {
            throw new ServiceException("新增进度类别失败，数据库异常", HttpStatus.ERROR);
        }
        return progressCategory.getId();
    }

    /**
     * 修改进度类别
     *
     * @param req 进度类别
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PgsProgressCategoryUpdateReq req) {
        // 将实体类和 DTO 进行转换
        PgsProgressCategory progressCategory = new PgsProgressCategory();
        BeanUtils.copyProperties(req, progressCategory);
        PgsProgressCategory oldProgressCategory = this.getById(req.getId());
        if (oldProgressCategory == null) {
            throw new ServiceException("修改进度类别失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 数据校验
        validEntityBeforeSave(progressCategory);
        // 写入数据库
        boolean result = this.updateById(progressCategory);
        if (!result) {
            throw new ServiceException("更新进度类别失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PgsProgressCategory entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        Long pid = entity.getPid();
        if (projectId != null && projectId != 0) {
            if (this.getById(projectId) == null) {
                throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
            }
        }
        if (pid != null && pid != 0) {
            if (this.getById(pid) == null) {
                throw new ServiceException("对应进度类别不存在", HttpStatus.NOT_FOUND);
            }
        }
        // 名称唯一性校验
        LambdaQueryWrapper<PgsProgressCategory> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PgsProgressCategory::getName, entity.getName());
        if (projectId != null && projectId != 0) {
            lqw.eq(PgsProgressCategory::getProjectId, entity.getProjectId());
        }
        if (pid != null && pid != 0) {
            lqw.eq(PgsProgressCategory::getPid, entity.getPid());
        }
        if (entity.getId() != null) {
            // 排除自身
            lqw.ne(PgsProgressCategory::getId, entity.getId());
        }
        if (this.count(lqw) > 0) {
            throw new ServiceException("已有同名进度类别", HttpStatus.CONFLICT);
        }
    }

    /**
     * 校验并批量删除进度类别信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取进度类别视图对象
     *
     * @param progressCategory 进度类别对象
     * @return 进度类别视图对象
     */
    @Override
    public PgsProgressCategoryVo getVo(PgsProgressCategory progressCategory) {
        if (progressCategory == null) {
            return null;
        }
        // 对象转封装类
        PgsProgressCategoryVo progressCategoryVo = new PgsProgressCategoryVo();
        BeanUtils.copyProperties(progressCategory, progressCategoryVo);
        return progressCategoryVo;
    }

    /**
     * 获取进度类别查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<PgsProgressCategory> buildQueryWrapper(PgsProgressCategoryQueryReq req) {
        LambdaQueryWrapper<PgsProgressCategory> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        Long matrixId = req.getMatrixId();
        // 精确查询
        lqw.in(ObjectUtils.isNotEmpty(projectId), PgsProgressCategory::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(matrixId), PgsProgressCategory::getMatrixId, matrixId);
        lqw.orderByAsc(PgsProgressCategory::getWorkType);
        return lqw;
    }

    /**
     * 获取进度类别列表对象视图
     *
     * @param progressCategoryList 进度类别列表对象
     * @return 进度类别列表对象视图
     */
    @Override
    public List<PgsProgressCategoryVo> getVoList(List<PgsProgressCategory> progressCategoryList) {
        if (CollUtil.isEmpty(progressCategoryList)) {
            return List.of();
        }
        // 1. 构建 pid -> 子节点列表的映射
        Map<Long, List<PgsProgressCategory>> parentIdToChildrenMap = progressCategoryList.stream()
            .filter(item -> item.getPid() != 0)
            .collect(Collectors.groupingBy(PgsProgressCategory::getPid));
        // 对象列表 => 封装对象列表
        return progressCategoryList.stream().map(progressCategory -> {
            PgsProgressCategoryVo vo = new PgsProgressCategoryVo();
            BeanUtils.copyProperties(progressCategory, vo);
            // 如果是父节点，计算其子节点的总和
            if (progressCategory.getPid() == 0) {
                List<PgsProgressCategory> children = parentIdToChildrenMap.getOrDefault(progressCategory.getId(), Collections.emptyList());
                // 累加子节点数据
                BigDecimal total = children.stream().map(PgsProgressCategory::getTotal).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal completed = children.stream().map(PgsProgressCategory::getCompleted).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal planTotal = children.stream().map(PgsProgressCategory::getPlanTotal).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 可以在 VO 中额外设置这些总和值（或替换原有字段）
                vo.setTotal(total);
                vo.setCompleted(completed);
                vo.setPlanTotal(planTotal);
            }
            // 计算百分比（避免除以 0）
            vo.setCompletedPercentage(BigDecimalUtil.toPercentage(vo.getCompleted(), vo.getTotal()));
            vo.setPlanTotalPercentage(BigDecimalUtil.toPercentage(vo.getPlanTotal(), vo.getTotal()));
            return vo;
        }).toList();
    }

    /**
     * 根据模板创建进度类别
     *
     * @param projectId 项目id
     * @param matrixIds 方阵id列表
     * @return 是否创建成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByTemplate(Long projectId, List<Long> matrixIds) {
        // 获取模板进度类别
        List<PgsProgressCategoryTemplate> categoryTemplateList = pgsProgressCategoryTemplateService.lambdaQuery()
            .in(PgsProgressCategoryTemplate::getProjectId, projectId, PgsProgressCategoryConstant.PUBLIC_PROJECT_ID)
            .list();
        // 遍历模板进度类别，复制数据
        if (CollUtil.isEmpty(categoryTemplateList)) {
            throw new ServiceException("对应模板进度类别不存在", HttpStatus.NOT_FOUND);
        }
        List<PgsProgressCategory> newList = new ArrayList<>();
        List<FacPercentageFacility> percentageFacilityList = new ArrayList<>();
        // 每个 matrixId 对应一套新的 ID 映射
        for (Long matrixId : matrixIds) {
            // templateId -> newId
            Map<Long, Long> localIdMap = new HashMap<>();
            List<PgsProgressCategory> localList = new ArrayList<>();
            for (PgsProgressCategoryTemplate template : categoryTemplateList) {
                Long newId = IdWorker.getId();
                localIdMap.put(template.getId(), newId);
                PgsProgressCategory newCategory = new PgsProgressCategory();
                newCategory.setId(newId);
                newCategory.setName(template.getName());
                newCategory.setUnitType(template.getUnitType());
                newCategory.setWorkType(template.getWorkType());
                newCategory.setProjectId(projectId);
                newCategory.setMatrixId(matrixId);
                // 先临时设置旧 pid
                newCategory.setPid(template.getPid());
                localList.add(newCategory);
                // 创建百分比设施
                if (template.getPid() != 0 && template.getUnitType().equals(PgsProgressUnitTypeEnum.PERCENTAGE.getValue())) {
                    newCategory.setTotal(BigDecimal.valueOf(100));
                    FacPercentageFacility percentageFacility = new FacPercentageFacility();
                    percentageFacility.setProjectId(projectId);
                    percentageFacility.setMatrixId(matrixId);
                    percentageFacility.setProgressCategoryId(newId);
                    percentageFacility.setProgressCategoryName(template.getName());
                    percentageFacilityList.add(percentageFacility);
                }
            }
            // 修正本 matrix 的 pid
            for (PgsProgressCategory category : localList) {
                Long oldPid = category.getPid();
                if (oldPid != 0) {
                    category.setPid(localIdMap.getOrDefault(oldPid, 0L));
                }
            }
            newList.addAll(localList);
        }
        boolean result = this.saveBatch(newList);
        if (!result) {
            throw new ServiceException("创建进度类别失败", HttpStatus.ERROR);
        }
        // 保存百分比设施
        if (CollUtil.isNotEmpty(percentageFacilityList)) {
            boolean save = percentageFacilityService.saveBatch(percentageFacilityList);
            if (!save) {
                throw new ServiceException("创建设施失败", HttpStatus.ERROR);
            }
        }
        return true;
    }
}
