package com.gxwebsoft.ai.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.dto.AuditContentRequest;
import com.gxwebsoft.ai.dto.export.PersonnelExportEntity;
import com.gxwebsoft.ai.service.AuditContent9PersonnelService;
import com.gxwebsoft.common.core.web.ApiResult;

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;

/**
 * 审计内容9控制器 - 人员编制管理审计
 */
@Slf4j
@Tag(name = "审计内容9-人员编制管理审计")
@RestController
@RequestMapping("/api/ai/auditContent9")
public class AuditContent9Controller extends BaseAuditContentController {
    
    @Autowired
    private AuditContent9PersonnelService auditContent9PersonnelService;
    
    /**
     * 生成人员编制管理审计表数据
     */
    @Operation(summary = "生成人员编制管理审计表")
    @PostMapping("/generatePersonnelTable")
    public ApiResult<?> generatePersonnelTable(@RequestBody AuditContentRequest request, HttpServletRequest servletRequest) {
        return generateTableData(request, servletRequest.getRequestURI(), 
            (params) -> auditContent9PersonnelService.generatePersonnelTableData(
                params.knowledgeBaseId, params.libraryKbIds, params.projectLibrary,
                params.username, params.history, params.suggestion
            ));
    }
    
    /**
     * 导出人员编制管理审计表到Excel
     */
    @Operation(summary = "导出人员编制管理审计表到Excel")
    @PostMapping("/exportPersonnelTable")
    public void exportPersonnelTable(@RequestBody Map<String, Object> request, HttpServletResponse response) {
        exportToExcel(request, response, "人员编制管理审计表", 
            this::convertToPersonnelEntityList, PersonnelExportEntity.class);
    }
    
    // ========== 数据转换方法 ==========
    
    private List<PersonnelExportEntity> convertToPersonnelEntityList(List<Map<String, Object>> originalData) {
        return originalData.stream().map(this::convertToPersonnelEntity).collect(Collectors.toList());
    }
    
    private PersonnelExportEntity convertToPersonnelEntity(Map<String, Object> item) {
        PersonnelExportEntity entity = new PersonnelExportEntity();
        entity.setIndex(getStringValue(item, "index"));
        entity.setAuditContent(getStringValue(item, "auditContent"));
        entity.setAuditTarget(getStringValue(item, "auditTarget"));
        entity.setAuditEvidence(getStringValue(item, "auditEvidence"));
        entity.setGenerationResult(getStringValue(item, "generationResult"));
        entity.setWorkPaperIndex(formatWorkPaperIndex(item.get("workPaperIndex")));
        return entity;
    }
}