package com.gxwebsoft.credit.controller;

import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.credit.entity.CreditSuspectedRelationship;
import com.gxwebsoft.credit.param.CreditSuspectedRelationshipImportParam;
import com.gxwebsoft.credit.param.CreditSuspectedRelationshipParam;
import com.gxwebsoft.credit.service.CreditCompanyService;
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
import com.gxwebsoft.credit.service.CreditSuspectedRelationshipService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 疑似关系控制器
 *
 * @author 科技小王子
 * @since 2026-01-07 13:52:14
 */
@Tag(name = "疑似关系管理")
@RestController
@RequestMapping("/api/credit/credit-suspected-relationship")
public class CreditSuspectedRelationshipController extends BaseController {
    @Resource
    private CreditSuspectedRelationshipService creditSuspectedRelationshipService;

    @Resource
    private BatchImportSupport batchImportSupport;

    @Resource
    private CreditCompanyService creditCompanyService;

    @Resource
    private CreditCompanyRecordCountService creditCompanyRecordCountService;

    @Operation(summary = "分页查询疑似关系")
    @GetMapping("/page")
    public ApiResult<PageResult<CreditSuspectedRelationship>> page(CreditSuspectedRelationshipParam param) {
        // 使用关联查询
        return success(creditSuspectedRelationshipService.pageRel(param));
    }

    @Operation(summary = "查询全部疑似关系")
    @GetMapping()
    public ApiResult<List<CreditSuspectedRelationship>> list(CreditSuspectedRelationshipParam param) {
        // 使用关联查询
        return success(creditSuspectedRelationshipService.listRel(param));
    }

