package com.chushang.inspection.ins;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.exception.utils.AssertUtil;
import com.chushang.common.core.web.Result;
import com.chushang.oss.feign.RemoteOssService;
import com.deepoove.poi.XWPFTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

/**
 * 模板相关操作
 * @auther: zhao
 * @date: 2024/7/1 11:50
 */
@Slf4j
@Service
public class TemplateService {

    @Resource
    RemoteOssService remoteOssService;

    public void computeWord(String fileName, String templateFid, Map<String, Object> data){
        XWPFTemplate template = null;
        // 如果为null 时, 获取 本地
        if (null == templateFid){
            try (InputStream stream = ResourceUtil.getStream("template" + File.separator + "default.docx")) {
                template = XWPFTemplate.compile(stream);
                template.render(data);
                FileUtil.touch(fileName);
                template.writeToFile(fileName);
            } catch (Exception e) {
                log.error("【{}】模版替换失败", fileName, e);
            } finally {
                IoUtil.close(template);
            }
        }else {
            Result<byte[]> result = remoteOssService.getFile(templateFid, SecurityConstants.INNER);
            if (result.isSuccess() && null != result.getData()){
                try (InputStream stream = new ByteArrayInputStream(result.getData())) {
                    template = XWPFTemplate.compile(stream);
                    template.render(data);
                    FileUtil.touch(fileName);
                    template.writeToFile(fileName);
                } catch (Exception e) {
                    log.error("【{}】模版替换失败", fileName, e);
                } finally {
                    IoUtil.close(template);
                }
            }else {
                AssertUtil.invalidate(true, "获取模板文件失败, 失败原因: " + result.getMsg());
            }
        }
    }
}
