package com.hotwj.platform.common.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.hotwj.platform.common.service.ITemplateService;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
import com.hotwj.platform.noticeManagerment.signFileDetail.domain.vo.HotSignFileDetailVo;
import com.hotwj.platform.noticeManagerment.signFileDetail.mapper.HotSignFileDetailMapper;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringSubstitutor;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class TemplateServiceImpl implements ITemplateService {

    private static final DateTimeFormatter SIGN_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

    private final HotSignFileDetailMapper signFileDetailMapper;
    private final ISysCompanyService companyService;
    private final HotCompanySafetyManagerMapper safetyManagerMapper;
    private final HotDriverMapper driverMapper;
    private final OssService ossService;

    @Override
    public String fillTemplate(String templateContent, Map<String, Object> dataMap) {
        if (StrUtil.isBlank(templateContent)) {
            return "";
        }
        Map<String, Object> renderMap = dataMap == null ? new HashMap<>() : dataMap;
        StringSubstitutor substitutor = new StringSubstitutor(renderMap, "{", "}");
        substitutor.setEnableUndefinedVariableException(false);
        String rendered = substitutor.replace(templateContent);
        return rendered.replaceAll("\\{[^{}]+\\}", "");
    }

    @Override
    public Map<String, Object> prepareDataMapForSignDetail(Long detailId) {
        Map<String, Object> dataMap = new HashMap<>();
        HotSignFileDetailVo detail = signFileDetailMapper.selectVoById(detailId);
        if (detail == null) {
            return dataMap;
        }
        String signOssId = detail.getSignOssId();

        if (detail.getCompanyId() != null) {
            SysCompanyVo company = companyService.queryById(detail.getCompanyId());
            if (company != null) {
                dataMap.put("企业名字", StringUtils.defaultString(company.getCompanyName()));
                dataMap.put("信用代码", StringUtils.defaultString(company.getCreditCode()));
                String sealUrl = resolveOssUrl(company.getSealUrl());
                if (StrUtil.isNotBlank(sealUrl)) {
                    dataMap.put("电子公章", buildSealImgTag(sealUrl));
                }
            }
        }
        if (StrUtil.isNotBlank(detail.getStaffId()) && NumberUtil.isLong(detail.getStaffId())) {
            HotCompanySafetyManager manager;
            try {
                manager = safetyManagerMapper.selectById(Long.valueOf(detail.getStaffId()));
            } catch (Exception e) {
                manager = null;
            }
            if (manager != null && manager.getId() != null) {
                dataMap.put("管理员姓名", StringUtils.defaultString(manager.getName()));
                dataMap.put("管理员身份证号码", StringUtils.defaultString(manager.getIdCardNo()));
                dataMap.put("管理员手机号码", StringUtils.defaultString(manager.getPhone()));
                dataMap.put("管理员岗位", StringUtils.defaultString(manager.getJobName()));
                if (StrUtil.isNotBlank(signOssId)) {
                    String signImg = resolveOssUrl(signOssId);
                    dataMap.put("管理员签名", buildSignImgTag(signImg));
                    if (detail.getSignTime() != null) {
                        String signDate = detail.getSignTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(SIGN_DATE_FORMATTER);
                        dataMap.put("管理员签字日期", signDate);
                    }
                }
            }
        } else if (StrUtil.isNotBlank(detail.getStaffId()) && !NumberUtil.isLong(detail.getStaffId())) {
            HotDriver driver = driverMapper.selectById(detail.getStaffId());
            if (driver != null && driver.getId() != null) {
                dataMap.put("驾驶员姓名", StringUtils.defaultString(driver.getName()));
                dataMap.put("驾驶员身份证号码", StringUtils.defaultString(driver.getIdCardNo()));
                dataMap.put("驾驶员手机号码", StringUtils.defaultString(driver.getPhone()));
                dataMap.put("驾驶员从业资格证号码", StringUtils.defaultString(driver.getQualificationNo()));
                dataMap.put("驾驶员驾驶车牌号", StringUtils.defaultString(driver.getPlateNumber()));
                if (StrUtil.isNotBlank(signOssId)) {
                    String signImg = resolveOssUrl(signOssId);
                    dataMap.put("驾驶员签名", buildSignImgTag(signImg));
                    if (detail.getSignTime() != null) {
                        String signDate = detail.getSignTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(SIGN_DATE_FORMATTER);
                        dataMap.put("驾驶员签字日期", signDate);
                    }
                }
            }
        }


        return dataMap;
    }

    private String resolveOssUrl(String source) {
        if (StrUtil.isBlank(source)) {
            return null;
        }
        if (source.startsWith("http://") || source.startsWith("https://")) {
            return source;
        }
        String urls = ossService.selectUrlByIds(source);
        if (StrUtil.isBlank(urls)) {
            return source;
        }
        if (urls.contains(",")) {
            for (String part : urls.split(",")) {
                if (StrUtil.isNotBlank(part)) {
                    return part.trim();
                }
            }
        }
        return urls;
    }

    private String buildSignImgTag(String url) {
        return "<img src=\"" + url + "\" style=\"display:inline-block !important; max-height: 66px; max-width: 160px; vertical-align: middle; margin: 0 2px;\" />";
    }

    private String buildSealImgTag(String url) {
        return "<span style=\"display:inline-block; position:relative; width:0; height:0; line-height:0; vertical-align:middle; overflow:visible;\"><img src=\"" + url + "\" style=\"position:absolute; left:-35px; top:-60px; max-height:120px; max-width:220px; z-index:9; pointer-events:none;\" /></span>";
    }
}