    @Operation(summary = "根据id查询疑似关系")
    @GetMapping("/{id}")
    public ApiResult<CreditSuspectedRelationship> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(creditSuspectedRelationshipService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:save')")
    @OperationLog
    @Operation(summary = "添加疑似关系")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CreditSuspectedRelationship creditSuspectedRelationship) {
        // 记录当前登录用户id
        // User loginUser = getLoginUser();
        // if (loginUser != null) {
        // creditSuspectedRelationship.setUserId(loginUser.getUserId());
        // }
        if (creditSuspectedRelationshipService.save(creditSuspectedRelationship)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:update')")
    @OperationLog
    @Operation(summary = "修改疑似关系")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CreditSuspectedRelationship creditSuspectedRelationship) {
        if (creditSuspectedRelationshipService.updateById(creditSuspectedRelationship)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:remove')")
    @OperationLog
    @Operation(summary = "删除疑似关系")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (creditSuspectedRelationshipService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:save')")
    @OperationLog
    @Operation(summary = "批量添加疑似关系")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<CreditSuspectedRelationship> list) {
        if (creditSuspectedRelationshipService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:update')")
    @OperationLog
    @Operation(summary = "批量修改疑似关系")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CreditSuspectedRelationship> batchParam) {
        if (batchParam.update(creditSuspectedRelationshipService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:remove')")
    @OperationLog
    @Operation(summary = "批量删除疑似关系")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (creditSuspectedRelationshipService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    /**
     * 根据企业名称匹配企业并更新 companyId（匹配 CreditCompany.name / CreditCompany.matchName）
     *
     * <p>默认仅更新 companyId=0 的记录；如需覆盖更新，传 onlyNull=false。</p>
     */
    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:update')")
    @OperationLog
    @Operation(summary = "根据企业名称匹配并更新companyId")
    @PostMapping("/company-id/refresh")
    public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
        @RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
        @RequestParam(value = "limit", required = false) Integer limit
    ) {
        User loginUser = getLoginUser();
        Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;

        BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
            creditSuspectedRelationshipService,
            creditCompanyService,
            currentTenantId,
            onlyNull,
            limit,
            CreditSuspectedRelationship::getId,
            CreditSuspectedRelationship::setId,
            CreditSuspectedRelationship::getName,
            CreditSuspectedRelationship::getCompanyId,
            CreditSuspectedRelationship::setCompanyId,
            CreditSuspectedRelationship::getHasData,
            CreditSuspectedRelationship::setHasData,
            CreditSuspectedRelationship::getTenantId,
            CreditSuspectedRelationship::new
        );

        if (!stats.anyDataRead) {
            return success("无可更新数据", stats.toMap());
        }
        return success("更新完成，更新" + stats.updated + "条", stats.toMap());
    }

    /**
     * 批量导入疑似关系
     */
    @PreAuthorize("hasAuthority('credit:creditSuspectedRelationship:save')")
    @Operation(summary = "批量导入疑似关系")
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
                                               @RequestParam(value = "companyId", required = false) Integer companyId) {
        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;
        Set<Integer> touchedCompanyIds = new HashSet<>();

        try {
            ExcelImportSupport.ImportResult<CreditSuspectedRelationshipImportParam> importResult = ExcelImportSupport.readAnySheet(
                file, CreditSuspectedRelationshipImportParam.class, this::isEmptyImportRow);
            List<CreditSuspectedRelationshipImportParam> list = importResult.getData();
            int usedTitleRows = importResult.getTitleRows();
            int usedHeadRows = importResult.getHeadRows();
            int usedSheetIndex = importResult.getSheetIndex();

            if (CollectionUtils.isEmpty(list)) {
                return fail("未读取到数据，请确认模板表头与示例格式一致", null);
            }

            User loginUser = getLoginUser();
            Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
            Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
            Map<String, String> urlByName = ExcelImportSupport.readHyperlinksByHeaderKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "企业名称");

            final int chunkSize = 500;
            final int mpBatchSize = 500;
            List<CreditSuspectedRelationship> chunkItems = new ArrayList<>(chunkSize);
            List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);

            for (int i = 0; i < list.size(); i++) {
                CreditSuspectedRelationshipImportParam param = list.get(i);
                try {
                    CreditSuspectedRelationship item = convertImportParamToEntity(param);
                    if (!ImportHelper.isBlank(item.getName())) {
                        String link = urlByName.get(item.getName().trim());
                        if (link != null && !link.isEmpty()) {
                            item.setUrl(link);
                        }
                    }

                    if (item.getCompanyId() == null && companyId != null) {
                        item.setCompanyId(companyId);
                    }
                    if (item.getUserId() == null && currentUserId != null) {
                        item.setUserId(currentUserId);
                    }
                    if (item.getTenantId() == null && currentTenantId != null) {
                        item.setTenantId(currentTenantId);
                    }
                    if (item.getStatus() == null) {
                        item.setStatus(0);
                    }
                    if (item.getRecommend() == null) {
                        item.setRecommend(0);
                    }
                    if (item.getDeleted() == null) {
                        item.setDeleted(0);
                    }

                    int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
                    if (ImportHelper.isBlank(item.getName())) {
                        errorMessages.add("第" + excelRowNumber + "行：企业名称不能为空");
                        continue;
                    }
                    if (ImportHelper.isBlank(item.getRelatedParty())) {
                        errorMessages.add("第" + excelRowNumber + "行：关联方不能为空");
                        continue;
                    }

                    if (item.getCompanyId() != null && item.getCompanyId() > 0) {
                        touchedCompanyIds.add(item.getCompanyId());
                    }

                    chunkItems.add(item);
                    chunkRowNumbers.add(excelRowNumber);
                    if (chunkItems.size() >= chunkSize) {
                        successCount += batchImportSupport.persistChunkWithFallback(
                            chunkItems,
                            chunkRowNumbers,
                            () -> {
                                List<String> names = new ArrayList<>(chunkItems.size());
                                List<String> relatedParties = new ArrayList<>(chunkItems.size());
                                for (CreditSuspectedRelationship it : chunkItems) {
                                    if (it == null) {
                                        continue;
                                    }
                                    if (!ImportHelper.isBlank(it.getName())) {
                                        names.add(it.getName().trim());
                                    }
                                    if (!ImportHelper.isBlank(it.getRelatedParty())) {
                                        relatedParties.add(it.getRelatedParty().trim());
                                    }
                                }

                                List<CreditSuspectedRelationship> existingList = (names.isEmpty() || relatedParties.isEmpty())
                                    ? new ArrayList<>()
                                    : creditSuspectedRelationshipService.lambdaQuery()
                                    .in(CreditSuspectedRelationship::getName, names)
                                    .in(CreditSuspectedRelationship::getRelatedParty, relatedParties)
                                    .list();

                                java.util.Map<String, CreditSuspectedRelationship> byNameRelated = new java.util.HashMap<>();
                                java.util.Map<String, CreditSuspectedRelationship> byNameRelatedType = new java.util.HashMap<>();
                                for (CreditSuspectedRelationship existing : existingList) {
                                    if (existing == null
                                        || ImportHelper.isBlank(existing.getName())
                                        || ImportHelper.isBlank(existing.getRelatedParty())) {
                                        continue;
                                    }
                                    String n = existing.getName().trim();
                                    String r = existing.getRelatedParty().trim();
                                    byNameRelated.putIfAbsent(n + "|" + r, existing);
                                    if (!ImportHelper.isBlank(existing.getType())) {
                                        byNameRelatedType.putIfAbsent(n + "|" + r + "|" + existing.getType().trim(), existing);
                                    }
                                }

                                List<CreditSuspectedRelationship> updates = new ArrayList<>();
                                List<CreditSuspectedRelationship> inserts = new ArrayList<>();
                                for (CreditSuspectedRelationship it : chunkItems) {
                                    if (it == null
                                        || ImportHelper.isBlank(it.getName())
                                        || ImportHelper.isBlank(it.getRelatedParty())) {
                                        continue;
                                    }
                                    String n = it.getName().trim();
                                    String r = it.getRelatedParty().trim();
                                    CreditSuspectedRelationship existing;
                                    if (!ImportHelper.isBlank(it.getType())) {
                                        existing = byNameRelatedType.get(n + "|" + r + "|" + it.getType().trim());
                                    } else {
                                        existing = byNameRelated.get(n + "|" + r);
                                    }
                                    if (existing != null) {
                                        it.setId(existing.getId());
                                        updates.add(it);
                                    } else {
                                        inserts.add(it);
                                    }
                                }
                                if (!updates.isEmpty()) {
                                    creditSuspectedRelationshipService.updateBatchById(updates, mpBatchSize);
                                }
                                if (!inserts.isEmpty()) {
                                    creditSuspectedRelationshipService.saveBatch(inserts, mpBatchSize);
                                }
                                return updates.size() + inserts.size();
                            },
                            (rowItem, rowNumber) -> {
                                boolean saved = creditSuspectedRelationshipService.save(rowItem);
                                if (!saved) {
                                    CreditSuspectedRelationship existing = creditSuspectedRelationshipService.lambdaQuery()
                                        .eq(CreditSuspectedRelationship::getName, rowItem.getName())
                                        .eq(CreditSuspectedRelationship::getRelatedParty, rowItem.getRelatedParty())
                                        .eq(!ImportHelper.isBlank(rowItem.getType()), CreditSuspectedRelationship::getType, rowItem.getType())
                                        .one();
                                    if (existing != null) {
                                        rowItem.setId(existing.getId());
                                        if (creditSuspectedRelationshipService.updateById(rowItem)) {
                                            return true;
                                        }
                                    }
                                } else {
                                    return true;
                                }
                                String prefix = rowNumber > 0 ? ("第" + rowNumber + "行：") : "";
                                errorMessages.add(prefix + "保存失败");
                                return false;
                            },
                            errorMessages
                        );
                        chunkItems.clear();
                        chunkRowNumbers.clear();
                    }
                } catch (Exception e) {
                    int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
                    errorMessages.add("第" + excelRowNumber + "行：" + e.getMessage());
                    e.printStackTrace();
                }
            }

            if (!chunkItems.isEmpty()) {
                successCount += batchImportSupport.persistChunkWithFallback(
                    chunkItems,
                    chunkRowNumbers,
                    () -> {
                        List<String> names = new ArrayList<>(chunkItems.size());
                        List<String> relatedParties = new ArrayList<>(chunkItems.size());
                        for (CreditSuspectedRelationship it : chunkItems) {
                            if (it == null) {
                                continue;
                            }
                            if (!ImportHelper.isBlank(it.getName())) {
                                names.add(it.getName().trim());
                            }
                            if (!ImportHelper.isBlank(it.getRelatedParty())) {
                                relatedParties.add(it.getRelatedParty().trim());
                            }
                        }

                        List<CreditSuspectedRelationship> existingList = (names.isEmpty() || relatedParties.isEmpty())
                            ? new ArrayList<>()
                            : creditSuspectedRelationshipService.lambdaQuery()
                            .in(CreditSuspectedRelationship::getName, names)
                            .in(CreditSuspectedRelationship::getRelatedParty, relatedParties)
                            .list();

                        java.util.Map<String, CreditSuspectedRelationship> byNameRelated = new java.util.HashMap<>();
                        java.util.Map<String, CreditSuspectedRelationship> byNameRelatedType = new java.util.HashMap<>();
                        for (CreditSuspectedRelationship existing : existingList) {
                            if (existing == null
                                || ImportHelper.isBlank(existing.getName())
                                || ImportHelper.isBlank(existing.getRelatedParty())) {
                                continue;
                            }
                            String n = existing.getName().trim();
                            String r = existing.getRelatedParty().trim();
                            byNameRelated.putIfAbsent(n + "|" + r, existing);
                            if (!ImportHelper.isBlank(existing.getType())) {
                                byNameRelatedType.putIfAbsent(n + "|" + r + "|" + existing.getType().trim(), existing);
                            }
                        }

                        List<CreditSuspectedRelationship> updates = new ArrayList<>();
                        List<CreditSuspectedRelationship> inserts = new ArrayList<>();
                        for (CreditSuspectedRelationship it : chunkItems) {
                            if (it == null
                                || ImportHelper.isBlank(it.getName())
                                || ImportHelper.isBlank(it.getRelatedParty())) {
                                continue;
                            }
                            String n = it.getName().trim();
                            String r = it.getRelatedParty().trim();
                            CreditSuspectedRelationship existing;
                            if (!ImportHelper.isBlank(it.getType())) {
                                existing = byNameRelatedType.get(n + "|" + r + "|" + it.getType().trim());
                            } else {
                                existing = byNameRelated.get(n + "|" + r);
                            }
                            if (existing != null) {
                                it.setId(existing.getId());
                                updates.add(it);
                            } else {
                                inserts.add(it);
                            }
                        }
                        if (!updates.isEmpty()) {
                            creditSuspectedRelationshipService.updateBatchById(updates, mpBatchSize);
                        }
                        if (!inserts.isEmpty()) {
                            creditSuspectedRelationshipService.saveBatch(inserts, mpBatchSize);
                        }
                        return updates.size() + inserts.size();
                    },
                    (rowItem, rowNumber) -> {
                        boolean saved = creditSuspectedRelationshipService.save(rowItem);
                        if (!saved) {
                            CreditSuspectedRelationship existing = creditSuspectedRelationshipService.lambdaQuery()
                                .eq(CreditSuspectedRelationship::getName, rowItem.getName())
                                .eq(CreditSuspectedRelationship::getRelatedParty, rowItem.getRelatedParty())
                                .eq(!ImportHelper.isBlank(rowItem.getType()), CreditSuspectedRelationship::getType, rowItem.getType())
                                .one();
                            if (existing != null) {
                                rowItem.setId(existing.getId());
                                if (creditSuspectedRelationshipService.updateById(rowItem)) {
                                    return true;
                                }
                            }
                        } else {
                            return true;
                        }
                        String prefix = rowNumber > 0 ? ("第" + rowNumber + "行：") : "";
                        errorMessages.add(prefix + "保存失败");
                        return false;
                    },
                    errorMessages
                );
            }

            creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.SUSPECTED_RELATIONSHIP, touchedCompanyIds);

            if (errorMessages.isEmpty()) {
                return success("成功导入" + successCount + "条数据", null);
            } else {
                return success("导入完成，成功" + successCount + "条，失败" + errorMessages.size() + "条", errorMessages);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail("导入失败：" + e.getMessage(), null);
        }
    }

    /**
     * 下载疑似关系导入模板
     */
    @Operation(summary = "下载疑似关系导入模板")
    @GetMapping("/import/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<CreditSuspectedRelationshipImportParam> templateList = new ArrayList<>();

        CreditSuspectedRelationshipImportParam example = new CreditSuspectedRelationshipImportParam();
        example.setName("示例科技有限公司");
        example.setStatusText("存续");
        example.setLegalPerson("李四");
        example.setRegisteredCapital("1000万人民币");
        example.setCreateDate("2018-06-01");
        example.setRelatedParty("关联方示例");
        example.setType("股权关联");
        example.setDetail("疑似关系详情示例");
        example.setComments("备注信息");
        templateList.add(example);

        Workbook workbook = ExcelImportSupport.buildTemplate("疑似关系导入模板", "疑似关系", CreditSuspectedRelationshipImportParam.class, templateList);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=credit_suspected_relationship_import_template.xlsx");

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    private boolean isEmptyImportRow(CreditSuspectedRelationshipImportParam param) {
        if (param == null) {
            return true;
        }
        if (isImportHeaderRow(param)) {
            return true;
        }
        return ImportHelper.isBlank(param.getName())
            && ImportHelper.isBlank(param.getRelatedParty())
            && ImportHelper.isBlank(param.getType());
    }

    private boolean isImportHeaderRow(CreditSuspectedRelationshipImportParam param) {
        return isHeaderValue(param.getName(), "企业名称")
            || isHeaderValue(param.getRelatedParty(), "关联方")
            || isHeaderValue(param.getType(), "疑似关系类型");
    }

    private static boolean isHeaderValue(String value, String headerText) {
        if (value == null) {
            return false;
        }
        return headerText.equals(value.trim());
    }

    private CreditSuspectedRelationship convertImportParamToEntity(CreditSuspectedRelationshipImportParam param) {
        CreditSuspectedRelationship entity = new CreditSuspectedRelationship();

        entity.setName(param.getName());
        entity.setStatusText(param.getStatusText());
        entity.setLegalPerson(param.getLegalPerson());
        entity.setRegisteredCapital(param.getRegisteredCapital());
        entity.setCreateDate(param.getCreateDate());
        entity.setRelatedParty(param.getRelatedParty());
        entity.setType(param.getType());
        entity.setDetail(param.getDetail());
        entity.setComments(param.getComments());

        return entity;
    }

}
