package com.simuwang.daq.components.report.writer;

import com.simuwang.base.mapper.report.ReportBaseInfoMapper;
import com.simuwang.base.mapper.report.ReportFundInfoMapper;
import com.simuwang.base.pojo.dos.report.ReportBaseInfoDO;
import com.simuwang.base.pojo.dos.report.ReportFundInfoDO;
import com.simuwang.base.pojo.dto.report.ReportBaseInfoDTO;
import com.simuwang.base.pojo.dto.report.ReportData;
import com.simuwang.base.pojo.dto.report.ReportFundInfoDTO;
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) {
            ReportBaseInfoDO entity = baseInfo.toEntity();
            this.baseInfoMapper.insert(entity);
        }
    }

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

    protected abstract void writeExtData(T reportData);
}
