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.CreditJudicialDocument;
import com.gxwebsoft.credit.param.CreditJudicialDocumentImportParam;
import com.gxwebsoft.credit.param.CreditJudicialDocumentParam;
import com.gxwebsoft.credit.service.CreditCompanyService;
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
import com.gxwebsoft.credit.service.CreditJudicialDocumentService;
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 2025-12-19 19:51:03
 */
@Tag(name = "裁判文书司法大数据管理")
@RestController
@RequestMapping("/api/credit/credit-judicial-document")
public class CreditJudicialDocumentController extends BaseController {
    @Resource
    private CreditJudicialDocumentService creditJudicialDocumentService;

    @Resource
    private BatchImportSupport batchImportSupport;

    @Resource
    private CreditCompanyService creditCompanyService;

    @Resource
    private CreditCompanyRecordCountService creditCompanyRecordCountService;

    @Operation(summary = "分页查询裁判文书司法大数据")
    @GetMapping("/page")
    public ApiResult<PageResult<CreditJudicialDocument>> page(CreditJudicialDocumentParam param) {
        // 使用关联查询
        return success(creditJudicialDocumentService.pageRel(param));
    }

    @Operation(summary = "查询全部裁判文书司法大数据")
    @GetMapping()
    public ApiResult<List<CreditJudicialDocument>> list(CreditJudicialDocumentParam param) {
        // 使用关联查询
        return success(creditJudicialDocumentService.listRel(param));
    }

