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.StrUtil;
import com.hotwj.platform.reportStatistics.service.IReportDataProvider;
import com.hotwj.platform.reportStatistics.service.IVehicleFilePrintService;
import com.hotwj.platform.resourceManagement.vehicleClaim.domain.bo.HotVehicleClaimBo;
import com.hotwj.platform.resourceManagement.vehicleClaim.domain.vo.HotVehicleClaimVo;
import com.hotwj.platform.resourceManagement.vehicleClaim.service.IHotVehicleClaimService;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.service.IHotVehicleService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.OssService;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 车辆出险记录数据提供者
 *
 * @author shihongwei
 */
@Component
@RequiredArgsConstructor
public class VehicleClaimRecordProvider implements IReportDataProvider {

    private final IHotVehicleClaimService claimService;
    private final IHotVehicleService vehicleService;
    private final OssService ossService;

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

    @Override
    public String getReportType() {
        return IVehicleFilePrintService.TYPE_CLAIM_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<>();
        }

        HotVehicleVo vehicle = vehicleService.queryById(vehicleId);

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

        HotVehicleClaimBo bo = new HotVehicleClaimBo();
        bo.setVehicleId(String.valueOf(vehicleId));
        bo.setIsDeleted(0L);
        List<HotVehicleClaimVo> list = claimService.queryList(bo);

        if (CollUtil.isNotEmpty(list) && (startDate != null || endDate != null)) {
            Date finalStartDate = startDate;
            Date finalEndDate = endDate;
            list = list.stream()
                    .filter(item -> {
                        Date recordDate = item.getIncidentTime();
                        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<>();
            // 创建一个空对象，确保能渲染出一页
            HotVehicleClaimVo emptyRecord = new HotVehicleClaimVo();
            list.add(emptyRecord);
        } else {
            list = new ArrayList<>(list);
            // 按照登记日期incidentTime降序排列
            list.sort((o1, o2) -> {
                if (o1.getIncidentTime() == null && o2.getIncidentTime() == null) {
                    return 0;
                }
                if (o1.getIncidentTime() == null) {
                    return 1;
                }
                if (o2.getIncidentTime() == null) {
                    return -1;
                }
                return o2.getIncidentTime().compareTo(o1.getIncidentTime());
            });

            // 合并所有记录的图片
            for (HotVehicleClaimVo vo : list) {
                List<String> recordImages = splitUrls(ossService.selectUrlByIds(vo.getImageUrls()));
                vo.setImages(recordImages);
            }
        }

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

        // 放入列表数据
        ctx.put("records", list);

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