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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hotwj.platform.common.mapper.PublicMapper;
import com.hotwj.platform.common.vo.AddressVo;
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.hiddenDangerInspection.domain.vo.HotHiddenDangerInspectionVo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.service.IHotHiddenDangerInspectionService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@RequiredArgsConstructor
public class SafetyFireHazardInspectionProvider implements IReportDataProvider {

    private final ISysCompanyService sysCompanyService;
    private final PublicMapper publicMapper;
    private final IHotHiddenDangerInspectionService hiddenDangerInspectionService;
    private final OssService ossService;

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

    @Override
    public String getReportTitle() {
        return "安全生产（消防）隐患排查整改记录";
    }

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

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

        SysCompanyVo company = sysCompanyService.queryById(companyId);
        String companyName = "";
        String regionName = "";
        if (company != null) {
            companyName = StringUtils.blankToDefault(company.getCompanyName(), "");
            if (StringUtils.isNotBlank(company.getRegionCode())) {
                AddressVo addressVo = publicMapper.selectAddressByCode(company.getRegionCode());
                if (addressVo != null) {
                    regionName = addressVo.getLabel();
                }
            }
        }
        ctx.put("companyName", companyName);

        if ("cover".equals(mode)) {
            ctx.put("regionName", regionName);
            ctx.put("printYear", DateUtil.format(new Date(), "yyyy"));
        } else if ("detail".equals(mode)) {
            HotHiddenDangerInspectionVo inspection = (HotHiddenDangerInspectionVo) params.get("inspection");
            if (inspection == null) {
                Long inspectionId = MapUtil.getLong(params, "inspectionId");
                if (inspectionId != null) {
                    inspection = hiddenDangerInspectionService.queryById(inspectionId);
                }
            }
            if (inspection != null) {
                ctx.put("inspection", inspection);
                ctx.put("checkContentLabel", buildInspectionContentLabel(inspection.getCheckContentJson()));
                ctx.put("checkerSignUrl", resolveMaybeOssUrl(inspection.getSignImgUrl()));
                ctx.put("approverSignUrl", resolveMaybeOssUrl(inspection.getApproverSignImgUrl()));
            }
        } else if ("photo".equals(mode)) {
            HotHiddenDangerInspectionVo inspection = (HotHiddenDangerInspectionVo) params.get("inspection");
            if (inspection == null) {
                Long inspectionId = MapUtil.getLong(params, "inspectionId");
                if (inspectionId != null) {
                    inspection = hiddenDangerInspectionService.queryById(inspectionId);
                }
            }
            if (inspection != null) {
                ctx.put("inspection", inspection);
                List<String> photos = resolveInspectionImages(inspection.getAttachmentUrl());
                ctx.put("photos", photos);
            }
        }

        return ctx;
    }

    private String buildInspectionContentLabel(String json) {
        List<Map<String, Object>> items = parseInspectionContent(json);
        if (items.isEmpty()) {
            return StringUtils.blankToDefault(json, "");
        }
        StringBuilder sb = new StringBuilder();
        int i = 1;
        for (Map<String, Object> item : items) {
            if (item == null) {
                continue;
            }
            String content = String.valueOf(item.getOrDefault("content", ""));
            String valueText = String.valueOf(item.getOrDefault("valueText", ""));
            if (StringUtils.isBlank(content) && StringUtils.isBlank(valueText)) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append("<br/>");
            }
            sb.append(i).append("、").append(content);
            if (StringUtils.isNotBlank(valueText)) {
                sb.append("（").append(valueText).append("）");
            }
            i++;
        }
        return sb.toString();
    }

    private List<Map<String, Object>> parseInspectionContent(String json) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (StringUtils.isBlank(json)) {
            return result;
        }
        try {
            List<Map<String, Object>> list = JsonUtils.parseObject(
                    json,
                    new TypeReference<List<Map<String, Object>>>() {
                    }
            );
            if (list == null) {
                return result;
            }
            for (Map<String, Object> item : list) {
                if (item == null) {
                    continue;
                }
                Object content = item.get("content");
                String contentText = content == null ? "" : String.valueOf(content);
                Object normal = item.get("normalText");
                Object abnormal = item.get("abnormalText");
                Object res = item.get("result");
                String rv = res == null ? "" : String.valueOf(res);
                String valueText;
                if ("1".equals(rv)) {
                    valueText = normal == null ? "" : String.valueOf(normal);
                } else if ("0".equals(rv)) {
                    valueText = abnormal == null ? "" : String.valueOf(abnormal);
                } else {
                    valueText = normal == null ? "" : String.valueOf(normal);
                }
                item.put("content", contentText);
                item.put("valueText", valueText);
                result.add(item);
            }
        } catch (Exception e) {
            return result;
        }
        return result;
    }

    private List<String> resolveInspectionImages(String attachmentUrl) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(attachmentUrl)) {
            return result;
        }
        String urls = attachmentUrl;
        if (!(attachmentUrl.contains("http://") || attachmentUrl.contains("https://"))) {
            urls = ossService.selectUrlByIds(attachmentUrl);
        }
        return splitUrls(urls);
    }

    private List<String> splitUrls(String urls) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(urls)) {
            return result;
        }
        for (String s : urls.split(",")) {
            String t = s == null ? "" : s.trim();
            if (!t.isEmpty()) {
                result.add(t);
            }
        }
        return result;
    }

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