package com.ruoyi.docking.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.docking.entity.ProjectProgress;
import com.ruoyi.docking.entity.request.YdxxtjRequest;
import com.ruoyi.docking.mapper.ProjectProgressMapper;
import com.ruoyi.docking.service.ProjectProgressService;
import com.ruoyi.gysl.entity.BasicInformation;
import com.ruoyi.gysl.entity.request.ZwIdPageReq;
import com.ruoyi.gysl.entity.response.YdxxtjResponse;
import com.ruoyi.gysl.service.BasicInformationService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 项目月度进度（对接数据）(ProjectProgress)表服务实现类
 *
 * @author makejava
 * @since 2025-03-25 14:49:04
 */
@Service("projectProgressService")
public class ProjectProgressServiceImpl extends ServiceImpl<ProjectProgressMapper, ProjectProgress> implements ProjectProgressService {

    @Resource
    private BasicInformationService basicInformationService;

    @Resource
    private ProjectProgressMapper projectProgressMapper;

    @Value("${isZs}")
    private Boolean isZs;

    /**
     * 查询所有数据
     *
     * @param zwIdPageReq 查询实体
     * @return 所有数据
     */
    @Override
    public List<ProjectProgress> page(ZwIdPageReq zwIdPageReq) {
        //查询对应的项目基础信息数据
        BasicInformation byId = basicInformationService.getById(zwIdPageReq.getXmId());
        //获取对接的数据
        List<ProjectProgress> page = new ArrayList<>();
        if (isZs) {
            page = projectProgressMapper.page(byId.getName());
        }
        List<ProjectProgress> list = projectProgressMapper.getXmId(byId.getId());
        return new ArrayList<>(Stream.concat(list.stream(), page.stream())
                .collect(Collectors.toMap(
                        ProjectProgress::getMonth,
                        v -> v,
                        (existing, replacement) -> existing // 冲突时保留现有值（即list中的值）
                ))
                .values());
    }

    /**
     * 项目月度信息投资统计
     */
    @Override
    public List<YdxxtjResponse> ydxxtj(YdxxtjRequest zwIdPageReq) {
        //查询对应的项目基础信息数据
        BasicInformation byId = basicInformationService.getById(zwIdPageReq.getXmId());
        //获取对接的数据
        List<ProjectProgress> page = new ArrayList<>();
        if (isZs) {
            page = projectProgressMapper.page(byId.getName());
        }
        List<ProjectProgress> list = projectProgressMapper.getXmId(byId.getId());
        List<ProjectProgress> projectProgresses = new ArrayList<>(Stream.concat(list.stream(), page.stream())
                .collect(Collectors.toMap(
                        ProjectProgress::getMonth,
                        v -> v,
                        (existing, replacement) -> existing // 冲突时保留现有值（即list中的值）
                ))
                .values());
        List<YdxxtjResponse> res = new ArrayList<>();
        if (zwIdPageReq.getType() == 1) {
            projectProgresses.forEach(x -> {
                if (x.getMonth() != null && x.getMonth().substring(0, 4).equals(zwIdPageReq.getYears())) {
                    YdxxtjResponse yd = new YdxxtjResponse();
                    yd.setMonth(x.getMonth());
                    yd.setYtze(BigDecimal.valueOf(x.getMonthDoneAmount()));
                    if(byId.getJhtze()==null||x.getMonthDoneAmount()==null){
                        yd.setYtzbl(new BigDecimal(0));
                    }else {
                        yd.setYtzbl(BigDecimal.valueOf(x.getMonthDoneAmount()).divide(byId.getJhtze(), RoundingMode.HALF_UP));
                    }
                    yd.setLjtze(BigDecimal.valueOf(x.getTotalDoneAmount()));
                    res.add(yd);
                }
            });
            return res;
        } else if (zwIdPageReq.getType() == 2) {
            YdxxtjResponse yd1 = new YdxxtjResponse();
            yd1.setJd(1);
            yd1.setJdtze(new BigDecimal(0));
            YdxxtjResponse yd2 = new YdxxtjResponse();
            yd2.setJd(2);
            yd2.setJdtze(new BigDecimal(0));
            YdxxtjResponse yd3 = new YdxxtjResponse();
            yd3.setJd(3);
            yd3.setJdtze(new BigDecimal(0));
            YdxxtjResponse yd4 = new YdxxtjResponse();
            yd4.setJd(4);
            yd4.setJdtze(new BigDecimal(0));
            res.add(yd1);
            res.add(yd2);
            res.add(yd3);
            res.add(yd4);
            projectProgresses.forEach(x -> {
                if (x.getMonth() != null && x.getMonth().substring(0, 4).equals(zwIdPageReq.getYears())) {
                    String monthStr = x.getMonth().substring(5, 7); // 提取 "MM"
                    // 计算季度：1~3月为Q1，4~6月为Q2，7~9月为Q3，10~12月为Q4
                    int quarter = (Integer.parseInt(monthStr) - 1) / 3 + 1;
                    for (YdxxtjResponse re : res) {
                        if (re.getJd() == quarter) {
                            re.setJdtze(re.getJdtze().add(BigDecimal.valueOf(x.getMonthDoneAmount())));
                        }
                    }
                }
            });
            return res;
        } else {
            throw new ServiceException("查询失败");
        }
    }
}

