package com.qaup.web.controller.system;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qaup.common.annotation.Log;
import com.qaup.common.core.controller.BaseController;
import com.qaup.common.core.domain.AjaxResult;
import com.qaup.common.core.page.TableDataInfo;
import com.qaup.common.enums.BusinessType;
import com.qaup.common.utils.poi.ExcelUtil;
import com.qaup.system.domain.SysVehicleType;
import com.qaup.system.service.ISysVehicleTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 车辆类型（路径编码模式）Controller
 * 
 * @author Claude Code
 * @date 2025-07-13
 */
@Tag(name = "车辆类型管理")
@RestController
@RequestMapping("/system/vehicle_type")
public class SysVehicleTypeController extends BaseController
{
    @Autowired
    private ISysVehicleTypeService sysVehicleTypeService;

    /**
     * 查询车辆类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询车辆类型列表")
    @GetMapping("/list")
    public TableDataInfo list(SysVehicleType sysVehicleType)
    {
        startPage();
        List<SysVehicleType> list = sysVehicleTypeService.selectSysVehicleTypeList(sysVehicleType);
        return getDataTable(list);
    }

    /**
     * 查询车辆类型树形结构列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询车辆类型树形结构列表")
    @GetMapping("/tree")
    public AjaxResult tree()
    {
        List<SysVehicleType> tree = sysVehicleTypeService.buildVehicleTypeTree();
        return AjaxResult.success(tree);
    }

    /**
     * 查询一级分类列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询一级分类列表")
    @GetMapping("/top-level")
    public AjaxResult topLevelTypes()
    {
        List<SysVehicleType> topLevelTypes = sysVehicleTypeService.selectTopLevelTypes();
        return AjaxResult.success(topLevelTypes);
    }

    /**
     * 根据父编码查询子类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "根据父编码查询子类型列表")
    @GetMapping("/children/{parentCode}")
    public AjaxResult getChildTypes(@PathVariable String parentCode)
    {
        List<SysVehicleType> childTypes = sysVehicleTypeService.selectChildTypesByParentCode(parentCode);
        return AjaxResult.success(childTypes);
    }

    /**
     * 查询无人车类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询无人车类型列表")
    @GetMapping("/unmanned")
    public AjaxResult unmannedVehicleTypes()
    {
        List<SysVehicleType> unmannedTypes = sysVehicleTypeService.selectUnmannedVehicleTypes();
        return AjaxResult.success(unmannedTypes);
    }

    /**
     * 查询特勤车类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询特勤车类型列表")
    @GetMapping("/special")
    public AjaxResult specialVehicleTypes()
    {
        List<SysVehicleType> specialTypes = sysVehicleTypeService.selectSpecialVehicleTypes();
        return AjaxResult.success(specialTypes);
    }

    /**
     * 查询普通车类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询普通车类型列表")
    @GetMapping("/normal")
    public AjaxResult normalVehicleTypes()
    {
        List<SysVehicleType> normalTypes = sysVehicleTypeService.selectNormalVehicleTypes();
        return AjaxResult.success(normalTypes);
    }

    /**
     * 查询叶子节点类型列表（具体车辆类型）
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:list')")
    @Operation(summary = "查询叶子节点类型列表")
    @GetMapping("/leaf")
    public AjaxResult leafTypes()
    {
        List<SysVehicleType> leafTypes = sysVehicleTypeService.selectLeafTypes();
        return AjaxResult.success(leafTypes);
    }

    /**
     * 导出车辆类型列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:export')")
    @Operation(summary = "导出车辆类型列表")
    @Log(title = "车辆类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysVehicleType sysVehicleType)
    {
        List<SysVehicleType> list = sysVehicleTypeService.selectSysVehicleTypeList(sysVehicleType);
        ExcelUtil<SysVehicleType> util = new ExcelUtil<SysVehicleType>(SysVehicleType.class);
        util.exportExcel(response, list, "车辆类型数据");
    }

    /**
     * 获取车辆类型详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:query')")
    @Operation(summary = "获取车辆类型详细信息")
    @GetMapping(value = "/{id}")
    @Parameter(name = "id", description = "车辆类型ID", required = true)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysVehicleTypeService.selectSysVehicleTypeById(id));
    }

    /**
     * 根据类型编码获取车辆类型详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:query')")
    @Operation(summary = "根据类型编码获取车辆类型详细信息")
    @GetMapping(value = "/code/{typeCode}")
    public AjaxResult getInfoByCode(@PathVariable("typeCode") String typeCode)
    {
        SysVehicleType vehicleType = sysVehicleTypeService.selectSysVehicleTypeByCode(typeCode);
        return AjaxResult.success(vehicleType);
    }

    /**
     * 获取车辆类型层级路径
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:query')")
    @Operation(summary = "获取车辆类型层级路径")
    @GetMapping(value = "/hierarchy/{typeCode}")
    public AjaxResult getTypeHierarchy(@PathVariable("typeCode") String typeCode)
    {
        List<SysVehicleType> hierarchy = sysVehicleTypeService.getTypeHierarchy(typeCode);
        return AjaxResult.success(hierarchy);
    }

    /**
     * 新增车辆类型
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:add')")
    @Operation(summary = "新增车辆类型")
    @Log(title = "车辆类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysVehicleType sysVehicleType)
    {
        // 检查类型编码是否已存在
        if (sysVehicleTypeService.checkTypeCodeExists(sysVehicleType.getTypeCode())) {
            return AjaxResult.error("车辆类型编码已存在: " + sysVehicleType.getTypeCode());
        }

        // 设置创建者
        sysVehicleType.setCreateBy(getUsername());
        
        // 自动设置一些字段
        if (sysVehicleType.getTypeCode() != null) {
            // 根据类型编码确定层级
            int dotCount = sysVehicleType.getTypeCode().length() - 
                           sysVehicleType.getTypeCode().replace(".", "").length();
            sysVehicleType.setPathLevel(dotCount + 1);
            
            // 设置父编码
            if (dotCount > 0) {
                String parentCode = sysVehicleType.getTypeCode().substring(0, 
                    sysVehicleType.getTypeCode().lastIndexOf('.'));
                sysVehicleType.setParentCode(parentCode);
            }
            
            // 设置是否为叶子节点（二级分类为叶子节点）
            sysVehicleType.setIsLeaf(sysVehicleType.getPathLevel() == 2);
        }
        
        return toAjax(sysVehicleTypeService.insertSysVehicleType(sysVehicleType));
    }

    /**
     * 修改车辆类型
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:edit')")
    @Operation(summary = "修改车辆类型")
    @Log(title = "车辆类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysVehicleType sysVehicleType)
    {
        sysVehicleType.setUpdateBy(getUsername());
        return toAjax(sysVehicleTypeService.updateSysVehicleType(sysVehicleType));
    }

    /**
     * 删除车辆类型
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:remove')")
    @Operation(summary = "删除车辆类型")
    @Log(title = "车辆类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否存在子类型或关联的车辆信息
        for (Long id : ids) {
            SysVehicleType vehicleType = sysVehicleTypeService.selectSysVehicleTypeById(id);
            if (vehicleType != null) {
                int childCount = sysVehicleTypeService.countChildTypes(vehicleType.getTypeCode());
                if (childCount > 0) {
                    return AjaxResult.error("车辆类型 [" + vehicleType.getDisplayNameCn() + "] 存在子类型，不能删除");
                }
                // TODO: 检查是否有车辆信息关联此类型
            }
        }
        
        return toAjax(sysVehicleTypeService.deleteSysVehicleTypeByIds(ids));
    }

    /**
     * 根据类型编码删除车辆类型
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:remove')")
    @Operation(summary = "根据类型编码删除车辆类型")
    @Log(title = "车辆类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/code/{typeCode}")
    public AjaxResult removeByCode(@PathVariable String typeCode)
    {
        // 检查是否存在子类型
        int childCount = sysVehicleTypeService.countChildTypes(typeCode);
        if (childCount > 0) {
            return AjaxResult.error("车辆类型编码 [" + typeCode + "] 存在子类型，不能删除");
        }
        
        return toAjax(sysVehicleTypeService.deleteSysVehicleTypeByCode(typeCode));
    }

    /**
     * 初始化标准车辆类型数据
     */
    //@PreAuthorize("@ss.hasPermi('system:vehicle_type:add')")
    @Operation(summary = "初始化标准车辆类型数据")
    @Log(title = "车辆类型", businessType = BusinessType.INSERT)
    @PostMapping("/init")
    public AjaxResult initStandardData()
    {
        int count = sysVehicleTypeService.initDataFromEnum();
        return AjaxResult.success("初始化完成，共创建 " + count + " 条标准车辆类型数据");
    }
}