    @Operation(summary = "根据id查询裁判文书司法大数据")
    @GetMapping("/{id}")
    public ApiResult<CreditJudicialDocument> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(creditJudicialDocumentService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:save')")
    @OperationLog
    @Operation(summary = "添加裁判文书司法大数据")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CreditJudicialDocument creditJudicialDocument) {
        // 记录当前登录用户id
        // User loginUser = getLoginUser();
        // if (loginUser != null) {
        // creditJudicialDocument.setUserId(loginUser.getUserId());
        // }
        if (creditJudicialDocumentService.save(creditJudicialDocument)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:update')")
    @OperationLog
    @Operation(summary = "修改裁判文书司法大数据")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CreditJudicialDocument creditJudicialDocument) {
        if (creditJudicialDocumentService.updateById(creditJudicialDocument)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:remove')")
    @OperationLog
    @Operation(summary = "删除裁判文书司法大数据")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (batchImportSupport.hardRemoveById(CreditJudicialDocument.class, id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:save')")
    @OperationLog
    @Operation(summary = "批量添加裁判文书司法大数据")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<CreditJudicialDocument> list) {
        if (creditJudicialDocumentService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:update')")
    @OperationLog
    @Operation(summary = "批量修改裁判文书司法大数据")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CreditJudicialDocument> batchParam) {
        if (batchParam.update(creditJudicialDocumentService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:remove')")
    @OperationLog
    @Operation(summary = "批量删除裁判文书司法大数据")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (batchImportSupport.hardRemoveByIds(CreditJudicialDocument.class, ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    /**
     * 根据“当事人/第三人”文本中包含的企业名称匹配企业并更新 companyId（匹配 CreditCompany.name / CreditCompany.matchName）
     *
     * <p>默认仅更新 companyId=0 的记录；如需覆盖更新，传 onlyNull=false。</p>
     */
    @PreAuthorize("hasAuthority('credit:creditJudicialDocument: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.refreshCompanyIdByCompanyNameContainedInText(
            creditJudicialDocumentService,
            creditCompanyService,
            currentTenantId,
            onlyNull,
            limit,
            CreditJudicialDocument::getId,
            CreditJudicialDocument::setId,
            CreditJudicialDocument::getCompanyId,
            CreditJudicialDocument::setCompanyId,
            CreditJudicialDocument::getHasData,
            CreditJudicialDocument::setHasData,
            CreditJudicialDocument::getTenantId,
            CreditJudicialDocument::new,
            // 需求：otherPartiesThirdParty 字段包含企业名称时，回填 companyId
            CreditJudicialDocument::getOtherPartiesThirdParty
        );

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

    /**
     * 批量导入裁判文书司法大数据
     */
    @PreAuthorize("hasAuthority('credit:creditJudicialDocument: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 {
            // 支持按选项卡名称导入：默认读取“裁判文书”sheet（不存在则回退到第 0 个sheet）
            int sheetIndex = ExcelImportSupport.findSheetIndex(file, "裁判文书", 0);
            ExcelImportSupport.ImportResult<CreditJudicialDocumentImportParam> importResult = ExcelImportSupport.read(
                file, CreditJudicialDocumentImportParam.class, this::isEmptyImportRow, sheetIndex);
            List<CreditJudicialDocumentImportParam> 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> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
            Map<String, String> urlByTitle = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "文书标题");

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

            for (int i = 0; i < list.size(); i++) {
                CreditJudicialDocumentImportParam param = list.get(i);
                try {
                    CreditJudicialDocument item = convertImportParamToEntity(param);
                    String link = null;
                    if (!ImportHelper.isBlank(item.getCaseNumber())) {
                        link = urlByCaseNumber.get(item.getCaseNumber().trim());
                    }
                    if (ImportHelper.isBlank(link) && !ImportHelper.isBlank(item.getTitle())) {
                        link = urlByTitle.get(item.getTitle().trim());
                    }
                    if (!ImportHelper.isBlank(link)) {
                        item.setUrl(link.trim());
                    }

                    if (item.getCompanyId() == null && companyId != null) {
                        item.setCompanyId(companyId);
                    }
                    if (item.getCompanyId() != null && item.getCompanyId() > 0) {
                        touchedCompanyIds.add(item.getCompanyId());
                    }
                    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.getCaseNumber())) {
                        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.persistInsertOnlyChunk(
                            creditJudicialDocumentService,
                            chunkItems,
                            chunkRowNumbers,
                            mpBatchSize,
                            CreditJudicialDocument::getCaseNumber,
                            "",
                            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.persistInsertOnlyChunk(
                    creditJudicialDocumentService,
                    chunkItems,
                    chunkRowNumbers,
                    mpBatchSize,
                    CreditJudicialDocument::getCaseNumber,
                    "",
                    errorMessages
                );
            }

            creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.JUDICIAL_DOCUMENT, 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);
        }
    }

    /**
     * 批量导入历史裁判文书（仅解析“历史裁判文书”选项卡）
     * 规则：使用数据库唯一索引约束，重复数据不导入。
     */
    @PreAuthorize("hasAuthority('credit:creditJudicialDocument:save')")
    @Operation(summary = "批量导入历史裁判文书司法大数据")
    @PostMapping("/import/history")
    public ApiResult<List<String>> importHistoryBatch(@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 {
            int sheetIndex = ExcelImportSupport.findSheetIndex(file, "历史裁判文书");
            if (sheetIndex < 0) {
                return fail("未读取到数据，请确认文件中存在“历史裁判文书”选项卡且表头与示例格式一致", null);
            }

            ExcelImportSupport.ImportResult<CreditJudicialDocumentImportParam> importResult = ExcelImportSupport.read(
                file, CreditJudicialDocumentImportParam.class, this::isEmptyImportRow, sheetIndex);
            List<CreditJudicialDocumentImportParam> 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> urlByCaseNumber = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "案号");
            Map<String, String> urlByTitle = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "文书标题");

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

            for (int i = 0; i < list.size(); i++) {
                CreditJudicialDocumentImportParam param = list.get(i);
                int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
                try {
                    CreditJudicialDocument item = convertImportParamToEntity(param);
                    if (item.getCaseNumber() != null) {
                        item.setCaseNumber(item.getCaseNumber().trim());
                    }
                    if (ImportHelper.isBlank(item.getCaseNumber())) {
                        errorMessages.add("第" + excelRowNumber + "行：案号不能为空");
                        continue;
                    }

                    String link = null;
                    if (!ImportHelper.isBlank(item.getCaseNumber())) {
                        link = urlByCaseNumber.get(item.getCaseNumber());
                    }
                    if (ImportHelper.isBlank(link) && !ImportHelper.isBlank(item.getTitle())) {
                        link = urlByTitle.get(item.getTitle().trim());
                    }
                    if (!ImportHelper.isBlank(link)) {
                        item.setUrl(link.trim());
                    }

                    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.getDeleted() == null) {
                        item.setDeleted(0);
                    }
                    // 历史导入的数据统一标记为“失效”
                    item.setDataStatus("失效");

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

                    chunkItems.add(item);
                    chunkRowNumbers.add(excelRowNumber);
                    if (chunkItems.size() >= chunkSize) {
                        successCount += batchImportSupport.persistInsertOnlyChunk(
                            creditJudicialDocumentService,
                            chunkItems,
                            chunkRowNumbers,
                            mpBatchSize,
                            CreditJudicialDocument::getCaseNumber,
                            "",
                            errorMessages
                        );
                        chunkItems.clear();
                        chunkRowNumbers.clear();
                    }
                } catch (Exception e) {
                    errorMessages.add("第" + excelRowNumber + "行：" + e.getMessage());
                    e.printStackTrace();
                }
            }

            if (!chunkItems.isEmpty()) {
                successCount += batchImportSupport.persistInsertOnlyChunk(
                    creditJudicialDocumentService,
                    chunkItems,
                    chunkRowNumbers,
                    mpBatchSize,
                    CreditJudicialDocument::getCaseNumber,
                    "",
                    errorMessages
                );
            }

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

            if (errorMessages.isEmpty()) {
                return success("成功导入" + successCount + "条数据", null);
            }
            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<CreditJudicialDocumentImportParam> templateList = new ArrayList<>();

        CreditJudicialDocumentImportParam example = new CreditJudicialDocumentImportParam();
        example.setTitle("裁判文书");
        example.setOtherPartiesThirdParty("第三人示例");
        example.setOccurrenceTime("2024-01-01");
        example.setCaseNumber("（2024）示例案号");
        example.setCauseOfAction("案由示例");
        example.setInvolvedAmount("100000");
        example.setDefendantAppellee("裁判结果示例");
        example.setCourtName("示例法院");
        example.setReleaseDate("2024-01-02");
        example.setComments("备注信息");
        templateList.add(example);

        Workbook workbook = ExcelImportSupport.buildTemplate("裁判文书导入模板", "裁判文书", CreditJudicialDocumentImportParam.class, templateList);

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

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

    private boolean isEmptyImportRow(CreditJudicialDocumentImportParam param) {
        if (param == null) {
            return true;
        }
        return ImportHelper.isBlank(param.getCaseNumber());
    }

    private CreditJudicialDocument convertImportParamToEntity(CreditJudicialDocumentImportParam param) {
        CreditJudicialDocument entity = new CreditJudicialDocument();

      String involvedAmount = !ImportHelper.isBlank(param.getInvolvedAmount2())
        ? param.getInvolvedAmount2()
        : param.getInvolvedAmount();

        entity.setTitle(param.getTitle());
        entity.setDocumentType(param.getDocumentType());
        entity.setDataStatus(param.getDataStatus());
        entity.setOtherPartiesThirdParty(param.getOtherPartiesThirdParty());
        entity.setOccurrenceTime(param.getOccurrenceTime());
        entity.setCaseNumber(param.getCaseNumber());
        entity.setCauseOfAction(param.getCauseOfAction());
        entity.setInvolvedAmount(involvedAmount);
        // Excel导入字段映射补全：否则对应数据库字段(defendant_appellee/release_date)会一直为空
        entity.setDefendantAppellee(param.getDefendantAppellee());
        entity.setReleaseDate(param.getReleaseDate());
        entity.setCourtName(param.getCourtName());
        entity.setComments(param.getComments());
      System.out.println("entity = " + entity);
        return entity;
    }

}
