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.driverManagement.driver.domain.vo.HotDriverVo;
import com.hotwj.platform.driverManagement.driver.service.IHotDriverService;
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.resourceManagement.vehicleRepair.domain.bo.HotVehicleRepairBo;
import com.hotwj.platform.resourceManagement.vehicleRepair.domain.vo.HotVehicleRepairVo;
import com.hotwj.platform.resourceManagement.vehicleRepair.service.IHotVehicleRepairService;
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 VehicleRepairRecordProvider implements IReportDataProvider {

    private final IHotVehicleRepairService repairService;
    private final IHotVehicleService vehicleService;
    private final IHotCompanySafetyManagerService companySafetyManagerService;
    private final IHotDriverService driverService;
    private final DictService dictService;
    private final OssService ossService;

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

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

        HotVehicleRepairBo bo = new HotVehicleRepairBo();
        bo.setVehicleId(String.valueOf(vehicleId));
        bo.setIsDeleted(0L);
        // 获取维修记录，这里取最近一次
        List<HotVehicleRepairVo> list = repairService.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.getFinishDate();
                        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<>();
            HotVehicleRepairVo emptyRecord = new HotVehicleRepairVo();
            emptyRecord.setVehicle(vehicle);
            if (vehicle != null) {
                emptyRecord.setPlateNumber(vehicle.getPlateNumber());
            }
            list.add(emptyRecord);
        } else {
            list = new ArrayList<>(list);
            Map<String, String> recorderNameCache = new HashMap<>();
            // 按照完成日期 finishDate 倒序
            list.sort((o1, o2) -> {
                if (o1.getFinishDate() == null && o2.getFinishDate() == null) {
                    return 0;
                }
                if (o1.getFinishDate() == null) {
                    return 1;
                }
                if (o2.getFinishDate() == null) {
                    return -1;
                }
                return o2.getFinishDate().compareTo(o1.getFinishDate());
            });

            // 处理图片并设置车辆信息
            for (HotVehicleRepairVo vo : list) {
                List<String> images = splitUrls(ossService.selectUrlByIds(vo.getProofImageUrls()));
                vo.setImages(images);
                vo.setVehicle(vehicle);
                vo.setRepairCategory(resolveRepairCategory(vo.getRepairCategory()));
                vo.setRecorder(resolveRecorderName(vo.getRecorder(), recorderNameCache));
            }
        }

        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 resolveRepairCategory(String repairCategory) {
        if (StrUtil.isBlank(repairCategory)) {
            return repairCategory;
        }
        List<String> labels = Arrays.stream(repairCategory.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(code -> dictService.getDictLabel("hot_vehicle_repair", code))
                .map(label -> StrUtil.blankToDefault(label, ""))
                .filter(StrUtil::isNotBlank)
                .toList();
        if (CollUtil.isNotEmpty(labels)) {
            return StrUtil.join("，", labels);
        }
        return repairCategory;
    }

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