package com.zjty.inspect.service.impl;

import com.zjty.inspect.dao.MasterReportDao;
import com.zjty.inspect.dao.TechnologyDao;
import com.zjty.inspect.entity.*;
import com.zjty.inspect.service.ParameterService;
import com.zjty.inspect.service.ReportService;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.Map;
import java.util.Optional;

/**
 * @author Mcj
 * @date 2020-02-27 10:35
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ReportServiceImpl implements ReportService {

    @Autowired
    private TechnologyDao technologyDao;

    @Autowired
    private ParameterService parameterService;

    @Autowired
    private MasterReportDao reportDao;

    //执行静态化
    private String generateHtml(String templateContent, Map model ){
        //创建配置对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //创建模板加载器
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate("template",templateContent);
        //向configuration配置模板加载器
        configuration.setTemplateLoader(stringTemplateLoader);
        //获取模板
        try {
            Template template = configuration.getTemplate("template");
            //调用api进行静态化
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    public CustomPage findReportByPage(int page) {
        PageRequest of = PageRequest.of(page - 1, 10);
        org.springframework.data.domain.Page<MasterReport> all = reportDao.findAll(of);
        CustomPage<MasterReport> reportCustomPage = new CustomPage<>();
        reportCustomPage.setTotalElement((int) all.getTotalElements());
        reportCustomPage.setTotalPage(all.getTotalPages());
        reportCustomPage.addAll(all.getContent());
        return reportCustomPage;
    }

    @Override
    public ReportManage findReportById(String id) {
        Optional<MasterReport> report = reportDao.findById(id);
        ReportManage reportManage = new ReportManage();
        if(report.isPresent()){
            reportManage.setReport(report.get());
            InspectParameter inspectParameter = parameterService.getParameterById(report.get().getId());
            reportManage.setInspectParameter(inspectParameter);
        }
        return reportManage;
    }

    @Override
    public void saveReport(MasterReport report) {
        reportDao.save(report);
    }
}
