package com.smppw.modaq.application.components.report.writer;

import com.smppw.modaq.domain.dto.report.ReportBaseInfoDTO;
import com.smppw.modaq.domain.dto.report.ReportData;
import com.smppw.modaq.domain.dto.report.ReportFundInfoDTO;
import com.smppw.modaq.domain.mapper.report.ReportBaseInfoMapper;
import com.smppw.modaq.domain.mapper.report.ReportFundInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractReportWriter<T extends ReportData> implements ReportWriter<T> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ReportBaseInfoMapper baseInfoMapper;
    private final ReportFundInfoMapper fundInfoMapper;

    public AbstractReportWriter(ReportBaseInfoMapper baseInfoMapper, ReportFundInfoMapper fundInfoMapper) {
        this.baseInfoMapper = baseInfoMapper;
        this.fundInfoMapper = fundInfoMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void write(T reportData) {
        if (reportData == null) {
            this.logger.error("The report no result!");
            return;
        }
        // 基本信息+基金信息保存
        this.saveBaseInfo(reportData);
        this.saveFundInfo(reportData);
        // 其他信息保存
        this.writeExtData(reportData);
    }

    private void saveBaseInfo(T reportData) {
        ReportBaseInfoDTO baseInfo = reportData.getBaseInfo();
        if (baseInfo != null) {
            this.baseInfoMapper.insert(baseInfo.toEntity());
        }
    }

    private void saveFundInfo(T reportData) {
        ReportFundInfoDTO fundInfo = reportData.getFundInfo();
        if (fundInfo != null) {
            this.fundInfoMapper.insert(fundInfo.toEntity());
        }
    }

    protected abstract void writeExtData(T reportData);
}
