package com.hotent.baseInfo.controller;

import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.baseInfo.dto.*;
import com.hotent.baseInfo.manager.CostCatalogManager;
import com.hotent.baseInfo.model.CostCatalog;
import com.hotent.baseInfo.req.CostCatalogPageReq;
import com.hotent.baseInfo.vo.CatalogNameVo;
import com.hotent.baseInfo.vo.CatalogOperationVo;
import com.hotent.baseInfo.vo.CatalogTreeVo;
import com.hotent.common.CrudService;
import com.hotent.constant.BaseConstant;
import com.hotent.util.CopyUtil;
import com.hotent.util.JsonUtil;
import com.hotent.util.treeutil.SumTree;
import com.hotent.util.treeutil.newtreeutil.TreeDotUtils;
import org.springframework.web.bind.annotation.*;
import com.hotent.base.model.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;
import java.util.List;

/**
 * 成本监审目录管理 前端控制器
 *
 * @author 超级管理员
 * @since 2025-01-23
 */
@Api(tags = "成本监审目录管理")
@RestController
@RequestMapping("/api/catalog")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostCatalogController {

    @Autowired
    private CostCatalogManager costCatalogManager;

    /**
     * 目录列表查询
     */
    @PostMapping("/list")
    @ApiOperation(value = "查询监审目录树及列表数据", notes = "支持树形结构展示和多条件查询")
    public CommonResult<List<SumTree<CatalogTreeVo>>> getCatalogList(@RequestBody CostCatalogPageReq req) throws Exception {

        List<CostCatalog> catalogList = costCatalogManager.getCatalogList(req);

        List<CatalogTreeVo> allList = JsonUtil.getJsonToList(catalogList, CatalogTreeVo.class);
        for (int i = 0; i < catalogList.size(); i++) {
            CostCatalog costCatalog = catalogList.get(i);
            allList.get(i).setId(costCatalog.getCatalogId());
        }
        List<SumTree<CatalogTreeVo>> trees = TreeDotUtils.convertListToTreeDotFilter(allList);
        CommonResult<List<SumTree<CatalogTreeVo>>> result = CommonResult.ok();
        result.setValue(trees);
        return result;
    }

    /**
     * 目录类别新增
     */
    @PostMapping("/aadCategory")
    @ApiOperation(value = "新增目录类别", notes = "新增目录类别（非末级节点）")
    public CommonResult<CatalogOperationVo> createCategory(
            @ApiParam("类别新增参数") @Valid @RequestBody CategoryCreateDto createDto) {

        try {
            costCatalogManager.createCategory(createDto);
            return CommonResult.<CatalogOperationVo>ok().message("新增类别成功");
        } catch (Exception e) {
            return CommonResult.<CatalogOperationVo>error().message("新增失败：" + e.getMessage());
        }
    }

    //获取目录类型
    @GetMapping("/getCategory")
    @ApiOperation(value = "获取目录类别", notes = "获取目录类别")
    public CommonResult<List<CostCatalog>> getCategory() {
        return  CommonResult.<List<CostCatalog>>ok().value(costCatalogManager.getCategoryList()) ;
    }

    /**
     * 目录内容新增
     */
    @PostMapping("/addContent")
    @ApiOperation(value = "新增目录内容", notes = "新增目录内容（末级节点）")
    public CommonResult<CatalogOperationVo> createContent(
            @ApiParam("内容新增参数") @Valid @RequestBody ContentCreateDto createDto) {

        try {
            costCatalogManager.createContent(createDto);
            return CommonResult.<CatalogOperationVo>ok().message("新增内容成功");
        } catch (Exception e) {
            return CommonResult.<CatalogOperationVo>error().message("新增失败：" + e.getMessage());
        }
    }


    /**
     * 目录状态切换（启用/停用）
     */
    @PostMapping("/status")
    @ApiOperation(value = "切换目录节点的启用/停用状态", notes = "支持单个节点状态切换")
    public CommonResult<String> updateStatus(
            @ApiParam("状态切换参数") @Valid @RequestBody CatalogStatusDto statusDto) {

        try {
            boolean success = costCatalogManager.updateStatus(statusDto);
            if (success) {
                String statusText = statusDto.getStatus().equals(BaseConstant.ENABLE) ? "启用" : "停用";
                return CommonResult.<String>ok().message("状态已更新为" + statusText);
            } else {
                return CommonResult.<String>error().message("状态更新失败");
            }
        } catch (Exception e) {
            return CommonResult.<String>error().message("状态更新失败：" + e.getMessage());
        }
    }

    /**
     * 目录信息维护
     */
    @PutMapping("/updateCategory")
    @ApiOperation(value = "修改目录类型", notes = "修改目录类型")
    public CommonResult<String> updateCategory(
            @ApiParam("修改目录类型") @Valid @RequestBody CategoryCreateDto updateDto) {

        try {
            boolean success = costCatalogManager.updateCategory(updateDto);
            if (success) {
                return CommonResult.<String>ok().message("信息维护成功");
            } else {
                return CommonResult.<String>error().message("信息维护失败");
            }
        } catch (Exception e) {
            return CommonResult.<String>error().message("信息维护失败：" + e.getMessage());
        }
    }

    @PutMapping("/updateContent")
    @ApiOperation(value = "修改目录内容", notes = "修改目录内容")
    public CommonResult<String> updateCategory(
            @ApiParam("修改目录内容") @Valid @RequestBody ContentCreateDto updateDto) {

        try {
            boolean success = costCatalogManager.updateContent(updateDto);
            if (success) {
                return CommonResult.<String>ok().message("信息维护成功");
            } else {
                return CommonResult.<String>error().message("信息维护失败");
            }
        } catch (Exception e) {
            return CommonResult.<String>error().message("信息维护失败：" + e.getMessage());
        }
    }

    /**
     * 获取目录详情（兼容旧接口）
     */
    @GetMapping("/detail")
    @ApiOperation(value = "根据ID获取目录详情", notes = "获取单个目录的详细信息")
    public CommonResult<CostCatalog> getCatalogDetail(
            @ApiParam("目录ID") @RequestParam("id") String id) {

        try {
            CostCatalog catalog = costCatalogManager.getDetail(id);
            if (catalog != null && BaseConstant.NORMAL_STATUS.equals(catalog.getIsDeleted())) {
                return CommonResult.<CostCatalog>ok().value(catalog);
            } else {
                return CommonResult.<CostCatalog>error().message("目录不存在");
            }
        } catch (Exception e) {
            return CommonResult.<CostCatalog>error().message("查询失败：" + e.getMessage());
        }
    }

    //根据ParentId生成code
    @GetMapping("/generateCode")
    @ApiOperation(value = "根据父节点ID生成目录编码", notes = "根据父节点ID生成目录编码")
    public CommonResult<String> generateCode(
            @ApiParam("父节点ID") @RequestParam("parentId") String parentId) {

        String code = costCatalogManager.generateNewCode(parentId);
        return CommonResult.<String>ok().value(code);


    }


    @PostMapping("/deleteById")
    @ApiOperation("根据id删除")
    public CommonResult<String> deleteById(@ApiParam("id") @RequestParam("id") String id) {
        boolean result = costCatalogManager.removeById(id);
        if(!result) {
            return new CommonResult<>(ResponseErrorEnums.FAIL_OPTION, "删除实体失败");
        }
        return new CommonResult<>();
    }


    /**
     * 验证目录名称是否重复
     */
    @GetMapping("/validate-name")
    @ApiOperation(value = "验证目录名称是否重复", notes = "用于实时校验目录名称是否重复")
    public CommonResult<Boolean> validateName(
            @ApiParam("目录名称") @RequestParam("name") String name,
            @ApiParam("父节点ID") @RequestParam("parentId") String parentId,
            @ApiParam("排除的ID（用于更新）") @RequestParam(value = "excludeId", required = false) String excludeId) {

        try {
            boolean isDuplicate = costCatalogManager.isNameDuplicate(name, parentId, excludeId);
            return CommonResult.<Boolean>ok().value(isDuplicate);
        } catch (Exception e) {
            return CommonResult.<Boolean>error().message("校验失败：" + e.getMessage());
        }
    }
}