package com.yhy.module.core.controller.admin.workbench;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.*;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.yhy.module.core.controller.admin.workbench.vo.WbProjectTreeRespVO;
import com.yhy.module.core.controller.admin.workbench.vo.WbProjectTreeSaveReqVO;
import com.yhy.module.core.controller.admin.workbench.vo.WbProjectTreeSwapSortReqVO;
import com.yhy.module.core.service.workbench.WbProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 工作台项目管理树 Controller
 *
 * @author yhy
 */
@Tag(name = "工作台 - 项目管理")
@RestController
@RequestMapping("/core/wb/project")
@Validated
public class WbProjectController {

    @Resource
    private WbProjectService wbProjectService;

    @Resource
    private com.yhy.module.core.service.workbench.WbSnapshotReadService wbSnapshotReadService;

    @Resource
    private com.yhy.module.core.service.quota.QuotaRateItemService quotaRateItemService;

    @Resource
    private com.yhy.module.core.service.quota.QuotaRateFieldLabelService quotaRateFieldLabelService;

    @Resource
    private com.yhy.module.core.service.quota.QuotaFeeItemService quotaFeeItemService;

    @Resource
    private com.yhy.module.core.service.workbench.AuditModeService auditModeService;

    @Resource
    private com.yhy.module.core.service.workbench.ProgressPaymentModeService progressPaymentModeService;

