package com.zehong.system.config.ureport;

import com.bstek.ureport.exception.ReportException;
import com.zehong.system.domain.BaseExportTemp;
import com.zehong.system.mapper.BaseExportTempMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

@Service
public class UreportBusinessService extends FileReportProvider{
    @Resource
    private BaseExportTempMapper baseExportTempMapper;

    @Override
    public void deleteReport(String file) {
        if(file.startsWith(getPrefix())){
            file=file.substring(getPrefix().length(),file.length());
        }
        String fullPath=getFileStoreDir()+"/"+file;

        //删除数据库记录
        BaseExportTemp baseExportTemp = baseExportTempMapper.selectSignleByFullPath(fullPath);
        if(baseExportTemp!=null){
            baseExportTempMapper.deleteBaseExportTempById(baseExportTemp.getId());
        }

        File f=new File(fullPath);
        if(f.exists()){
            f.delete();
        }
    }

    @Override
    public void saveReport(String file, String content) {
        if(file.startsWith(getPrefix())){
            file=file.substring(getPrefix().length(),file.length());
        }
        String fullPath=getFileStoreDir()+"/"+file;
        FileOutputStream outStream=null;
        try{
            outStream=new FileOutputStream(new File(fullPath));
            IOUtils.write(content, outStream,"utf-8");
            //判断模板是否已存在---根据模板fullPath查询
            BaseExportTemp baseExportTemp = baseExportTempMapper.selectSignleByFullPath(fullPath);
            if(baseExportTemp!=null){
                //更新模板数据库
                baseExportTemp.setContent(content);
                baseExportTemp.setUpdateTime(new Date());
                baseExportTempMapper.updateBaseExportTemp(baseExportTemp);
            }else{
                //将模板数据保存在数据库中
                baseExportTemp = new BaseExportTemp();
                baseExportTemp.setContent(content);
                baseExportTemp.setFileStoreDir(getFileStoreDir());
                baseExportTemp.setFullPath(fullPath);
                baseExportTemp.setName(file.replaceAll("\\.ureport\\.xml",""));
                baseExportTemp.setPrefix(getPrefix());
                baseExportTemp.setTempFileName(file);
                baseExportTemp.setCreateTime(new Date());
                baseExportTempMapper.insertBaseExportTemp(baseExportTemp);
            }
        }catch(Exception ex){
            throw new ReportException(ex);
        }finally{
            if(outStream!=null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
