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.EmailFundAssetMapper;
import com.simuwang.base.pojo.dos.AssetDO;
import com.simuwang.base.pojo.dos.EmailFundAssetDO;
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.EmailFundAssetService;
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: EmailFundAssetServiceImpl
 * Author:   chenjianhua
 * Date:     2024/9/15 12:43
 * Description: ${DESCRIPTION}
 */
@Service
public class EmailFundAssetServiceImpl implements EmailFundAssetService {

    @Autowired
    private EmailFundAssetMapper emailFundAssetMapper;

    @Autowired
    private EmailParseService emailParseService;

    @Override
    public void reparseFileAsset(String sourceFundName, String targetFundId) {
        List<EmailFundAssetDO> fundAssetDOList = emailFundAssetMapper.selectNotMappingAsset(sourceFundName);
        Map<String,List<EmailFundAssetDO>> fundAssetDOGroup = fundAssetDOList.stream().collect(Collectors.groupingBy(e -> DateUtils.format(e.getPriceDate(),DateUtils.YYYY_MM_DD)));
        List<EmailFundAssetDO> dataList = new ArrayList<>();
        //去重
        for(String priceDate : fundAssetDOGroup.keySet()){
            List<EmailFundAssetDO> doList = fundAssetDOGroup.get(priceDate);
            dataList.add(doList.get(0));
        }
        if(fundAssetDOList.size() > 0){
            //修改采集库的数据
            for(EmailFundAssetDO fundNavDO : fundAssetDOList){
                fundNavDO.setFundId(targetFundId);
                fundNavDO.setExceptionStatus(1);
                fundNavDO.setIsvalid(1);
                fundNavDO.setIsStored(1);
                fundNavDO.setUpdateTime(new Date());
                fundNavDO.setCreateTime(new Date());
            }
            emailFundAssetMapper.batchUpdate(fundAssetDOList);
            //净值入库
            List<AssetDO> assetDOList = dataList.stream().filter(e -> StrUtil.isNotBlank(e.getFundId()))
                    .map(e -> BeanUtil.copyProperties(e, AssetDO.class)).collect(Collectors.toList());
            emailParseService.saveAssetDo(assetDOList);
        }
    }
}
