package com.gxwebsoft.ai.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.dto.AuditContentRequest;
import com.gxwebsoft.ai.dto.export.BudgetManageExportEntity;
import com.gxwebsoft.ai.dto.export.BudgetExecutionExportEntity;
import com.gxwebsoft.ai.service.AuditContent5BudgetManageService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.ai.service.AuditContent5BudgetExecutionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 审计内容5控制器 - 预算管理审计
 */
@Slf4j
@Tag(name = "审计内容5-预算管理审计")
@RestController
@RequestMapping("/api/ai/auditContent5")
public class AuditContent5Controller extends BaseAuditContentController {
    
    @Autowired
    private AuditContent5BudgetManageService auditContent5BudgetManageService;
    
    @Autowired
    private AuditContent5BudgetExecutionService auditContent5BudgetExecutionService;
    
    /**
     * 生成预算管理审计表数据
     */
    @Operation(summary = "生成预算管理审计表")
    @PostMapping("/generateBudgetManageTable")
    public ApiResult<?> generateBudgetManageTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent5BudgetManageService.generateBudgetManageTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion, request.getData()
            ));
    }
    
    /**
     * 生成预算执行情况审计表数据
     */
    @Operation(summary = "生成预算执行情况审计表")
    @PostMapping("/generateBudgetExecutionTable")
    public ApiResult<?> generateBudgetExecutionTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent5BudgetExecutionService.generateBudgetExecutionTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion, request.getData()
            ));
    }
    
    /**
     * 导出预算管理审计表到Excel
     */
    @Operation(summary = "导出预算管理审计表到Excel")
    @PostMapping("/exportBudgetManageTable")
    public void exportBudgetManageTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "预算管理审计表", 
            this::convertToBudgetManageEntityList, BudgetManageExportEntity.class);
    }
    
    /**
     * 导出预算执行情况审计表到Excel
     */
    @Operation(summary = "导出预算执行情况审计表到Excel")
    @PostMapping("/exportBudgetExecutionTable")
    public void exportBudgetExecutionTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "预算执行情况审计表", 
            this::convertToBudgetExecutionEntityList, BudgetExecutionExportEntity.class);
    }
    
    // ========== 数据转换方法 ==========
    
    private List<BudgetManageExportEntity> convertToBudgetManageEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToBudgetManageEntity).collect(Collectors.toList());
    }
    
    private List<BudgetExecutionExportEntity> convertToBudgetExecutionEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToBudgetExecutionEntity).collect(Collectors.toList());
    }
    
    private BudgetManageExportEntity convertToBudgetManageEntity(Map<String, Object> item) {
        BudgetManageExportEntity entity = new BudgetManageExportEntity();
        entity.setBudgetSubject(getStringValue(item, "budgetSubject"));
        entity.setIndicatorSourceTotal(getStringValue(item, "indicatorSourceTotal"));
        entity.setIndicatorSourceLastYearBalance(getStringValue(item, "indicatorSourceLastYearBalance"));
        entity.setIndicatorSourceInitialBudget(getStringValue(item, "indicatorSourceInitialBudget"));
        entity.setIndicatorSourceAdditionalBudget(getStringValue(item, "indicatorSourceAdditionalBudget"));
        entity.setIndicatorUseTotal(getStringValue(item, "indicatorUseTotal"));
        entity.setIndicatorUseAppropriationSubtotal(getStringValue(item, "indicatorUseAppropriationSubtotal"));
        entity.setIndicatorUseAppropriation(getStringValue(item, "indicatorUseAppropriation"));
        entity.setIndicatorUseSalaryPayment(getStringValue(item, "indicatorUseSalaryPayment"));
        entity.setIndicatorUseGovProcurement(getStringValue(item, "indicatorUseGovProcurement"));
        entity.setFinanceManagementAccount(getStringValue(item, "financeManagementAccount"));
        entity.setBudgetUsedForOther(getStringValue(item, "budgetUsedForOther"));
        entity.setIndicatorBalance(getStringValue(item, "indicatorBalance"));
        entity.setGovernmentProcurement(getStringValue(item, "governmentProcurement"));
        entity.setPayableToUnit(getStringValue(item, "payableToUnit"));
        entity.setOther(getStringValue(item, "other"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
    
    private BudgetExecutionExportEntity convertToBudgetExecutionEntity(Map<String, Object> item) {
        BudgetExecutionExportEntity entity = new BudgetExecutionExportEntity();
        entity.setProject(getStringValue(item, "project"));
        entity.setLastYearCarryOver(getStringValue(item, "lastYearCarryOver"));
        entity.setCurrentYearBudgetTotal(getStringValue(item, "currentYearBudgetTotal"));
        entity.setInitialApprovedBudget(getStringValue(item, "initialApprovedBudget"));
        entity.setAdditionalBudgetAmount(getStringValue(item, "additionalBudgetAmount"));
        entity.setActualAppropriation(getStringValue(item, "actualAppropriation"));
        entity.setIndicatorBalance(getStringValue(item, "indicatorBalance"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
}