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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.reportStatistics.service.IVehicleFilePrintService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.vo.HotCompanySafetyManagerVo;
import com.hotwj.platform.resourceManagement.companySafetyManager.service.IHotCompanySafetyManagerService;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.service.IHotVehicleService;
import com.hotwj.platform.securityManagement.accidentArchive.domain.bo.HotAccidentArchiveBo;
import com.hotwj.platform.securityManagement.accidentArchive.domain.vo.HotAccidentArchiveVo;
import com.hotwj.platform.securityManagement.accidentArchive.service.IHotAccidentArchiveService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.service.OssService;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 交通事故记录数据提供者
 *
 * @author shihongwei
 */
@Component
@RequiredArgsConstructor
public class VehicleTrafficAccidentRecordProvider implements IReportDataProvider {

    private final IHotAccidentArchiveService accidentArchiveService;
    private final IHotVehicleService vehicleService;
    private final IHotCompanySafetyManagerService companySafetyManagerService;
    private final DictService dictService;
    private final OssService ossService;

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

    @Override
    public String getReportType() {
        return IVehicleFilePrintService.TYPE_VEHICLE_ACCIDENT_RECORD;
    }

    @Override
    public String getReportTitle() {
        return "交通事故记录";
    }

    @Override
    public Map<String, Object> prepareData(Map<String, Object> params) {
        Long vehicleId = MapUtil.getLong(params, "vehicleId");
        if (vehicleId == null) {
            return new HashMap<>();
        }

        String beginTime = MapUtil.getStr(params, "beginTime");
        String endTime = MapUtil.getStr(params, "endTime");
        Integer printEmptyData = MapUtil.getInt(params, "printEmptyData");
        boolean allowEmpty = printEmptyData == null || printEmptyData == 1;
        Date startDate = null;
        Date endDate = null;
        if (StrUtil.isNotBlank(beginTime)) {
            startDate = DateUtil.beginOfDay(DateUtil.parse(beginTime, "yyyy-MM-dd"));
        }
        if (StrUtil.isNotBlank(endTime)) {
            endDate = DateUtil.endOfDay(DateUtil.parse(endTime, "yyyy-MM-dd"));
        }

        HotAccidentArchiveBo bo = new HotAccidentArchiveBo();
        bo.setVehicleId(vehicleId);
        bo.setIsDeleted(0L);
        // 获取事故记录
        List<HotAccidentArchiveVo> list = accidentArchiveService.queryList(bo);

        // 单独查询车辆信息
        HotVehicleVo vehicle = vehicleService.queryById(vehicleId);

        // 如果没有记录，创建一个空对象，填充车辆信息，确保能渲染出一页
        if (CollUtil.isNotEmpty(list) && (startDate != null || endDate != null)) {
            Date finalStartDate = startDate;
            Date finalEndDate = endDate;
            list = list.stream()
                    .filter(item -> {
                        Date recordDate = item.getAccidentTime();
                        if (recordDate == null) {
                            return false;
                        }
                        if (finalStartDate != null && recordDate.before(finalStartDate)) {
                            return false;
                        }
                        return finalEndDate == null || !recordDate.after(finalEndDate);
                    })
                    .toList();
        }

        if (CollUtil.isEmpty(list)) {
            if (!allowEmpty) {
                return null;
            }
            list = new ArrayList<>();
            HotAccidentArchiveVo emptyRecord = new HotAccidentArchiveVo();
            // 填充车辆信息
            if (vehicle != null) {
                emptyRecord.setPlateNumber(vehicle.getPlateNumber());
                emptyRecord.setVehicleId(vehicleId);
            }
            list.add(emptyRecord);
        } else {
            list = new ArrayList<>(list);
            Map<String, String> reporterNameCache = new HashMap<>();
            // 按照发生时间 accidentTime 倒序
            list.sort((o1, o2) -> {
                if (o1.getAccidentTime() == null && o2.getAccidentTime() == null) {
                    return 0;
                }
                if (o1.getAccidentTime() == null) {
                    return 1;
                }
                if (o2.getAccidentTime() == null) {
                    return -1;
                }
                return o2.getAccidentTime().compareTo(o1.getAccidentTime());
            });

            // 处理图片
            for (HotAccidentArchiveVo vo : list) {
                List<String> images = splitUrls(ossService.selectUrlByIds(vo.getResponsibilityCertificateUrls()));
                vo.setImages(images);
                vo.setAccidentPattern(resolveAccidentCategory(vo));
                vo.setReporterName(resolveReporterName(vo.getReporterName(), reporterNameCache));
            }
        }

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

        return ctx;
    }

    private List<String> splitUrls(String urls) {
        if (StrUtil.isBlank(urls)) {
            return new ArrayList<>();
        }
        List<String> list = new ArrayList<>();
        String[] parts = urls.split(",");
        for (String p : parts) {
            String v = p.trim();
            if (StrUtil.isNotBlank(v)) {
                list.add(v);
            }
        }
        return list;
    }

    private String resolveAccidentCategory(HotAccidentArchiveVo vo) {
        if (StrUtil.isNotBlank(vo.getAccidentForms())) {
            List<String> labels = Arrays.stream(vo.getAccidentForms().split(","))
                    .map(String::trim)
                    .filter(StrUtil::isNotBlank)
                    .map(code -> dictService.getDictLabel("hot_accident_archive_form", code))
                    .map(label -> StrUtil.blankToDefault(label, ""))
                    .filter(StrUtil::isNotBlank)
                    .toList();
            if (CollUtil.isNotEmpty(labels)) {
                return StrUtil.join("，", labels);
            }
        }
        return vo.getAccidentPattern();
    }

    private String resolveReporterName(String reporterName, Map<String, String> cache) {
        if (StrUtil.isBlank(reporterName)) {
            return reporterName;
        }
        String cached = cache.get(reporterName);
        if (StrUtil.isNotBlank(cached)) {
            return cached;
        }
        if (!NumberUtil.isLong(reporterName)) {
            cache.put(reporterName, reporterName);
            return reporterName;
        }
        HotCompanySafetyManagerVo manager = companySafetyManagerService.queryById(Long.valueOf(reporterName));
        if (manager != null && StrUtil.isNotBlank(manager.getName())) {
            cache.put(reporterName, manager.getName());
            return manager.getName();
        }
        cache.put(reporterName, reporterName);
        return reporterName;
    }
}
