package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiCustEnterpriseRelationAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustEnterpriseRelationEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustEnterpriseRelationQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiCustEnterpriseRelationExcel;
import com.ruoyi.info.collection.domain.vo.CcdiCustEnterpriseRelationVO;
import com.ruoyi.info.collection.domain.vo.CustEnterpriseRelationImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.service.ICcdiCustEnterpriseRelationImportService;
import com.ruoyi.info.collection.service.ICcdiCustEnterpriseRelationService;
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-12
 */
@Tag(name = "信贷客户实体关联信息管理")
@RestController
@RequestMapping("/ccdi/custEnterpriseRelation")
public class CcdiCustEnterpriseRelationController extends BaseController {

    @Resource
    private ICcdiCustEnterpriseRelationService relationService;

    @Resource
    private ICcdiCustEnterpriseRelationImportService relationImportService;

    /**
     * 查询信贷客户实体关联列表
     */
    @Operation(summary = "查询信贷客户实体关联列表")
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiCustEnterpriseRelationQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiCustEnterpriseRelationVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiCustEnterpriseRelationVO> result = relationService.selectRelationPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 获取信贷客户实体关联详细信息
     */
    @Operation(summary = "获取信贷客户实体关联详细信息")
    @Parameter(name = "id", description = "主键ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(relationService.selectRelationById(id));
    }

    /**
     * 新增信贷客户实体关联
     */
    @Operation(summary = "新增信贷客户实体关联")
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:add')")
    @Log(title = "信贷客户实体关联信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiCustEnterpriseRelationAddDTO addDTO) {
        return toAjax(relationService.insertRelation(addDTO));
    }

    /**
     * 修改信贷客户实体关联
     */
    @Operation(summary = "修改信贷客户实体关联")
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:edit')")
    @Log(title = "信贷客户实体关联信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiCustEnterpriseRelationEditDTO editDTO) {
        return toAjax(relationService.updateRelation(editDTO));
    }

    /**
     * 删除信贷客户实体关联
     */
    @Operation(summary = "删除信贷客户实体关联")
    @Parameter(name = "ids", description = "主键ID数组", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:remove')")
    @Log(title = "信贷客户实体关联信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(relationService.deleteRelationByIds(ids));
    }

    /**
     * 下载导入模板
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiCustEnterpriseRelationExcel.class, "信贷客户实体关联信息");
    }

    /**
     * 异步导入信贷客户实体关联
     */
    @Operation(summary = "异步导入信贷客户实体关联")
    @Parameter(name = "file", description = "导入文件", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:custEnterpriseRelation:import')")
    @Log(title = "信贷客户实体关联信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@Parameter(description = "导入文件") MultipartFile file) throws Exception {
        List<CcdiCustEnterpriseRelationExcel> list = EasyExcelUtil.importExcel(file.getInputStream(), CcdiCustEnterpriseRelationExcel.class);

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

        // 提交异步任务
        String taskId = relationService.importRelation(list);

        // 立即返回
        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:custEnterpriseRelation:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO statusVO = relationImportService.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:custEnterpriseRelation:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        List<CustEnterpriseRelationImportFailureVO> failures = relationImportService.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<CustEnterpriseRelationImportFailureVO> pageData = failures.subList(fromIndex, toIndex);

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