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

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.domain.vo.HotVehicleAnnualReviewVo;
import com.hotwj.platform.resourceManagement.vehicleAnnualReview.service.IHotVehicleAnnualReviewService;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.bo.HotVehicleBo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.bo.HotVehicleStatusBo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleCategoryStatVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleExportVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleImportVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.service.IHotVehicleService;
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.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
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.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司车辆信息
 *
 * @author shihongwei
 * @date 2025-12-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/resourceManagement/vehicle")
@Tag(name = "公司车辆信息", description = "公司车辆信息管理")
public class HotVehicleController extends BaseController {

    private final IHotVehicleService hotVehicleService;
    private final IHotVehicleAnnualReviewService hotVehicleAnnualReviewService;

    /**
     * 统计公司车辆分类数量
     */
    //@SaCheckPermission("resourceManagement:vehicle:list")
    @GetMapping("/stat")
    @Operation(summary = "统计公司车辆分类数量")
    public R<List<HotVehicleCategoryStatVo>> stat(Long companyId) {
        return R.ok(hotVehicleService.queryVehicleCategoryStat(companyId));
    }

    /**
     * 查询公司车辆信息列表
     */
    //@SaCheckPermission("resourceManagement:vehicle:list")
    @GetMapping("/list")
    @Operation(summary = "查询公司车辆信息列表")
    public TableDataInfo<HotVehicleVo> list(HotVehicleBo bo, PageQuery pageQuery) {
        return hotVehicleService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询公司车辆信息列表（状态为数组）
     */
    //@SaCheckPermission("resourceManagement:vehicle:list")
    @GetMapping("/listByStatus")
    @Operation(summary = "查询公司车辆信息列表（状态为数组）")
    public TableDataInfo<HotVehicleVo> listByStatus(HotVehicleStatusBo bo, PageQuery pageQuery) {
        return hotVehicleService.queryPageListByStatus(bo, pageQuery);
    }

    /**
     * 查询当前企业可绑定的车辆列表
     */
    @GetMapping("/bindableList")
    @Operation(summary = "查询当前企业可绑定的车辆列表")
    public R<List<HotVehicleVo>> bindableList(HotVehicleBo bo) {
        bo.setCompanyId(LoginHelper.getLoginUser().getCompanyId());
        return R.ok(hotVehicleService.queryBindableList(bo));
    }

    /**
     * 导入车辆
     */
    //@SaCheckPermission("resourceManagement:vehicle:import")
    @Log(title = "公司车辆信息", businessType = BusinessType.IMPORT)
    @RepeatSubmit()
    @PostMapping("/importData")
    @Operation(summary = "导入公司车辆信息")
    public R<String> importData(@RequestPart("file") MultipartFile file, @NotNull(message = "公司ID不能为空") Long companyId) throws Exception {
        List<HotVehicleImportVo> list = ExcelUtil.importExcel(file.getInputStream(), HotVehicleImportVo.class);
        return R.ok(hotVehicleService.importData(list, companyId));
    }

    /**
     * 下载导入模板
     */
    @SaIgnore
    @GetMapping("/importTemplate")
    @Operation(summary = "下载导入模板")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "车辆导入模板", HotVehicleImportVo.class, response);
    }

    /**
     * 导出公司车辆信息列表
     */
    //@SaCheckPermission("resourceManagement:vehicle:export")
    @Log(title = "公司车辆信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "车辆台账导出")
    public void export(@NotEmpty(message = "车辆ID不能为空") String ids, HttpServletResponse response) {
        List<String> vehicleIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(id -> !id.isEmpty())
                .collect(Collectors.toList());
        if (vehicleIds.isEmpty()) {
            throw new ServiceException("车辆ID不能为空");
        }

        HotVehicleBo bo = new HotVehicleBo();
        bo.setIds(vehicleIds);
        List<HotVehicleVo> list = hotVehicleService.queryList(bo);
        List<HotVehicleExportVo> exportList = new ArrayList<>();
        for (HotVehicleVo vehicle : list) {
            HotVehicleExportVo vo = new HotVehicleExportVo();
            vo.setArchiveNo(vehicle.getArchiveNo());
            vo.setPlateNumber(vehicle.getPlateNumber());
            vo.setBrandModel(vehicle.getBrandModel());
            vo.setVehicleType(vehicle.getVehicleType());
            vo.setVehicleModel(vehicle.getVehicleModel());
            vo.setPlateColor(vehicle.getPlateColor());
            vo.setVehicleRegisterDate(vehicle.getVehicleRegisterDate());
            vo.setRatedLoadKg(vehicle.getRatedLoadKg());
            vo.setEngineNumber(vehicle.getDriveMotorModel());
            vo.setFrameNumber(vehicle.getFrameNumber());
            vo.setTransportLicenseNo(vehicle.getTransportLicenseNo());
            vo.setFuelType(vehicle.getFuelType());
            vo.setTransportValidMonth(vehicle.getTransportValidMonth());

            HotVehicleAnnualReviewVo review = hotVehicleAnnualReviewService.queryLatestByVehicleId(vehicle.getId());
            if (review != null) {
                Long level = review.getEvaluationLevel();
                if (level != null) {
                    if (level == 1L) {
                        vo.setTechnicalLevel("一级");
                    } else if (level == 2L) {
                        vo.setTechnicalLevel("二级");
                    } else {
                        vo.setTechnicalLevel(String.valueOf(level));
                    }
                }
                vo.setInspectionDate(review.getReviewDate());
            }
            exportList.add(vo);
        }
        ExcelUtil.exportExcel(exportList, "车辆台账信息", HotVehicleExportVo.class, response);
    }

    /**
     * 导出车辆全部信息
     */
    //@SaCheckPermission("resourceManagement:vehicle:export")
    @Log(title = "公司车辆信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTemplateData")
    @Operation(summary = "导出车辆全部信息")
    public void exportTemplateData(@NotEmpty(message = "车辆ID不能为空") String ids, HttpServletResponse response) {
        List<String> vehicleIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(id -> !id.isEmpty())
                .collect(Collectors.toList());
        if (vehicleIds.isEmpty()) {
            throw new ServiceException("车辆ID不能为空");
        }

        HotVehicleBo bo = new HotVehicleBo();
        bo.setIds(vehicleIds);
        List<HotVehicleVo> list = hotVehicleService.queryList(bo);
        List<HotVehicleImportVo> exportList = new ArrayList<>();
        for (HotVehicleVo vehicle : list) {
            HotVehicleImportVo vo = new HotVehicleImportVo();
            BeanUtil.copyProperties(vehicle, vo, "transportValidMonth", "inspectionValidMonth");
            vo.setEngineNo(vehicle.getDriveMotorModel());
            vo.setTransportValidMonth(DateUtils.parseDate(vehicle.getTransportValidMonth()));
            vo.setInspectionValidMonth(DateUtils.parseDate(vehicle.getInspectionValidMonth()));
            exportList.add(vo);
        }
        ExcelUtil.exportExcel(exportList, "车辆全部信息", HotVehicleImportVo.class, response);
    }
    
    /**
     * 获取公司车辆信息详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("resourceManagement:vehicle:query")
    @GetMapping("/{id}")
    @Operation(summary = "获取公司车辆信息详细信息")
    public R<HotVehicleVo> getInfo(@NotNull(message = "主键不能为空")
                                   @PathVariable Long id) {
        return R.ok(hotVehicleService.queryById(id));
    }

    /**
     * 新增公司车辆信息
     */
    //@SaCheckPermission("resourceManagement:vehicle:add")
    @Log(title = "公司车辆信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Operation(summary = "新增公司车辆信息")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody HotVehicleBo bo) {
        return toAjax(hotVehicleService.insertByBo(bo));
    }

    /**
     * 修改公司车辆信息
     */
    //@SaCheckPermission("resourceManagement:vehicle:edit")
    @Log(title = "公司车辆信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Operation(summary = "修改公司车辆信息")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody HotVehicleBo bo) {
        return toAjax(hotVehicleService.updateByBo(bo));
    }

    /**
     * 删除公司车辆信息
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("resourceManagement:vehicle:remove")
    @Log(title = "公司车辆信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除公司车辆信息")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(hotVehicleService.deleteWithValidByIds(List.of(ids), true));
    }
}
