package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.*;
import com.ruoyi.info.collection.domain.excel.CcdiIntermediaryEnterpriseRelationExcel;
import com.ruoyi.info.collection.domain.excel.CcdiIntermediaryPersonExcel;
import com.ruoyi.info.collection.domain.vo.*;
import com.ruoyi.info.collection.service.ICcdiIntermediaryEnterpriseRelationImportService;
import com.ruoyi.info.collection.service.ICcdiIntermediaryPersonImportService;
import com.ruoyi.info.collection.service.ICcdiIntermediaryService;
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.util.ArrayList;
import java.util.List;

/**
 * 中介信息Controller
 *
 * @author ruoyi
 * @date 2026-02-04
 */
@Tag(name = "中介信息管理")
@RestController
@RequestMapping("/ccdi/intermediary")
public class CcdiIntermediaryController extends BaseController {

    @Resource
    private ICcdiIntermediaryService intermediaryService;

    @Resource
    private ICcdiIntermediaryPersonImportService personImportService;

    @Resource
    private ICcdiIntermediaryEnterpriseRelationImportService enterpriseRelationImportService;

    /**
     * 查询中介列表
     */
    @Operation(summary = "查询中介列表")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiIntermediaryQueryDTO queryDTO) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiIntermediaryVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiIntermediaryVO> result = intermediaryService.selectIntermediaryPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 查询个人中介详情
     */
    @Operation(summary = "查询个人中介详情")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/person/{bizId}")
    public AjaxResult getPersonInfo(@PathVariable String bizId) {
        CcdiIntermediaryPersonDetailVO vo = intermediaryService.selectIntermediaryPersonDetail(bizId);
        return success(vo);
    }

    /**
     * 查询中介亲属列表
     */
    @Operation(summary = "查询中介亲属列表")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/{bizId}/relatives")
    public AjaxResult getRelativeList(@PathVariable String bizId) {
        return success(intermediaryService.selectIntermediaryRelativeList(bizId));
    }

    /**
     * 查询中介亲属详情
     */
    @Operation(summary = "查询中介亲属详情")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/relative/{relativeBizId}")
    public AjaxResult getRelativeInfo(@PathVariable String relativeBizId) {
        return success(intermediaryService.selectIntermediaryRelativeDetail(relativeBizId));
    }

    /**
     * 查询实体中介详情
     */
    @Operation(summary = "查询实体中介详情")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/entity/{socialCreditCode}")
    public AjaxResult getEntityInfo(@PathVariable String socialCreditCode) {
        CcdiIntermediaryEntityDetailVO vo = intermediaryService.selectIntermediaryEntityDetail(socialCreditCode);
        return success(vo);
    }

    /**
     * 新增个人中介
     */
    @Operation(summary = "新增个人中介")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:add')")
    @Log(title = "个人中介", businessType = BusinessType.INSERT)
    @PostMapping("/person")
    public AjaxResult addPerson(@Validated @RequestBody CcdiIntermediaryPersonAddDTO addDTO) {
        return toAjax(intermediaryService.insertIntermediaryPerson(addDTO));
    }

    /**
     * 修改个人中介
     */
    @Operation(summary = "修改个人中介")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:edit')")
    @Log(title = "个人中介", businessType = BusinessType.UPDATE)
    @PutMapping("/person")
    public AjaxResult editPerson(@Validated @RequestBody CcdiIntermediaryPersonEditDTO editDTO) {
        return toAjax(intermediaryService.updateIntermediaryPerson(editDTO));
    }

    /**
     * 新增中介亲属
     */
    @Operation(summary = "新增中介亲属")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:add')")
    @Log(title = "中介亲属", businessType = BusinessType.INSERT)
    @PostMapping("/{bizId}/relative")
    public AjaxResult addRelative(@PathVariable String bizId, @Validated @RequestBody CcdiIntermediaryRelativeAddDTO addDTO) {
        return toAjax(intermediaryService.insertIntermediaryRelative(bizId, addDTO));
    }

    /**
     * 修改中介亲属
     */
    @Operation(summary = "修改中介亲属")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:edit')")
    @Log(title = "中介亲属", businessType = BusinessType.UPDATE)
    @PutMapping("/relative")
    public AjaxResult editRelative(@Validated @RequestBody CcdiIntermediaryRelativeEditDTO editDTO) {
        return toAjax(intermediaryService.updateIntermediaryRelative(editDTO));
    }

    /**
     * 新增实体中介
     */
    @Operation(summary = "新增实体中介")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:add')")
    @Log(title = "实体中介", businessType = BusinessType.INSERT)
    @PostMapping("/entity")
    public AjaxResult addEntity(@Validated @RequestBody CcdiIntermediaryEntityAddDTO addDTO) {
        return toAjax(intermediaryService.insertIntermediaryEntity(addDTO));
    }

    /**
     * 修改实体中介
     */
    @Operation(summary = "修改实体中介")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:edit')")
    @Log(title = "实体中介", businessType = BusinessType.UPDATE)
    @PutMapping("/entity")
    public AjaxResult editEntity(@Validated @RequestBody CcdiIntermediaryEntityEditDTO editDTO) {
        return toAjax(intermediaryService.updateIntermediaryEntity(editDTO));
    }

    /**
     * 查询中介关联机构列表
     */
    @Operation(summary = "查询中介关联机构列表")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/{bizId}/enterprise-relations")
    public AjaxResult getEnterpriseRelationList(@PathVariable String bizId) {
        return success(intermediaryService.selectIntermediaryEnterpriseRelationList(bizId));
    }

    /**
     * 查询中介关联机构详情
     */
    @Operation(summary = "查询中介关联机构详情")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:query')")
    @GetMapping("/enterprise-relation/{id}")
    public AjaxResult getEnterpriseRelationInfo(@PathVariable Long id) {
        return success(intermediaryService.selectIntermediaryEnterpriseRelationDetail(id));
    }

    /**
     * 新增中介关联机构
     */
    @Operation(summary = "新增中介关联机构")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:add')")
    @Log(title = "中介关联机构", businessType = BusinessType.INSERT)
    @PostMapping("/{bizId}/enterprise-relation")
    public AjaxResult addEnterpriseRelation(@PathVariable String bizId,
                                            @Validated @RequestBody CcdiIntermediaryEnterpriseRelationAddDTO addDTO) {
        return toAjax(intermediaryService.insertIntermediaryEnterpriseRelation(bizId, addDTO));
    }

    /**
     * 修改中介关联机构
     */
    @Operation(summary = "修改中介关联机构")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:edit')")
    @Log(title = "中介关联机构", businessType = BusinessType.UPDATE)
    @PutMapping("/enterprise-relation")
    public AjaxResult editEnterpriseRelation(@Validated @RequestBody CcdiIntermediaryEnterpriseRelationEditDTO editDTO) {
        return toAjax(intermediaryService.updateIntermediaryEnterpriseRelation(editDTO));
    }

    /**
     * 删除中介
     */
    @Operation(summary = "删除中介")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:remove')")
    @Log(title = "中介信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(intermediaryService.deleteIntermediaryByIds(ids));
    }

    /**
     * 删除中介亲属
     */
    @Operation(summary = "删除中介亲属")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:remove')")
    @Log(title = "中介亲属", businessType = BusinessType.DELETE)
    @DeleteMapping("/relative/{relativeBizId}")
    public AjaxResult removeRelative(@PathVariable String relativeBizId) {
        return toAjax(intermediaryService.deleteIntermediaryRelative(relativeBizId));
    }

    /**
     * 删除中介关联机构
     */
    @Operation(summary = "删除中介关联机构")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:remove')")
    @Log(title = "中介关联机构", businessType = BusinessType.DELETE)
    @DeleteMapping("/enterprise-relation/{id}")
    public AjaxResult removeEnterpriseRelation(@PathVariable Long id) {
        return toAjax(intermediaryService.deleteIntermediaryEnterpriseRelation(id));
    }

    /**
     * 校验人员ID唯一性
     */
    @Operation(summary = "校验人员ID唯一性")
    @GetMapping("/checkPersonIdUnique")
    public AjaxResult checkPersonIdUnique(@RequestParam String personId, @RequestParam(required = false) String bizId) {
        boolean unique = intermediaryService.checkPersonIdUnique(personId, bizId);
        return success(unique);
    }

    /**
     * 校验统一社会信用代码唯一性
     */
    @Operation(summary = "校验统一社会信用代码唯一性")
    @GetMapping("/checkSocialCreditCodeUnique")
    public AjaxResult checkSocialCreditCodeUnique(@RequestParam String socialCreditCode, @RequestParam(required = false) String excludeId) {
        boolean unique = intermediaryService.checkSocialCreditCodeUnique(socialCreditCode, excludeId);
        return success(unique);
    }

    /**
     * 下载个人中介导入模板
     */
    @Operation(summary = "下载个人中介导入模板")
    @PostMapping("/importPersonTemplate")
    public void importPersonTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiIntermediaryPersonExcel.class, "个人中介信息");
    }

    /**
     * 下载实体中介导入模板
     */
    @Operation(summary = "下载中介实体关联关系导入模板")
    @PostMapping("/importEnterpriseRelationTemplate")
    public void importEnterpriseRelationTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiIntermediaryEnterpriseRelationExcel.class, "中介实体关联关系信息");
    }

    /**
     * 导入个人中介数据(异步)
     */
    @Operation(summary = "导入个人中介数据")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @Log(title = "个人中介", businessType = BusinessType.IMPORT)
    @PostMapping("/importPersonData")
    public AjaxResult importPersonData(MultipartFile file) throws Exception {
        List<CcdiIntermediaryPersonExcel> list = EasyExcelUtil.importExcel(
            file.getInputStream(), CcdiIntermediaryPersonExcel.class);

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

        // 提交异步任务
        String taskId = intermediaryService.importIntermediaryPerson(list);

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

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

    /**
     * 导入实体中介数据(异步)
     */
    @Operation(summary = "导入中介实体关联关系数据")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @Log(title = "中介实体关联关系", businessType = BusinessType.IMPORT)
    @PostMapping("/importEnterpriseRelationData")
    public AjaxResult importEnterpriseRelationData(MultipartFile file) throws Exception {
        List<CcdiIntermediaryEnterpriseRelationExcel> list = EasyExcelUtil.importExcel(
            file.getInputStream(), CcdiIntermediaryEnterpriseRelationExcel.class);

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

        String taskId = intermediaryService.importIntermediaryEnterpriseRelation(list);

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

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

    /**
     * 查询个人中介导入状态
     */
    @Operation(summary = "查询个人中介导入状态")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @GetMapping("/importPersonStatus/{taskId}")
    public AjaxResult getPersonImportStatus(@PathVariable String taskId) {
        try {
            ImportStatusVO status = personImportService.getImportStatus(taskId);
            return success(status);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询个人中介导入失败记录
     */
    @Operation(summary = "查询个人中介导入失败记录")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @GetMapping("/importPersonFailures/{taskId}")
    public TableDataInfo getPersonImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

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

    /**
     * 查询实体中介导入状态
     */
    @Operation(summary = "查询中介实体关联关系导入状态")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @GetMapping("/importEnterpriseRelationStatus/{taskId}")
    public AjaxResult getEnterpriseRelationImportStatus(@PathVariable String taskId) {
        try {
            ImportStatusVO status = enterpriseRelationImportService.getImportStatus(taskId);
            return success(status);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询中介实体关联关系导入失败记录
     */
    @Operation(summary = "查询中介实体关联关系导入失败记录")
    @PreAuthorize("@ss.hasPermi('ccdi:intermediary:import')")
    @GetMapping("/importEnterpriseRelationFailures/{taskId}")
    public TableDataInfo getEnterpriseRelationImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

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