package com.yd.oss.api.service.impl;

import com.aliyun.oss.OSS;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.oss.api.service.ApiPdfService;
import com.yd.oss.feign.request.ApiGeneratePdfRequest;
import com.yd.oss.feign.response.ApiGeneratePdfResponse;
import com.yd.oss.service.config.OssClientFactory;
import com.yd.oss.service.model.OssProvider;
import com.yd.oss.service.service.IOssProviderService;
import com.yd.oss.service.service.PdfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Slf4j
@Service
public class ApiPdfServiceImpl implements ApiPdfService {

    @Autowired
    private PdfService pdfService;

    @Autowired
    private IOssProviderService ossProviderService;

    @Autowired
    private OssClientFactory ossClientFactory;

    /**
     * 根据文件模板填充数据生成PDF
     * @param request
     * @return
     */
    @Override
    public Result<ApiGeneratePdfResponse> generatePDF(ApiGeneratePdfRequest request) {
        ApiGeneratePdfResponse response = new ApiGeneratePdfResponse();
        // 根据项目ID获取OSS提供商
        OssProvider provider = ossProviderService.getProviderByProjectId(request.getProjectBizId());
        if (provider == null) {
            throw new BusinessException("未找到项目对应的OSS提供商，projectBizId=" + request.getProjectBizId());
        }
        OSS ossClient = null;
        try {
            //根据提供商创建OSS
            ossClient = ossClientFactory.createOssClient(provider);
            String url = pdfService.generatePDF(request.getDataObject(),
                    request.getObjectId(),
                    request.getTemplateType(),
                    request.getCustomFileName(),
                    provider,ossClient);
            response.setUrl(url);
            return Result.success(response);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("生成PDF异常");
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
