package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiPurchaseTransactionAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiPurchaseTransactionEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiPurchaseTransactionQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiPurchaseTransactionExcel;
import com.ruoyi.info.collection.domain.excel.CcdiPurchaseTransactionSupplierExcel;
import com.ruoyi.info.collection.domain.vo.CcdiPurchaseTransactionVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.PurchaseTransactionImportFailureVO;
import com.ruoyi.info.collection.service.ICcdiPurchaseTransactionImportService;
import com.ruoyi.info.collection.service.ICcdiPurchaseTransactionService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 招投标信息维护Controller
 *
 * @author ruoyi
 * @date 2026-02-06
 */
@Tag(name = "招投标信息维护")
@RestController
@RequestMapping("/ccdi/purchaseTransaction")
public class CcdiPurchaseTransactionController extends BaseController {

    @Resource
    private ICcdiPurchaseTransactionService transactionService;

    @Resource
    private ICcdiPurchaseTransactionImportService transactionImportService;

    /**
     * 查询招投标信息列表
     */
    @Operation(summary = "查询招投标信息列表")
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiPurchaseTransactionQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiPurchaseTransactionVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiPurchaseTransactionVO> result = transactionService.selectTransactionPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 获取招投标信息详细信息
     */
    @Operation(summary = "获取招投标信息详细信息")
    @Parameter(name = "purchaseId", description = "采购事项ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:query')")
    @GetMapping(value = "/{purchaseId}")
    public AjaxResult getInfo(@PathVariable String purchaseId) {
        return success(transactionService.selectTransactionById(purchaseId));
    }

    /**
     * 新增招投标信息
     */
    @Operation(summary = "新增招投标信息")
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:add')")
    @Log(title = "招投标信息维护", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiPurchaseTransactionAddDTO addDTO) {
        return toAjax(transactionService.insertTransaction(addDTO));
    }

    /**
     * 修改招投标信息
     */
    @Operation(summary = "修改招投标信息")
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:edit')")
    @Log(title = "招投标信息维护", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiPurchaseTransactionEditDTO editDTO) {
        return toAjax(transactionService.updateTransaction(editDTO));
    }

    /**
     * 删除招投标信息
     */
    @Operation(summary = "删除招投标信息")
    @Parameter(name = "purchaseIds", description = "采购事项ID数组", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:remove')")
    @Log(title = "招投标信息维护", businessType = BusinessType.DELETE)
    @DeleteMapping("/{purchaseIds}")
    public AjaxResult remove(@PathVariable String[] purchaseIds) {
        return toAjax(transactionService.deleteTransactionByIds(purchaseIds));
    }

    /**
     * 下载双Sheet导入模板
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(
            response,
            CcdiPurchaseTransactionExcel.class,
            "招投标主信息",
            CcdiPurchaseTransactionSupplierExcel.class,
            "供应商明细",
            "招投标信息维护导入模板"
        );
    }

    /**
     * 异步导入招投标信息
     */
    @Operation(summary = "异步导入招投标信息")
    @Parameter(name = "file", description = "导入文件", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:import')")
    @Log(title = "招投标信息维护", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@Parameter(description = "导入文件") MultipartFile file) throws Exception {
        List<CcdiPurchaseTransactionExcel> mainList = EasyExcelUtil.importExcel(
            file.getInputStream(),
            CcdiPurchaseTransactionExcel.class,
            "招投标主信息"
        );
        List<CcdiPurchaseTransactionSupplierExcel> supplierList = EasyExcelUtil.importExcel(
            file.getInputStream(),
            CcdiPurchaseTransactionSupplierExcel.class,
            "供应商明细"
        );

        if ((mainList == null || mainList.isEmpty()) && (supplierList == null || supplierList.isEmpty())) {
            return error("至少需要一条数据");
        }

        // 提交异步任务
        String taskId = transactionService.importTransaction(mainList, supplierList);

        // 立即返回,不等待后台任务完成
        ImportResultVO result = new ImportResultVO();
        result.setTaskId(taskId);
        result.setStatus("PROCESSING");
        result.setMessage("导入任务已提交,正在后台处理");

        return AjaxResult.success("导入任务已提交,正在后台处理", result);
    }

    /**
     * 查询导入状态
     */
    @Operation(summary = "查询导入状态")
    @Parameter(name = "taskId", description = "任务ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO statusVO = transactionImportService.getImportStatus(taskId);
        return success(statusVO);
    }

    /**
     * 查询导入失败记录
     */
    @Operation(summary = "查询导入失败记录")
    @Parameter(name = "taskId", description = "任务ID", required = true)
    @Parameter(name = "pageNum", description = "页码", required = false)
    @Parameter(name = "pageSize", description = "每页条数", required = false)
    @PreAuthorize("@ss.hasPermi('ccdi:purchaseTransaction:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        List<PurchaseTransactionImportFailureVO> failures = transactionImportService.getImportFailures(taskId);

        // 手动分页
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, failures.size());

        // 检查 fromIndex 是否超出范围
        if (fromIndex >= failures.size()) {
            return getDataTable(new ArrayList<>(), failures.size());
        }

        List<PurchaseTransactionImportFailureVO> pageData = failures.subList(fromIndex, toIndex);

        return getDataTable(pageData, failures.size());
    }
}
