package com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.strategy;

import cn.hutool.core.date.StopWatch;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.module.common.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionApplication;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionApplicationEquip;
import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.factory.support.SupportableDocGenerator;
import com.yeejoin.amos.boot.module.jyjc.biz.file.inspectapp.strategy.common.InspectAppDocCmService;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcInspectionApplicationEquipServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcInspectionApplicationServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.util.WordTemplateUtils;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgUseInfoMapper;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class GenericDocGeneratorStrategy implements SupportableDocGenerator {

    private final JyjcInspectionApplicationServiceImpl jyjcInspectionApplicationService;

    private final JyjcInspectionApplicationEquipServiceImpl jyjcInspectionApplicationEquipService;

    private final InspectAppDocCmService appDocCmService;

    private final IdxBizJgUseInfoMapper idxBizJgUseInfoMapper;
    
    private final AmosRequestContext amosRequestContext;

    @Override
    public boolean support(String equList, String equCategory, String equDefine) {
        return !EquipmentClassifityEnum.YLGD.getCode().equals(equList);
    }

    @Override
    public String generate(String appSeq) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("1.组织数据");
        Map<String, Object> params = appDocCmService.getBaseInFo(appSeq);
        JyjcInspectionApplication inspectionApplication = jyjcInspectionApplicationService.getBaseMapper().selectById(appSeq);
        params.put("numberOfEquip", inspectionApplication.getNumberOfEquip());
        setEquipExcelData(inspectionApplication, params);
        stopWatch.stop();
        stopWatch.start("2.文件生成及上传");
        this.setRequestContext();
        String path = this.generatePdfAndUpload(params);
        stopWatch.stop();
        log.info("生成台套气瓶申请表耗时：{}", stopWatch.prettyPrint(TimeUnit.SECONDS));
        return path;
    }

    private void setRequestContext() {
        RequestContext.setProduct(amosRequestContext.getProduct());
        RequestContext.setAppKey(amosRequestContext.getAppKey());
        RequestContext.setToken(amosRequestContext.getToken());
    }

    private void setEquipExcelData(JyjcInspectionApplication inspectionApplication, Map<String, Object> params) {
        List<Map<String, Object>> equips = this.buildEquipsBatch(inspectionApplication.getSequenceNbr());
        params.put("equips", equips);
    }

    private String generatePdfAndUpload(Map<String, Object> formData) {
        String wordPath = "inspect-app-generic.ftl";
        String fileName = "检验检测报检申请受理单";
        File pdfFile = null;
        try {
            // 填充模板,  word转pdf
            pdfFile = WordTemplateUtils.wordToPdf(fileName, wordPath, formData);
            // 上传文档到文件服务器
            return WordTemplateUtils.uploadFile(pdfFile, "/tzs/jyjc/inspectApp");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (pdfFile != null) {
                    Files.deleteIfExists(pdfFile.toPath());
                }
            } catch (Exception e) {
                log.error("文件找不到，删除失败：{}", e.getMessage());
            }
        }
    }

    private List<Map<String, Object>> buildEquipsBatch(Long sequenceNbr) {
        List<JyjcInspectionApplicationEquip> equips = jyjcInspectionApplicationEquipService.list(new LambdaQueryWrapper<JyjcInspectionApplicationEquip>()
                .eq(JyjcInspectionApplicationEquip::getApplicationSeq, sequenceNbr)
                .select(BaseEntity::getSequenceNbr, JyjcInspectionApplicationEquip::getEquipUnicode));
        List<String> records = equips.stream().map(JyjcInspectionApplicationEquip::getEquipUnicode).collect(Collectors.toList());
        return idxBizJgUseInfoMapper.queryBaseInfoByIds(records);
    }
}
