package com.brilliance.isc.common.api.trndoc.controller;

import com.brilliance.isc.common.api.trndoc.service.TrndocApiService;
import com.brilliance.isc.common.api.trndoc.vo.TrndocRequest;
import com.brilliance.isc.common.api.trndoc.vo.TrndocResponse;
import com.brilliance.isc.common.context.AppEnv;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.trndoc.service.TrndocService;
import com.brilliance.isc.common.vo.BizAmdInfoVo;
import com.brilliance.isc.common.vo.BizInfoVo;
import com.brilliance.isc.vo.ResponseSet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;

@Api("面函报文服务")
public class AbstractTrndocController<T1 extends BizInfoVo, T2 extends BizAmdInfoVo> {

    @Autowired
    private SettleContext settleContext;

    @Autowired
    private TrndocApiService trndocApiService;

    @Autowired
    private TrndocService trndocService;

    @Autowired
    private AppEnv appEnv;

    @ApiOperation("面函报文试算入口")
    public ResponseSet<TrndocResponse> assertTrndoc( TrndocRequest<T1, T2> trndoc) {
        try {
            settleContext.loadSettleSession(trndoc.getTransName(), trndoc.getUserId(), trndoc.getRec(), trndoc.getPtsList(), trndoc.getSptinr());
            return ResponseSet.simpleSuccess(trndocApiService.calcTrndoc(trndoc));
        } catch (Exception e) {
            throw e;
        } finally {
            SettleContext.removeUserSession();
            trndocService.clearCorTypeList();
        }
    }

    @ApiOperation("面函报文预览功能")
    public ResponseSet<TrndocResponse> showDOCS( Map<String, Object> paramMap) throws IOException {
        //需要在本地目录创建文件夹，路径为D:\rootPath\template，这下面存放的是模板文件
        String base46String = trndocService.showDOCS(paramMap);
        //存在这个文件就将这个文件转化为pdf格式，目前jar包由于是企业版的有水印
        if(paramMap.get("templateName")!=null){
            String fileName = (String)paramMap.get("templateName");
            String filePath = appEnv.getRootPath() + "/file/"+fileName;
            int index = fileName.lastIndexOf(".");
            String targetPath = appEnv.getRootPath() + "/file/" + fileName.substring(0,index)+".pdf";
            trndocService.wordToPdf(filePath,targetPath);
        }
        return ResponseSet.simpleSuccess(base46String);
    }

    @ApiOperation("附件试算入口")
    public ResponseSet<TrndocResponse> assertDoctre( TrndocRequest<T1, T2> trndoc) {
        try {
            settleContext.loadSettleSession(trndoc.getTransName(), trndoc.getUserId(), trndoc.getRec(), trndoc.getPtsList(), trndoc.getSptinr());
            return new ResponseSet<>(trndocApiService.calcDoctre(trndoc));
        } finally {
            SettleContext.removeUserSession();
            trndocService.clearCorTypeList();
        }
    }
}
