package com.gxwebsoft.ai.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.dto.AuditContentRequest;
import com.gxwebsoft.ai.dto.export.EightRegExportEntity;
import com.gxwebsoft.ai.dto.export.ExpenseExportEntity;
import com.gxwebsoft.ai.dto.export.LeaderListExportEntity;
import com.gxwebsoft.ai.service.AuditContent1EightRegService;
import com.gxwebsoft.ai.service.AuditContent1ExpenseService;
import com.gxwebsoft.ai.service.AuditContent1LeaderListService;
import com.gxwebsoft.common.core.web.ApiResult;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
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;

/**
 * 审计内容1控制器 - 八项规定对比分析
 */
@Slf4j
@RequiredArgsConstructor
@Tag(name = "审计内容1-八项规定")
@RestController
@RequestMapping("/api/ai/auditContent1")
public class AuditContent1Controller extends BaseAuditContentController {
    
    private final AuditContent1LeaderListService auditContent1LeaderListService;
    
    private final AuditContent1ExpenseService auditContent1ExpenseService;
    
    private final AuditContent1EightRegService auditContent1EightRegService;
    
    /**
     * 生成领导班子名单数据
     */
    @Operation(summary = "生成领导班子名单")
    @PostMapping("/generateLeaderListTable")
    public ApiResult<?> generateLeaderListTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent1LeaderListService.generateLeaderListTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion
            ));
    }

    /**
     * 生成支出情况表数据
     */
    @Operation(summary = "生成支出情况表")
    @PostMapping("/generateExpenseTable")
    public ApiResult<?> generateExpenseTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent1ExpenseService.generateExpenseTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion
            ));
    }
    
    /**
     * 生成八项规定对比分析表数据
     */
    @Operation(summary = "生成八项规定对比分析表")
    @PostMapping("/generateEightRegTable")
    public ApiResult<?> generateEightRegTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent1EightRegService.generateEightRegTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion
            ));
    }
    
    /**
     * 导出八项规定对比分析表到Excel
     */
    @Operation(summary = "导出八项规定对比分析表到Excel")
    @PostMapping("/exportEightRegTable")
    public void exportEightRegTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "八项规定对比分析表", 
            this::convertToEightRegEntityList, EightRegExportEntity.class);
    }
    
    /**
     * 导出领导班子名单到Excel
     */
    @Operation(summary = "导出领导班子名单到Excel")
    @PostMapping("/exportLeaderListTable")
    public void exportLeaderListTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "领导班子名单", 
            this::convertToLeaderListEntityList, LeaderListExportEntity.class);
    }
    
    /**
     * 导出支出情况表到Excel
     */
    @Operation(summary = "导出支出情况表到Excel")
    @PostMapping("/exportExpenseTable")
    public void exportExpenseTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "支出情况表", 
            this::convertToExpenseEntityList, ExpenseExportEntity.class);
    }
    
    // ========== 数据转换方法 ==========
    
    private List<EightRegExportEntity> convertToEightRegEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToEightRegEntity).collect(Collectors.toList());
    }
    
    private EightRegExportEntity convertToEightRegEntity(Map<String, Object> item) {
        EightRegExportEntity entity = new EightRegExportEntity();
        entity.setTitle(getStringValue(item, "title"));
        entity.setContent(getStringValue(item, "content"));
        entity.setTestContent(getStringValue(item, "testContent"));
        entity.setResult(getStringValue(item, "result"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
    
    private List<LeaderListExportEntity> convertToLeaderListEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToLeaderListEntity).collect(Collectors.toList());
    }

    private LeaderListExportEntity convertToLeaderListEntity(Map<String, Object> item) {
        LeaderListExportEntity entity = new LeaderListExportEntity();
        entity.setUnit(getStringValue(item, "unit"));
        entity.setName(getStringValue(item, "name"));
        entity.setDepartment(getStringValue(item, "department"));
        entity.setPartyPosition(getStringValue(item, "partyPosition"));
        entity.setAdminPosition(getStringValue(item, "adminPosition"));
        entity.setTenurePeriod(getStringValue(item, "tenurePeriod"));
        entity.setMainResponsibilities(getStringValue(item, "mainResponsibilities"));
        entity.setRemark(getStringValue(item, "remark"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
    
    private List<ExpenseExportEntity> convertToExpenseEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToExpenseEntity).collect(Collectors.toList());
    }

    private ExpenseExportEntity convertToExpenseEntity(Map<String, Object> item) {
        ExpenseExportEntity entity = new ExpenseExportEntity();
        entity.setExpenseType(getStringValue(item, "expenseType"));
        entity.setYear(getStringValue(item, "year"));
        entity.setFinalStatementAmount(getStringValue(item, "finalStatementAmount"));
        entity.setInitialBudgetAmount(getStringValue(item, "initialBudgetAmount"));
        entity.setChangePercentage(getStringValue(item, "changePercentage"));
        entity.setBudgetRatio(getStringValue(item, "budgetRatio"));
        entity.setRemark(getStringValue(item, "remark"));
        entity.setDataSource(getStringValue(item, "dataSource"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
}