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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.hotwj.platform.common.mapper.PublicMapper;
import com.hotwj.platform.common.vo.AddressVo;
import com.hotwj.platform.config.course.service.IHotCourseService;
import com.hotwj.platform.driverManagement.driver.domain.vo.HotDriverVo;
import com.hotwj.platform.driverManagement.driver.service.IHotDriverService;
import com.hotwj.platform.reportStatistics.domain.vo.PreJobTrainingLedgerVo;
import com.hotwj.platform.reportStatistics.domain.vo.security.PreJobTrainingDetail;
import com.hotwj.platform.reportStatistics.mapper.LedgerReportMapper;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import com.hotwj.platform.securityManagement.training.service.IHotTrainingService;
import com.hotwj.platform.securityManagement.trainingAnswer.domain.bo.TrainingAnswerRecordBo;
import com.hotwj.platform.securityManagement.trainingAnswer.domain.vo.HotTrainingAnswerRecordVo;
import com.hotwj.platform.securityManagement.trainingAnswer.service.IHotTrainingAnswerRecordService;
import com.hotwj.platform.securityManagement.trainingAudit.domain.bo.HotTrainingAuditBo;
import com.hotwj.platform.securityManagement.trainingAudit.domain.vo.HotTrainingAuditVo;
import com.hotwj.platform.securityManagement.trainingAudit.service.IHotTrainingAuditService;
import com.hotwj.platform.securityManagement.trainingCourseConfig.service.IHotTrainingCourseConfigService;
import com.hotwj.platform.securityManagement.trainingCourseRecord.domain.bo.HotTrainingCourseRecordBo;
import com.hotwj.platform.securityManagement.trainingCourseRecord.domain.vo.HotTrainingCourseRecordVo;
import com.hotwj.platform.securityManagement.trainingCourseRecord.service.IHotTrainingCourseRecordService;
import com.hotwj.platform.securityManagement.trainingParticipant.service.IHotTrainingParticipantService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 从业人员岗前培训考核卡 Provider
 */
@Component
@RequiredArgsConstructor
public class PreJobTrainingProvider implements IReportDataProvider {


    private final DictService dictService;
    private final IHotTrainingCourseRecordService trainingCourseRecordService;
    private final IHotTrainingAuditService trainingAuditService;
    private final OssService ossService;
    private final IHotDriverService driverService;
    private final LedgerReportMapper ledgerReportMapper;

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

    @Override
    public boolean isLandscape() {
        return true;
    }

    @Override
    public String getReportTitle() {
        return "从业人员岗前培训考核卡";
    }

    @Override
    public String getCoverProviderType() {
        return "PREJOB_TRAINING_COVER";
    }

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

        Map<String, Object> ctx = new HashMap<>();

        // 如果 driverId 缺失，检查是否传入了 "driver" 对象（为了兼容旧逻辑或内部调用）
        HotDriverVo driver = null;
        if (StringUtils.isNotBlank(driverId)) {
            driver = driverService.queryById(driverId);
        }

        if (driver != null) {
            Long companyId = driver.getCompanyId();
            // 翻译字典值
            driver.setGender(dictService.getDictLabel("sys_user_sex", driver.getGender()));
            driver.setEducation(dictService.getDictLabel("hot_academic", driver.getEducation()));

            List<PreJobTrainingDetail> details = new ArrayList<>();

            // 查询该驾驶员的所有岗前培训ID
            List<Long> trainingIds = ledgerReportMapper.selectDriverPreJobTrainingIds(companyId, driver.getId());

            if (CollUtil.isNotEmpty(trainingIds)) {
                for (Long trainingId : trainingIds) {
                    PreJobTrainingDetail detail = buildDetail(companyId, driver, trainingId);
                    details.add(detail);
                }
            } else {
                // 如果没有培训记录，创建一个空的详情对象以显示基本信息
                PreJobTrainingDetail detail = buildDetail(companyId, driver, null);
                details.add(detail);
            }

            ctx.put("details", details);
        }

