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.vehicleMaintenance.domain.bo.HotVehicleMaintenanceBo;
import com.hotwj.platform.resourceManagement.vehicleMaintenance.domain.vo.HotVehicleMaintenanceVo;
import com.hotwj.platform.resourceManagement.vehicleMaintenance.service.IHotVehicleMaintenanceService;
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 VehicleMaintenanceRecordProvider implements IReportDataProvider {

    private final IHotVehicleMaintenanceService maintenanceService;
    private final IHotVehicleService vehicleService;
    private final OssService ossService;

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

    @Override
    public String getReportType() {
        return IVehicleFilePrintService.TYPE_MAINTENANCE_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 maintenanceStartDate = MapUtil.getStr(params, "maintenanceStartDate");
        String maintenanceEndDate = MapUtil.getStr(params, "maintenanceEndDate");
        Integer printEmptyData = MapUtil.getInt(params, "printEmptyData");
        boolean allowEmpty = printEmptyData == null || printEmptyData == 1;
        Date startDate = null;
        Date endDate = null;
        if (StrUtil.isNotBlank(maintenanceStartDate)) {
            startDate = DateUtil.beginOfDay(DateUtil.parse(maintenanceStartDate, "yyyy-MM-dd"));
        }
        if (StrUtil.isNotBlank(maintenanceEndDate)) {
            endDate = DateUtil.endOfDay(DateUtil.parse(maintenanceEndDate, "yyyy-MM-dd"));
        }

        HotVehicleMaintenanceBo bo = new HotVehicleMaintenanceBo();
        bo.setVehicleId(String.valueOf(vehicleId));
        // 这里可以根据需要过滤最近一次或特定记录，目前假设打印最近一次
        List<HotVehicleMaintenanceVo> list = maintenanceService.queryList(bo);

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

        if (CollUtil.isNotEmpty(list) && (startDate != null || endDate != null)) {
            Date finalStartDate = startDate;
            Date finalEndDate = endDate;
            list = list.stream()
                    .filter(item -> {
                        Date recordDate = item.getFinishTime();
                        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;
            }
            // 如果没有维护记录，构造一个只有车牌号的空记录对象，以便模板显示车牌号
            HotVehicleMaintenanceVo emptyRecord = new HotVehicleMaintenanceVo();
            if (vehicle != null) {
                emptyRecord.setPlateNumber(vehicle.getPlateNumber());
            }
            ctx.put("record", emptyRecord);
            return ctx;
        }

        HotVehicleMaintenanceVo record = list.get(0);

        ctx.put("record", record);

        ctx.put("factoryCertImages", splitUrls(ossService.selectUrlByIds(record.getFactoryCertImageUrls())));
        ctx.put("finalInspectImages", splitUrls(ossService.selectUrlByIds(record.getFinalInspectImageUrls())));
        ctx.put("processInspectImages", splitUrls(ossService.selectUrlByIds(record.getProcessInspectImageUrls())));
        ctx.put("entryInspectImages", splitUrls(ossService.selectUrlByIds(record.getEntryInspectImageUrls())));

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