package com.hotwj.platform.resourceManagement.vehicleTerminalInstall.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
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.vehicleTerminalInstall.domain.bo.HotVehicleTerminalInstallBo;
import com.hotwj.platform.resourceManagement.vehicleTerminalInstall.domain.vo.HotVehicleTerminalInstallExportVo;
import com.hotwj.platform.resourceManagement.vehicleTerminalInstall.domain.vo.HotVehicleTerminalInstallVo;
import com.hotwj.platform.resourceManagement.vehicleTerminalInstall.service.IHotVehicleTerminalInstallService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定位终端安装记录
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/resourceManagement/vehicleTerminalInstall")
@Tag(name = "定位终端安装记录", description = "定位终端安装记录管理")
public class HotVehicleTerminalInstallController extends BaseController {

    private final IHotVehicleTerminalInstallService hotVehicleTerminalInstallService;
    private final IHotCompanySafetyManagerService hotCompanySafetyManagerService;
    private final IHotVehicleService hotVehicleService;

    /**
     * 查询定位终端安装记录列表
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:list")
    @GetMapping("/list")
    @Operation(summary = "查询定位终端安装记录列表")
    public TableDataInfo<HotVehicleTerminalInstallVo> list(HotVehicleTerminalInstallBo bo, PageQuery pageQuery) {
        return hotVehicleTerminalInstallService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询定位终端安装记录列表（车辆安装页面专用）
     */
    @GetMapping("/listForVehiclePage")
    @Operation(summary = "查询定位终端安装记录列表（车辆安装页面专用）")
    public TableDataInfo<HotVehicleTerminalInstallVo> listForVehiclePage(HotVehicleTerminalInstallBo bo, PageQuery pageQuery) {
        return hotVehicleTerminalInstallService.queryPageListForVehiclePage(bo, pageQuery);
    }

    /**
     * 导出定位终端安装记录列表
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:export")
    @Log(title = "定位终端安装记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "导出定位终端安装记录列表")
    public void export(HotVehicleTerminalInstallBo bo, HttpServletResponse response) {
        List<HotVehicleTerminalInstallVo> list = hotVehicleTerminalInstallService.queryList(bo);
        List<HotVehicleTerminalInstallExportVo> exportList = new ArrayList<>(list.size());
        Map<String, String> recorderNameCache = new HashMap<>();
        Map<String, String> plateNumberCache = new HashMap<>();
        for (HotVehicleTerminalInstallVo item : list) {
            HotVehicleTerminalInstallExportVo exportVo = new HotVehicleTerminalInstallExportVo();
            exportVo.setPlateNumber(resolvePlateNumber(item.getPlateNumber(), item.getVehicleId(), plateNumberCache));
            exportVo.setServiceProvider(item.getServiceProvider());
            exportVo.setDocumentNo(item.getDocumentNo());
            exportVo.setInstallDate(item.getInstallDate());
            exportVo.setServiceEndDate(item.getServiceEndDate());
            exportVo.setRecorderName(resolveRecorderName(item.getRecorderName(), item.getRecorder(), recorderNameCache));
            exportList.add(exportVo);
        }
        ExcelUtil.exportExcel(exportList, "定位终端安装记录", HotVehicleTerminalInstallExportVo.class, response);
    }

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

    private String resolvePlateNumber(String plateNumber, String vehicleId, Map<String, String> cache) {
        if (StrUtil.isNotBlank(plateNumber)) {
            return plateNumber;
        }
        if (StrUtil.isBlank(vehicleId)) {
            return plateNumber;
        }
        String cached = cache.get(vehicleId);
        if (StrUtil.isNotBlank(cached)) {
            return cached;
        }
        if (!NumberUtil.isLong(vehicleId)) {
            return plateNumber;
        }
        HotVehicleVo vehicle = hotVehicleService.queryById(Long.valueOf(vehicleId));
        if (vehicle != null && StrUtil.isNotBlank(vehicle.getPlateNumber())) {
            cache.put(vehicleId, vehicle.getPlateNumber());
            return vehicle.getPlateNumber();
        }
        return plateNumber;
    }

    /**
     * 获取定位终端安装记录详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:query")
    @GetMapping("/{id}")
    @Operation(summary = "获取定位终端安装记录详细信息")
    public R<HotVehicleTerminalInstallVo> getInfo(@NotNull(message = "主键不能为空")
                                                  @PathVariable Long id) {
        return R.ok(hotVehicleTerminalInstallService.queryById(id));
    }

    /**
     * 新增定位终端安装记录
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:add")
    @Log(title = "定位终端安装记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Operation(summary = "新增定位终端安装记录")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody HotVehicleTerminalInstallBo bo) {
        return toAjax(hotVehicleTerminalInstallService.insertByBo(bo));
    }

    /**
     * 修改定位终端安装记录
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:edit")
    @Log(title = "定位终端安装记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Operation(summary = "修改定位终端安装记录")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody HotVehicleTerminalInstallBo bo) {
        return toAjax(hotVehicleTerminalInstallService.updateByBo(bo));
    }

    /**
     * 删除定位终端安装记录
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("resourceManagement:vehicleTerminalInstall:remove")
    @Log(title = "定位终端安装记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除定位终端安装记录")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(hotVehicleTerminalInstallService.deleteWithValidByIds(List.of(ids), true));
    }
}
