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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hotwj.platform.common.mapper.PublicMapper;
import com.hotwj.platform.reportStatistics.domain.vo.GovSafetyEducationTrainingDetailVo;
import com.hotwj.platform.reportStatistics.domain.vo.GovSafetyEducationTrainingParticipantVo;
import com.hotwj.platform.reportStatistics.mapper.LedgerReportMapper;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
@RequiredArgsConstructor
public class SafetyEducationTrainingProvider implements IReportDataProvider {

    private final ISysCompanyService sysCompanyService;
    private final PublicMapper publicMapper;
    private final LedgerReportMapper ledgerReportMapper;
    private final OssService ossService;

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

    @Override
    public String getReportTitle() {
        return "安全生产教育培训记录";
    }

    @Override
    public Map<String, Object> prepareData(Map<String, Object> params) {
        String mode = MapUtil.getStr(params, "mode");

        Map<String, Object> ctx = new HashMap<>();
        ctx.put("mode", mode);

        if ("detail".equals(mode) || "signIn".equals(mode)) {
            Long trainingId = MapUtil.getLong(params, "trainingId");
            if (trainingId != null) {
                GovSafetyEducationTrainingDetailVo detail = buildSafetyEducationDetail(trainingId);
                ctx.put("detail", detail);
            }
        }

        return ctx;
    }

    private GovSafetyEducationTrainingDetailVo buildSafetyEducationDetail(Long trainingId) {
        GovSafetyEducationTrainingDetailVo detail = ledgerReportMapper.selectGovSafetyEducationTrainingDetail(trainingId);
        if (detail == null) {
            return null;
        }
        List<GovSafetyEducationTrainingParticipantVo> participants = ledgerReportMapper.selectGovSafetyEducationTrainingParticipants(trainingId);

        // 处理签名和头像 URL
        if (participants != null) {
            for (GovSafetyEducationTrainingParticipantVo p : participants) {
                // 格式化完成时间
                if (p.getCompleteTime() != null) {
                    p.setCompleteTimeLabel(DateUtil.format(p.getCompleteTime(), "yyyy-MM-dd HH:mm"));
                }

                // 处理签名
                if (p.getSignatureOssId() != null) {
                    p.setSignatureUrl(resolveMaybeOssUrl(String.valueOf(p.getSignatureOssId())));
                }

                // 处理学习照片（头像）- 取 JSON 中的最后一个值
                if (StringUtils.isNotBlank(p.getStudyPhotoOssId())) {
                    try {
                        JSONObject json = JSONUtil.parseObj(p.getStudyPhotoOssId());
                        if (!json.isEmpty()) {
                            // 获取最后一个 key 的值
                            // LinkedHashMap 保持插入顺序，但 JSONUtil 解析可能不保证。
                            // 假设 JSON 结构是课程 ID 对应 OSS ID，且我们想要任意一个或者最后一个。
                            // 这里取 values 集合的最后一个元素作为头像
                            Object[] values = json.values().toArray();
                            if (values.length > 0) {
                                String lastOssId = String.valueOf(values[values.length - 1]);
                                p.setAvatarUrl(resolveMaybeOssUrl(lastOssId));
                            }
                        }
                    } catch (Exception e) {
                        // ignore parse error
                    }
                }
            }
        }

        detail.setParticipantList(participants);
        
        List<String> courseNames = ledgerReportMapper.selectGovSafetyEducationTrainingCourseNames(trainingId);
        if (courseNames != null && !courseNames.isEmpty()) {
            String content = IntStream.range(0, courseNames.size())
                    .mapToObj(i -> (i + 1) + "：" + courseNames.get(i))
                    .collect(Collectors.joining("\n"));
            detail.setTrainingContent(content);
        }
        return detail;
    }

    private String resolveMaybeOssUrl(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        String first = value.split(",")[0].trim();
        if (StringUtils.isBlank(first)) {
            return null;
        }
        if (first.startsWith("http")) {
            return first;
        }
        if (first.matches("^\\d+$")) {
            String urls = ossService.selectUrlByIds(first);
            if (StringUtils.isBlank(urls)) {
                return null;
            }
            return urls.split(",")[0].trim();
        }
        return first;
    }
}