    @PostMapping("/create")
    @Operation(summary = "创建节点（目录或项目）")
    @PreAuthorize("@ss.hasPermission('core:wb-project:create')")
    public CommonResult<Long> createNode(@Valid @RequestBody WbProjectTreeSaveReqVO createReqVO) {
        return success(wbProjectService.createNode(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新节点")
    @PreAuthorize("@ss.hasPermission('core:wb-project:update')")
    public CommonResult<Boolean> updateNode(@Valid @RequestBody WbProjectTreeSaveReqVO updateReqVO) {
        wbProjectService.updateNode(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除节点")
    @Parameter(name = "id", description = "节点ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:delete')")
    public CommonResult<Boolean> deleteNode(@RequestParam("id") Long id) {
        wbProjectService.deleteNode(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获取节点详情")
    @Parameter(name = "id", description = "节点ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<WbProjectTreeRespVO> getNode(@RequestParam("id") Long id) {
        return success(wbProjectService.getNode(id));
    }

    @GetMapping("/tree")
    @Operation(summary = "获取项目管理树")
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<List<WbProjectTreeRespVO>> getTree() {
        return success(wbProjectService.getTree());
    }

    @PostMapping("/swap-sort")
    @Operation(summary = "交换排序")
    @PreAuthorize("@ss.hasPermission('core:wb-project:update')")
    public CommonResult<Boolean> swapSort(@Valid @RequestBody WbProjectTreeSwapSortReqVO swapReqVO) {
        wbProjectService.swapSort(swapReqVO);
        return success(true);
    }

    @PostMapping("/archive")
    @Operation(summary = "归档项目")
    @Parameter(name = "id", description = "项目节点ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:update')")
    public CommonResult<Boolean> archiveProject(@RequestParam("id") Long id) {
        wbProjectService.archiveProject(id);
        return success(true);
    }

    @PutMapping("/save-to-history")
    @Operation(summary = "将项目保存至历史库")
    @Parameter(name = "id", description = "项目节点ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:update')")
    public CommonResult<Boolean> saveToHistoryLibrary(@RequestParam("id") Long id) {
        wbProjectService.saveToHistoryLibrary(id);
        return success(true);
    }

    @PutMapping("/remove-from-history")
    @Operation(summary = "从历史库撤销项目")
    @Parameter(name = "id", description = "项目节点ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:update')")
    public CommonResult<Boolean> removeFromHistoryLibrary(@RequestParam("id") Long id) {
        wbProjectService.removeFromHistoryLibrary(id);
        return success(true);
    }

    @GetMapping("/rate-item-tree")
    @Operation(summary = "获取费率项树（优先使用快照数据）")
    @Parameters({
        @Parameter(name = "compileTreeId", description = "单位工程ID", required = true, example = "1"),
        @Parameter(name = "rateModeId", description = "费率模式ID", required = true, example = "100")
    })
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<List<com.yhy.module.core.controller.admin.quota.vo.QuotaRateItemRespVO>> getRateItemTree(
            @RequestParam("compileTreeId") Long compileTreeId,
            @RequestParam("rateModeId") Long rateModeId) {
        // 1. 优先从快照表读取
        List<com.yhy.module.core.dal.dataobject.workbench.WbRateItemDO> snapshotItems = 
                wbSnapshotReadService.getRateItems(compileTreeId, rateModeId);
        
        // 2. 转换为VO（复用后台标准库的逻辑）
        List<com.yhy.module.core.controller.admin.quota.vo.QuotaRateItemRespVO> result;
        if (snapshotItems != null && !snapshotItems.isEmpty()) {
            // 从快照数据构建树（转换为QuotaRateItemDO后调用公共方法）
            List<com.yhy.module.core.dal.dataobject.quota.QuotaRateItemDO> rateItems = snapshotItems.stream()
                    .map(wb -> {
                        com.yhy.module.core.dal.dataobject.quota.QuotaRateItemDO quota = new com.yhy.module.core.dal.dataobject.quota.QuotaRateItemDO();
                        quota.setId(wb.getId());
                        quota.setCatalogItemId(wb.getCatalogItemId());
                        quota.setParentId(wb.getParentId());
                        quota.setCustomCode(wb.getCustomCode());
                        quota.setName(wb.getName());
                        quota.setRateCode(wb.getRateCode());
                        quota.setIsEditable(wb.getIsEditable());
                        quota.setDefaultValue(wb.getDefaultValue());
                        quota.setValueMode(wb.getValueMode());
                        quota.setSettings(wb.getSettings());
                        quota.setNodeType(wb.getNodeType());
                        quota.setLevel(wb.getLevel());
                        quota.setSortOrder(wb.getSortOrder());
                        return quota;
                    })
                    .collect(java.util.stream.Collectors.toList());
            // 快照没有字段配置，传空列表
            result = quotaRateItemService.buildRateItemTree(rateItems, java.util.Collections.emptyList());
        } else {
            // 快照不存在，返回空列表（不回退到后台标准库）
            result = java.util.Collections.emptyList();
        }
        return success(result);
    }

    @GetMapping("/rate-field-label-list")
    @Operation(summary = "获取费率字段标签列表（优先使用快照数据）")
    @Parameters({
        @Parameter(name = "compileTreeId", description = "单位工程ID", required = true, example = "1"),
        @Parameter(name = "rateModeId", description = "费率模式ID", required = true, example = "100")
    })
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<List<com.yhy.module.core.controller.admin.quota.vo.QuotaRateFieldLabelRespVO>> getRateFieldLabelList(
            @RequestParam("compileTreeId") Long compileTreeId,
            @RequestParam("rateModeId") Long rateModeId) {
        // 1. 优先从快照表读取
        List<com.yhy.module.core.dal.dataobject.workbench.WbRateFieldLabelDO> snapshotItems = 
                wbSnapshotReadService.getRateFieldLabels(compileTreeId, rateModeId);
        
        // 2. 转换为VO
        List<com.yhy.module.core.controller.admin.quota.vo.QuotaRateFieldLabelRespVO> result = new java.util.ArrayList<>();
        if (snapshotItems != null && !snapshotItems.isEmpty()) {
            for (com.yhy.module.core.dal.dataobject.workbench.WbRateFieldLabelDO item : snapshotItems) {
                com.yhy.module.core.controller.admin.quota.vo.QuotaRateFieldLabelRespVO vo = 
                        new com.yhy.module.core.controller.admin.quota.vo.QuotaRateFieldLabelRespVO();
                vo.setId(item.getId());
                vo.setCatalogItemId(item.getCatalogItemId());
                vo.setLabelName(item.getLabelName());
                vo.setSortOrder(item.getSortOrder());
                result.add(vo);
            }
        } else {
            // 快照不存在，返回空列表（不回退到后台标准库）
        }
        return success(result);
    }

    @GetMapping("/fee-item-tree")
    @Operation(summary = "获取取费项树（只使用快照数据）")
    @Parameters({
        @Parameter(name = "compileTreeId", description = "单位工程ID", required = true, example = "1"),
        @Parameter(name = "rateModeId", description = "费率模式ID", required = true, example = "100")
    })
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<List<com.yhy.module.core.controller.admin.quota.vo.QuotaFeeItemWithRateRespVO>> getFeeItemTree(
            @RequestParam("compileTreeId") Long compileTreeId,
            @RequestParam("rateModeId") Long rateModeId) {
        // 只从快照表读取，不回退到后台标准库
        List<com.yhy.module.core.controller.admin.quota.vo.QuotaFeeItemWithRateRespVO> result = 
                wbSnapshotReadService.getFeeItemWithRateTree(compileTreeId, rateModeId);
        
        if (result == null) {
            // 快照不存在，返回空列表（不回退到后台标准库）
            result = java.util.Collections.emptyList();
        }
        return success(result);
    }

    @GetMapping("/check-mode-exists")
    @Operation(summary = "检查项目是否存在审核模式和进度款模式数据")
    @Parameter(name = "projectId", description = "项目ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:wb-project:query')")
    public CommonResult<Map<String, Boolean>> checkModeExists(@RequestParam("projectId") Long projectId) {
        Map<String, Boolean> result = new java.util.HashMap<>();
        result.put("hasAuditMode", !auditModeService.getAuditModeList(projectId).isEmpty());
        result.put("hasProgressPaymentMode", !progressPaymentModeService.getProgressPaymentModeList(projectId).isEmpty());
        return success(result);
    }
}
