package com.dsk.cscec.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.dsk.cscec.domain.CbSummary;
import com.dsk.cscec.domain.bo.CbSummaryActualListBo;
import com.dsk.cscec.domain.vo.CbGainLossAnalysisListVo;
import com.dsk.cscec.mapper.CbSummaryMapper;
import com.dsk.cscec.service.ICbGainLossAnalysisService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author lcl
 * @Data 2024/2/18 14:03
 */
@Slf4j
@Service
public class CbGainLossAnalysisServiceImpl implements ICbGainLossAnalysisService {

    @Resource
    private CbSummaryMapper cbSummaryMapper;

    @Override
    public List<CbGainLossAnalysisListVo> getList(CbSummaryActualListBo bo) {
        Assert.notNull(bo.getId(),"id不能为空");

        List<CbGainLossAnalysisListVo> resultList = new ArrayList<>();
        if (StringUtil.isBlank(bo.getExpenseDate())) {
            //默认当前月
            bo.setExpenseDate(DatePattern.SIMPLE_MONTH_FORMAT.format(new Date()));
        }

        CbSummary cbSummary = cbSummaryMapper.selectById(bo.getId());
        if (ObjectUtil.isEmpty(cbSummary)) {
            return resultList;
        }

        List<CbGainLossAnalysisListVo> childrenList = cbSummaryMapper.getGainLossAnalysisByParentId(bo.getId(), bo.getExpenseDate());
        if (0 == cbSummary.getLevel()) {
            resultList = childrenList;
        }else {
            childrenList = getProjectSumList(bo);
            CbGainLossAnalysisListVo cbGainLossAnalysisListVo = cbSummaryMapper.getGainLossAnalysisById(bo.getId(),bo.getExpenseDate());
            cbGainLossAnalysisListVo.setChildren(childrenList);
            resultList.add(cbGainLossAnalysisListVo);
        }
        return resultList;
    }

    /**
     * 盈亏对比分析列表
     *
     */
    private List<CbGainLossAnalysisListVo> getProjectSumList(CbSummaryActualListBo bo) {

        List<CbGainLossAnalysisListVo> childrenList = cbSummaryMapper.getGainLossAnalysisByParentId(bo.getId(), bo.getExpenseDate());
        childrenList.forEach(children -> {
            CbSummaryActualListBo childBo = new CbSummaryActualListBo();
            childBo.setId(children.getId());
            childBo.setExpenseDate(bo.getExpenseDate());
            children.setChildren(getProjectSumList(childBo));
        });

        return childrenList;

    }
}
