package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.entity.User;
import com.xy.xyaicpzs.service.ExcelImportService;
import com.xy.xyaicpzs.service.OperationHistoryService;
import com.xy.xyaicpzs.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * Excel数据导入控制器
 */
@Slf4j
@RestController
@RequestMapping("/excel")
@Tag(name = "Excel数据导入", description = "Excel数据导入相关接口")
public class ExcelImportController {

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private UserService userService;

    @Autowired
    private OperationHistoryService operationHistoryService;

    /**
     * 上传Excel文件并导入数据
     */
    @PostMapping("/upload")
    @Operation(summary = "上传Excel文件导入数据", description = "上传包含T1、T2、T3、T4、T5、T6和T7 sheet的Excel文件，将红球、蓝球、线系数和面系数数据分别导入到十二个数据库表中")
    public ApiResponse<String> uploadExcelFile(
            @Parameter(description = "Excel文件(.xlsx格式)", required = true)
            @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        if (!userService.isAdmin(loginUser)){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "无权限");
        }
        Long userId = loginUser.getId();
        String userName = loginUser.getUserName();
        
        String fileName = file.getOriginalFilename();
        log.info("接收到Excel文件上传请求，文件名：{}", fileName);
        
        try {
            String message = excelImportService.importExcelFile(file);
            
            // 记录操作历史 - 成功
            String resultMessage = String.format("%s成功上传并导入双色球Excel文件：%s，导入结果：%s", userName, fileName, message);
            operationHistoryService.recordOperation(userId, "双色球Excel数据导入", 1, "成功", resultMessage);
            
            return ResultUtils.success(message);
        } catch (Exception e) {
            log.error("双色球Excel文件导入失败，文件名：{}，错误：{}", fileName, e.getMessage(), e);
            
            // 记录操作历史 - 失败
            String resultMessage = String.format("%s双色球Excel文件导入失败：%s，文件名：%s，错误原因：%s", userName, fileName, fileName, e.getMessage());
            operationHistoryService.recordOperation(userId, "双色球Excel数据导入", 1, "失败", resultMessage);
            
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "双色球Excel文件导入失败：" + e.getMessage());
        }
    }

    /**
     * 上传Excel文件并导入开奖数据
     */
    @PostMapping("/upload-lottery-draws")
    @Operation(summary = "上传Excel文件导入开奖数据", description = "上传包含T10工作表的Excel文件，只导入开奖数据到lottery_draws表")
    public ApiResponse<String> uploadLotteryDrawsFile(
            @Parameter(description = "包含T10工作表的Excel文件(.xlsx格式)", required = true)
            @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        if (!userService.isAdmin(loginUser)){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "无权限");
        }
        Long userId = loginUser.getId();
        String userName = loginUser.getUserName();
        
        String fileName = file.getOriginalFilename();
        log.info("接收到开奖数据上传请求，文件名：{}", fileName);
        
        try {
            String message = excelImportService.importLotteryDrawsFile(file);
            
            // 记录操作历史 - 成功
            String resultMessage = String.format("%s成功上传并导入双色球开奖数据文件：%s，导入结果：%s", userName, fileName, message);
            operationHistoryService.recordOperation(userId, "双色球开奖数据导入", 1, "成功", resultMessage);
            
            return ResultUtils.success(message);
        } catch (Exception e) {
            log.error("开奖数据文件导入失败，文件名：{}，错误：{}", fileName, e.getMessage(), e);
            
            // 记录操作历史 - 失败
            String resultMessage = String.format("%s双色球开奖数据文件导入失败：%s，文件名：%s，错误原因：%s", userName, fileName, fileName, e.getMessage());
            operationHistoryService.recordOperation(userId, "双色球开奖数据导入", 1, "失败", resultMessage);
            
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "双色球开奖数据文件导入失败：" + e.getMessage());
        }
    }

    /**
     * 上传Excel文件并追加导入开奖数据
     */
    @PostMapping("/append-lottery-draws")
    @Operation(summary = "上传Excel文件追加导入开奖数据", description = "上传包含T10工作表的Excel文件，追加导入开奖数据（不清空现有数据，跳过重复期号）")
    public ApiResponse<String> appendLotteryDrawsFile(
            @Parameter(description = "包含T10工作表的Excel文件(.xlsx格式)", required = true)
            @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        if (!userService.isAdmin(loginUser)){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "无权限");
        }
        Long userId = loginUser.getId();
        String userName = loginUser.getUserName();
        
        String fileName = file.getOriginalFilename();
        log.info("接收到开奖数据追加上传请求，文件名：{}", fileName);
        
        try {
            String message = excelImportService.appendLotteryDrawsFile(file);
            
            // 记录操作历史 - 成功
            String resultMessage = String.format("%s成功追加导入双色球开奖数据文件：%s，导入结果：%s", userName, fileName, message);
            operationHistoryService.recordOperation(userId, "双色球开奖数据追加导入", 1, "成功", resultMessage);
            
            return ResultUtils.success(message);
        } catch (Exception e) {
            log.error("开奖数据追加导入失败，文件名：{}，错误：{}", fileName, e.getMessage(), e);
            
            // 记录操作历史 - 失败
            String resultMessage = String.format("%s双色球开奖数据追加导入失败：%s，文件名：%s，错误原因：%s", userName, fileName, fileName, e.getMessage());
            operationHistoryService.recordOperation(userId, "双色球开奖数据追加导入", 1, "失败", resultMessage);
            
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "双色球开奖数据追加导入失败：" + e.getMessage());
        }
    }

    /**
     * 获取导入说明
     */
    @GetMapping("/import-info")
    @Operation(summary = "获取导入说明", description = "获取Excel数据导入的详细说明")
    public String getImportInfo() {
        return excelImportService.getImportInfo();
    }
} 