package com.simuwang.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.simuwang.base.common.util.DateUtils;
import com.simuwang.base.mapper.EmailFundNavMapper;
import com.simuwang.base.pojo.dos.CompanyEmailSendHistoryDO;
import com.simuwang.base.pojo.dos.EmailFundNavDO;
import com.simuwang.base.pojo.dos.NavDO;
import com.simuwang.daq.service.EmailParseService;
import com.simuwang.manage.service.EmailFundNavService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * FileName: EmailFileNavServiceImpl
 * Author:   chenjianhua
 * Date:     2024/9/15 11:25
 * Description: ${DESCRIPTION}
 */
@Service
public class EmailFundNavServiceImpl implements EmailFundNavService {

    @Autowired
    private EmailFundNavMapper emailFundNavMapper;

    @Autowired
    private EmailParseService emailParseService;

    @Override
    public void reparseFileNav(String sourceFundName, String targetFundId) {
        List<EmailFundNavDO> fundNavDOList = emailFundNavMapper.selectNotMappingNav(sourceFundName);
        Map<String,List<EmailFundNavDO>> fundNavDOGroup = fundNavDOList.stream().collect(Collectors.groupingBy(e -> DateUtils.format(e.getPriceDate(),DateUtils.YYYY_MM_DD)));
        List<EmailFundNavDO> dataList = new ArrayList<>();
        //去重
        for(String priceDate : fundNavDOGroup.keySet()){
            List<EmailFundNavDO> doList = fundNavDOGroup.get(priceDate);
            dataList.add(doList.get(0));
        }
        if(fundNavDOList.size() > 0){
            //修改采集库的数据
            for(EmailFundNavDO fundNavDO : fundNavDOList){
                fundNavDO.setFundId(targetFundId);
                fundNavDO.setExceptionStatus(1);
                fundNavDO.setIsStored(1);
                fundNavDO.setUpdateTime(new Date());
            }
            emailFundNavMapper.batchUpdate(fundNavDOList);
            //净值入库
            List<NavDO> navDOList = dataList.stream().filter(e -> StrUtil.isNotBlank(e.getFundId()))
                    .map(e -> BeanUtil.copyProperties(e, NavDO.class)).collect(Collectors.toList());
            navDOList.forEach(e -> e.setUpdateTime(DateUtils.getNowDate()));
            emailParseService.saveNavDo(navDOList);
        }
    }
}
