package com.artfess.cqlt.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.artfess.base.enums.DelStatusEnum;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.cqlt.dao.QfInvestPatentDDao;
import com.artfess.cqlt.dao.QfInvestPatentMDao;
import com.artfess.cqlt.dao.QfInvestProductivityDDao;
import com.artfess.cqlt.dao.QfInvestProductivityMDao;
import com.artfess.cqlt.manager.QfInvestPatentDManager;
import com.artfess.cqlt.model.QfInvestExpenditureD;
import com.artfess.cqlt.model.QfInvestPatentD;
import com.artfess.cqlt.model.QfInvestPatentM;
import com.artfess.cqlt.model.QfInvestProductivityD;
import com.artfess.cqlt.model.QfInvestProductivityM;
import com.artfess.cqlt.vo.ReportReqVo;
import com.artfess.i18n.util.I18nUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 投资--萨固密集团专利授权数据填报详情表 服务实现类
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2023-02-23
 */
@Service
public class QfInvestPatentDManagerImpl extends BaseManagerImpl<QfInvestPatentDDao, QfInvestPatentD> implements QfInvestPatentDManager {

    @Resource
    private QfInvestProductivityMDao investProductivityMDao;

    @Resource
    private QfInvestProductivityDDao investProductivityDDao;

    @Resource
    private QfInvestPatentMDao investPatentMDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(QfInvestPatentM t) {
        Assert.hasText(t.getId(), I18nUtil.getMessage("QfOperationKpiM.reportId", LocaleContextHolder.getLocale()));
        QfInvestPatentM qfInvestPatentM = investPatentMDao.selectById(t.getId());
        Assert.notNull(qfInvestPatentM, I18nUtil.getMessage("filldata.notExist", LocaleContextHolder.getLocale()));
        Assert.isTrue(!"1".equals(qfInvestPatentM.getStatus()),  I18nUtil.getMessage("data_operate", LocaleContextHolder.getLocale()));
        t.getList().forEach(detail -> {
            detail.setMainId(t.getId());
        });
        boolean b = this.saveOrUpdateBatch(t.getList());
        return b;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdate(QfInvestPatentM t) {
        Assert.hasText(t.getId(), I18nUtil.getMessage("QfOperationKpiM.reportId", LocaleContextHolder.getLocale()));
        t.getList().forEach(detail -> {
            detail.setMainId(t.getId());
        });
        boolean b = this.saveOrUpdateBatch(t.getList());
        return b;
    }

    @Override
    public JSONObject investmentSituation(ReportReqVo vo) {

        if (null == vo.getStartYear() && null == vo.getEndYear()) {
            int endYear = LocalDate.now().getYear();
            vo.setEndYear(endYear);
            vo.setStartYear(endYear - 10);
        }

        JSONObject result = new JSONObject();
        List<QfInvestPatentD> patentsData = Lists.newArrayList();
        Map<String, List<QfInvestPatentD>> patents = baseMapper.countPatents(vo).stream().collect(Collectors.groupingBy(QfInvestPatentD::getSubjectCode));
        // 整理前端约定格式
        patents.entrySet().forEach(p -> {
            QfInvestPatentD data = new QfInvestPatentD();
            data.setSubjectCode(p.getKey());
            List<QfInvestPatentD> list = Lists.newArrayList();
            p.getValue().forEach(pl -> {
                data.setSubjectName(pl.getSubjectName());
                data.setSubjectNameEn(pl.getSubjectNameEn());
                data.setSubjectLevel(pl.getSubjectLevel());
                data.setSubjectUnit(pl.getSubjectUnit());
                list.add(new QfInvestPatentD(pl.getFillData(), pl.getFillYear()));
            });
            // 填充不连续的年份
            Comparator<QfInvestPatentD> comparator = Comparator.comparing(QfInvestPatentD::getFillYear);
            List<QfInvestPatentD> filledList = IntStream.range(0, list.size() - 1)
                    .mapToObj(i -> {
                        QfInvestPatentD prev = list.get(i);
                        QfInvestPatentD current = list.get(i + 1);
                        int diff = current.getFillYear() - prev.getFillYear();
                        if (diff > 1) {
                            return IntStream.range(1, diff)
                                    .mapToObj(j -> new QfInvestPatentD(new BigDecimal(0), prev.getFillYear() + j))
                                    .collect(Collectors.toList());
                        } else {
                            return new ArrayList<QfInvestPatentD>();
                        }
                    })
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
            filledList.addAll(list);
            filledList.sort(comparator);

            data.setList(filledList);
            patentsData.add(data);
        });
        result.put("patents", patentsData);

        List<QfInvestExpenditureD> investmentSituation = baseMapper.investmentSituation(vo);
        investmentSituation.forEach(reportRespVo -> {
            if (null != reportRespVo.getBudget() && null != reportRespVo.getActual()) {
                BigDecimal differenceValue = reportRespVo.getActual().subtract(reportRespVo.getBudget());
                reportRespVo.setDifferenceValue(differenceValue);
                String differenceRate = null;
                if(0 != reportRespVo.getActual().doubleValue()) {
                    differenceRate = differenceValue.divide(reportRespVo.getActual(), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")) + "%";
                }
                reportRespVo.setDifferenceRate(differenceRate);
            }
        });
        result.put("investmentSituation", investmentSituation);

        return result;
    }

    @Override
    public List<QfInvestProductivityD> capacitySituation(ReportReqVo vo) {
        if (null == vo.getStartYear() && null == vo.getEndYear()) {
            int endYear = LocalDate.now().getYear();
            vo.setEndYear(endYear);
            vo.setStartYear(endYear - 5);
        }

        QueryWrapper<QfInvestProductivityM> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("fill_year_");
        queryWrapper.orderByDesc("fill_month_");
        List<QfInvestProductivityM> qfInvestPatentMS = investProductivityMDao.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(qfInvestPatentMS)) {
            return Lists.newArrayList();
        }
        QfInvestProductivityM main = qfInvestPatentMS.get(0);
        QueryWrapper<QfInvestProductivityD> dQueryWrapper = new QueryWrapper<>();
        dQueryWrapper.eq("main_id_", main.getId());
        List<QfInvestProductivityD> result = investProductivityDDao.selectList(dQueryWrapper);
        return result;
    }
}
