package com.kingdee.eas.custom.integration.riskcontrol.controller;

import com.kingdee.eas.custom.integration.base.annotation.ApiDoc;
import com.kingdee.eas.custom.integration.base.controller.AbstractIntegrationController;
import com.kingdee.eas.custom.integration.base.dto.ApiResult;
import com.kingdee.eas.custom.integration.riskcontrol.dto.BatchComplaintDonationDeductRequest;
import com.kingdee.eas.custom.integration.riskcontrol.dto.ComplaintDonationDeductResponse;
import com.kingdee.eas.custom.integration.riskcontrol.service.ComplaintDonationDeductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 风控平台数据同步接口。
 * X-Api-Secret 认证，返回 200 并支持部分成功。
 */
@RestController
@RequestMapping("/risk-control")
public class RiskControlSyncController extends AbstractIntegrationController {

    @Autowired
    private ComplaintDonationDeductService complaintDonationDeductService;

    /**
     * 投诉乐捐扣除批量数据同步接口。
     * 以 bizId 为幂等键写入 DonationDeduct 实体，已存在的情况下按数据状态判断是否更新或拒绝。
     */
    @PostMapping("/complaint-donation-deduct/sync")
    @ApiDoc(name = "投诉乐捐扣除同步",
            desc = "接收风控平台发送的投诉乐捐扣除数据，支持批量写入。\n"
                 + "约束: records 必填且不超过 200 条; 字段均为必填。\n"
                 + "入参: {records:[{personNumber(人员编号), violationTypeCode(违规类型编码), "
                 + "complaintFineAmount(投诉罚款金额,BigDecimal), violationDonationAmount(违规捐赠金额,BigDecimal), "
                 + "voucherDate(凭证日期,yyyy-MM-dd), bizId(业务单据号,max80位), remark(备注)}]}。\n"
                 + "响应: {totalCount(总数), successCount(成功数), failCount(失败数), "
                 + "failDetails:[{identifier(失败标识,personNumber##bizId), reason(失败原因)}], "
                 + "createdBillIds:[单据ID]}。")
    public ApiResult<ComplaintDonationDeductResponse> syncComplaintDonationDeduct(
            @RequestBody BatchComplaintDonationDeductRequest request) {
        requireNotEmpty(request.getRecords(), "records");
        requireTrue(request.getRecords().size() <= 200,
                "批量写入记录数不能超过200，当前: " + request.getRecords().size());
        log.info("收到投诉乐捐扣除同步请求 - 记录数: {}",
                request.getRecords() != null ? request.getRecords().size() : 0);
        ComplaintDonationDeductResponse response =
                complaintDonationDeductService.writeComplaintDonationDeduct(request);
        return success(response);
    }
}
