package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiCustFmyRelationQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiCustFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.CcdiCustFmyRelationVO;
import com.ruoyi.info.collection.domain.vo.CustFmyRelationImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.service.ICcdiCustFmyRelationImportService;
import com.ruoyi.info.collection.service.ICcdiCustFmyRelationService;
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.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.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 信贷客户家庭关系Controller
 *
 * @author ruoyi
 * @date 2026-02-11
 */
@Tag(name = "信贷客户家庭关系管理")
@RestController
@RequestMapping("/ccdi/custFmyRelation")
public class CcdiCustFmyRelationController extends BaseController {

    @Resource
    private ICcdiCustFmyRelationService relationService;

    @Resource
    private ICcdiCustFmyRelationImportService relationImportService;

    /**
     * 查询信贷客户家庭关系列表
     */
    @Operation(summary = "查询信贷客户家庭关系列表")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:query')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiCustFmyRelationQueryDTO query) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiCustFmyRelationVO> page = relationService.selectRelationPage(
                query, pageDomain.getPageNum(), pageDomain.getPageSize());
        return getDataTable(page.getRecords(), page.getTotal());
    }

    /**
     * 根据ID查询信贷客户家庭关系详情
     */
    @Operation(summary = "查询信贷客户家庭关系详情")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CcdiCustFmyRelationVO relation = relationService.selectRelationById(id);
        return success(relation);
    }

    /**
     * 新增信贷客户家庭关系
     */
    @Operation(summary = "新增信贷客户家庭关系")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:add')")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiCustFmyRelationAddDTO addDTO) {
        return toAjax(relationService.insertRelation(addDTO));
    }

    /**
     * 修改信贷客户家庭关系
     */
    @Operation(summary = "修改信贷客户家庭关系")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiCustFmyRelationEditDTO editDTO) {
        return toAjax(relationService.updateRelation(editDTO));
    }

    /**
     * 删除信贷客户家庭关系
     */
    @Operation(summary = "删除信贷客户家庭关系")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(relationService.deleteRelationByIds(ids));
    }

    /**
     * 下载带字典下拉框的导入模板
     * 使用@DictDropdown注解自动添加下拉框
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiCustFmyRelationExcel.class, "信贷客户家庭关系");
    }

    /**
     * 异步导入信贷客户家庭关系
     */
    @Operation(summary = "异步导入信贷客户家庭关系")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:import')")
    @Log(title = "信贷客户家庭关系", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        List<CcdiCustFmyRelationExcel> excels = EasyExcelUtil.importExcel(
                file.getInputStream(),
                CcdiCustFmyRelationExcel.class
        );

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

        // 提交异步任务
        String taskId = relationService.importRelations(excels);

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

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

    /**
     * 查询导入状态
     */
    @Operation(summary = "查询导入状态")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:query')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable("taskId") String taskId) {
        ImportStatusVO statusVO = relationImportService.getImportStatus(taskId);
        return success(statusVO);
    }

    /**
     * 查询导入失败记录
     */
    @Operation(summary = "查询导入失败记录")
    @PreAuthorize("@ss.hasPermi('ccdi:custFmyRelation:query')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable("taskId") String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

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