package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.api.entity.JgCertificateReplenish;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgCertificateReplenishMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgCertificateReplenishService;
import com.yeejoin.amos.boot.module.jg.biz.utils.FileExporter;
import lombok.RequiredArgsConstructor;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 使用登记表补证服务实现类
 *
 * @author system_generator
 * @date 2025-03-19
 */
@Service
@RequiredArgsConstructor
public class JgCertificateReplenishServiceImpl extends BaseService<JgCertificateReplenish, JgCertificateReplenish, JgCertificateReplenishMapper> implements IJgCertificateReplenishService {
    private final CommonServiceImpl commonService;

    /**
     * 分页查询
     */
    public Page<JgCertificateReplenish> queryForJgCertificateReplenishPage(Page<JgCertificateReplenish> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<JgCertificateReplenish> queryForJgCertificateReplenishList() {
        return this.queryForList("", false);
    }

    /**
     * 补证申请表生成
     *
     * @param jsonObject
     * @return
     */
    @Override
    public Map<String, Object> getCertReplenishFormUrl(JSONObject jsonObject) {
        JSONObject formData = this.writeCertReplenishFormData(jsonObject);
        String wordPath = "CertificateReplenish.ftl";
        String fileName = "使用登记证补证申请表_";
        File pdfFile = null;
        try {
            pdfFile = commonService.wordToPdf(fileName, wordPath, formData);
            return MapBuilder.<String, Object>create()
                    .put("certReplenishFormUrl", commonService.uploadFile(pdfFile, "certificateReplenishFiles"))
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert pdfFile != null;
                Files.deleteIfExists(pdfFile.toPath());
            } catch (Exception e) {
                log.error("文件找不到，删除失败：{}", e);
            }
        }
    }

    /**
     * 补证pdf流生成
     *
     * @param jsonObject
     * @param response
     */
    @Override
    public void getCertReplenishFormStream(JSONObject jsonObject, HttpServletResponse response) {
        JSONObject formData = this.writeCertReplenishFormData(jsonObject);
        String wordPath = "CertificateReplenish.ftl";
        String fileName = "使用登记证补证申请表_";
        File pdfFile;
        try {
            pdfFile = commonService.wordToPdf(fileName, wordPath, formData);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            byte[] bytes = CommonServiceImpl.file2byte(pdfFile);
            String docTitle = pdfFile.getName();
            FileExporter.exportFile(FileExporter.FileType.valueOf("pdf"), docTitle, bytes, response);
        } catch (Exception e) {
            log.error("pdf文件转换失败：{}", e);
        } finally {
            try {
                Files.deleteIfExists(pdfFile.toPath());
            } catch (Exception e) {
                log.error("文件找不到，删除失败：{}", e);
            }
        }
    }

    private JSONObject writeCertReplenishFormData(JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        result.put("applyNo", "applyNo");
        result.put("useUnitName", "useUnitName");
        result.put("useUnitAddress", "useUnitAddress");
        result.put("applicationReason", "1");
        result.put("lossDamageTime", "2022-09-09");
        result.put("safetyManagerName", "张三");
        result.put("safetyManagerPhone", "13209090909");
        JSONArray equLists = new JSONArray();
        equLists.fluentAdd(MapBuilder.<String, Object>create()
                                   .put("index", "1")
                                   .put("productName", "产品名称")
                                   .put("equCode", "设备代码")
                                   .put("useRegistrationCode", "使用登记证编号")
                                   .put("factoryNum", "设备编号")
                                   .build())
                .fluentAdd(MapBuilder.<String, Object>create()
                                   .put("index", "2")
                                   .put("productName", "产品名称1")
                                   .put("equCode", "设备代码2")
                                   .put("useRegistrationCode", "使用登记证编号3")
                                   .put("factoryNum", "设备编号4")
                                   .build());
        result.put("equLists", equLists);
        result.put("handler", "handler");
        result.put("applicationDateYear", "2001");
        result.put("applicationDateMonth", "12");
        result.put("applicationDateDay", "12");
        return result;
    }
}