package com.hotwj.platform.reportStatistics.provider.security;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hotwj.platform.common.mapper.PublicMapper;
import com.hotwj.platform.common.utils.FileTextExtractor;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.securityManagement.training.domain.vo.HotTrainingVo;
import com.hotwj.platform.securityManagement.training.service.IHotTrainingService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

@Component
@RequiredArgsConstructor
public class OfflineTrainingProvider implements IReportDataProvider {

    private final IHotTrainingService trainingService;
    private final PublicMapper publicMapper;
    private final OssService ossService;
    private final HotDriverMapper driverMapper;

    @Override
    public String getTemplateCode() {
        return "templates/securityManage/offlineTraining.html.vm";
    }

    @Override
    public String getReportTitle() {
        return "线下培训记录表";
    }

    @Override
    public Map<String, Object> prepareData(Map<String, Object> params) {
        Long trainingId = MapUtil.getLong(params, "trainingId");
        Map<String, Object> ctx = new HashMap<>();
        if (trainingId == null) {
            return ctx;
        }
        HotTrainingVo training = trainingService.queryById(trainingId);
        if (training == null) {
            return ctx;
        }
        // 处理数据
        Map<String, Object> tMap = new HashMap<>();
        tMap.put("trainingSubject", StringUtils.blankToDefault(training.getPlanName(), ""));
        tMap.put("startTime", training.getStartTime());
        tMap.put("endTime", training.getEndTime());
        tMap.put("location", StringUtils.blankToDefault(training.getTrainingLocation(), "线下"));
        tMap.put("hostName", StringUtils.blankToDefault(training.getTeacherName(), ""));
        tMap.put("recorderName", StringUtils.blankToDefault(training.getRecorderName(), ""));

        // 培训人员
        String participantNames = "";
        String pIds = training.getParticipantIds();
        if (StringUtils.isNotBlank(pIds)) {
            List<String> ids = Arrays.stream(pIds.split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .toList();
            if (!ids.isEmpty()) {
                try {
                    String names = publicMapper.selectAttendeeNamesByIds(ids);
                    if (StringUtils.isNotBlank(names)) {
                        participantNames = names;
                    }
                } catch (Exception ignored) {
                }
            }
        }
        tMap.put("participantNames", StringUtils.blankToDefault(participantNames, ""));

        // 培训内容 (从 files 获取附件内容，支持doc/docx/xls/xlsx/ppt/pptx/txt/pdf)
        StringBuilder trainingContentBuilder = new StringBuilder();
        String filesJson = training.getFiles();
        if (StringUtils.isNotBlank(filesJson)) {
            List<String> fileUrls = new ArrayList<>();
            try {
                if (JSONUtil.isTypeJSON(filesJson)) {
                    JSONObject json = JSONUtil.parseObj(filesJson);
                    if (!json.isEmpty()) {
                        for (Object val : json.values()) {
                            String url = resolveMaybeOssUrl(String.valueOf(val));
                            if (StringUtils.isNotBlank(url)) {
                                fileUrls.add(url);
                            }
                        }
                    }
                } else {
                    for (String s : filesJson.split(",")) {
                        String url = resolveMaybeOssUrl(s);
                        if (StringUtils.isNotBlank(url)) {
                            fileUrls.add(url);
                        }
                    }
                }
            } catch (Exception e) {
                // ignore
            }

            for (String url : fileUrls) {
                try {
                    String ext = "";
                    if (url.contains("?")) {
                        String path = url.substring(0, url.indexOf("?"));
                        ext = StringUtils.substringAfterLast(path, ".");
                    } else {
                        ext = StringUtils.substringAfterLast(url, ".");
                    }

                    if (StringUtils.isNotBlank(ext)) {
                        byte[] fileBytes = HttpUtil.downloadBytes(url);
                        if (fileBytes != null && fileBytes.length > 0) {
                            try (InputStream is = new ByteArrayInputStream(fileBytes)) {
                                String text = FileTextExtractor.extractText(is, ext);
                                if (StringUtils.isNotBlank(text)) {
                                    if (trainingContentBuilder.length() > 0) {
                                        trainingContentBuilder.append("\n");
                                    }
                                    trainingContentBuilder.append(text);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    // ignore individual file errors
                }
            }
        }
        tMap.put("trainingContent", StringUtils.blankToDefault(trainingContentBuilder.toString(), ""));

        ctx.put("training", tMap);

        // 图片
        List<String> imgUrls = new ArrayList<>();
        if (StringUtils.isNotBlank(training.getPhotos())) {
            String photoJson = training.getPhotos();
            try {
                if (JSONUtil.isTypeJSON(photoJson)) {
                    JSONObject json = JSONUtil.parseObj(photoJson);
                    if (!json.isEmpty()) {
                        for (Object val : json.values()) {
                            String url = resolveMaybeOssUrl(String.valueOf(val));
                            if (StringUtils.isNotBlank(url)) {
                                imgUrls.add(url);
                            }
                        }
                    }
                } else {
                    for (String s : photoJson.split(",")) {
                        String url = resolveMaybeOssUrl(s);
                        if (StringUtils.isNotBlank(url)) {
                            imgUrls.add(url);
                        }
                    }
                }
            } catch (Exception e) {
                // ignore
            }
        }
        ctx.put("imgUrls", imgUrls);

        return ctx;
    }

    private String resolveMaybeOssUrl(String ossIdOrUrl) {
        if (StringUtils.isBlank(ossIdOrUrl)) {
            return null;
        }
        try {
            Long ossId = Long.parseLong(ossIdOrUrl);
            return ossService.selectUrlByIds(String.valueOf(ossId));
        } catch (NumberFormatException e) {
            return ossIdOrUrl;
        }
    }
}