        return ctx;
    }

    private PreJobTrainingDetail buildDetail(Long companyId, HotDriverVo driver, Long trainingId) {
        PreJobTrainingDetail detail = new PreJobTrainingDetail();
        detail.setDriverId(driver.getId());
        detail.setDriverName(driver.getName());
        detail.setGender(driver.getGender()); // Already translated
        detail.setIdCardNo(driver.getIdCardNo());
        detail.setEntryDateLabel(driver.getEntryDate() != null ? DateUtil.format(driver.getEntryDate(), "yyyy-MM-dd") : "");
        detail.setBirthDate(driver.getBirthDate() != null ? DateUtil.format(driver.getBirthDate(), "yyyy-MM-dd") : "");
        detail.setEducation(driver.getEducation()); // Already translated
        detail.setStartWorkDate(driver.getStartWorkDate() != null ? DateUtil.format(driver.getStartWorkDate(), "yyyy-MM-dd") : "");
        detail.setCurrentAddress(StringUtils.blankToDefault(driver.getCurrentAddress(), ""));

        // 查询指定培训ID的明细行
        // 如果 trainingId 为空（无记录），返回空列表
        List<PreJobTrainingDetail.PreJobTrainingRow> rows = new ArrayList<>();
        if (trainingId != null) {
            rows = ledgerReportMapper.selectDriverPreJobTrainingRows(companyId, driver.getId(), trainingId);
        }
        
        // 计算总分
        long totalScore = 0L;
        if (CollUtil.isNotEmpty(rows)) {
            for (PreJobTrainingDetail.PreJobTrainingRow row : rows) {
                if (StringUtils.isNotBlank(row.getExamScore())) {
                    try {
                        totalScore += Double.parseDouble(row.getExamScore());
                    } catch (NumberFormatException ignored) {}
                }
            }
            detail.setTotalScore(String.valueOf(totalScore));
        } else {
            detail.setTotalScore("");
        }

        int minRows = 8;
        while (rows.size() < minRows) {
            rows.add(new PreJobTrainingDetail.PreJobTrainingRow());
        }
        detail.setRows(rows);

        if (trainingId != null) {
            detail.setDriverSignImgUrl(resolveDriverSignatureUrl(companyId, trainingId, driver.getId()));
            detail.setAuditorSignImgUrl(resolveAuditorSignImgUrl(companyId, trainingId, driver.getId()));
        }

        return detail;
    }

    private String resolveDriverSignatureUrl(Long companyId, Long trainingId, String driverId) {
        if (companyId == null || trainingId == null || driverId == null) {
            return null;
        }
        HotTrainingCourseRecordBo bo = new HotTrainingCourseRecordBo();
        bo.setCompanyId(companyId);
        bo.setTrainingId(trainingId);
        bo.setUserId(driverId);
        bo.setIsDeleted(0L);
        List<HotTrainingCourseRecordVo> list = trainingCourseRecordService.queryList(bo);
        if (list == null || list.isEmpty()) {
            return null;
        }
        Long ossId = null;
        // Try to find a record with signature
        for (HotTrainingCourseRecordVo vo : list) {
            if (vo != null && vo.getSignatureOssId() != null) {
                ossId = vo.getSignatureOssId();
                break; // Use the first one found
            }
        }
        if (ossId == null) {
            return null;
        }
        return resolveMaybeOssUrl(String.valueOf(ossId));
    }

    private String resolveAuditorSignImgUrl(Long companyId, Long trainingId, String driverId) {
        if (companyId == null || trainingId == null || driverId == null) {
            return null;
        }
        HotTrainingAuditBo bo = new HotTrainingAuditBo();
        bo.setCompanyId(companyId);
        bo.setTrainingId(trainingId);
        bo.setUserId(driverId);
        bo.setIsPass(1L);
        bo.setIsDeleted(0L);
        List<HotTrainingAuditVo> list = trainingAuditService.queryList(bo);
        if (list == null || list.isEmpty()) {
            return null;
        }
        String url = null;
        for (HotTrainingAuditVo vo : list) {
            if (vo != null && vo.getSignImgUrl() != null) {
                url = vo.getSignImgUrl();
                break;
            }
        }
        if (StringUtils.isBlank(url)) {
            return null;
        }
        return resolveMaybeOssUrl(url);
    }

    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;
    }
}
