package com.ruoyi.loanpricing.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.loanpricing.domain.dto.ModelInvokeDTO;
import com.ruoyi.loanpricing.domain.vo.CustomerMapRecordVO;
import com.ruoyi.loanpricing.domain.vo.HistoryLoanContractVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


/**
 * @Author 吴凯程
 * @Date 2025/11/10
 **/
@Tag(name = "测算测试接口")
@RestController
@RequestMapping("/rate/pricing/mock")
public class LoanRatePricingMockController extends BaseController {

    @Anonymous
    @Operation(summary = "调用个人模型获取测算利率")
    @PostMapping("/invokeModel/personal")
    public AjaxResult invokePersonalModel(ModelInvokeDTO modelInvokeDTO) {
        return new AjaxResult(10000, "success", loadJsonFromResource("data/retail_output.json"));
    }

    @Anonymous
    @Operation(summary = "调用企业模型获取测算利率")
    @PostMapping("/invokeModel/corporate")
    public AjaxResult invokeCorporateModel(ModelInvokeDTO modelInvokeDTO) {
        return new AjaxResult(10000, "success", loadJsonFromResource("data/corp_output.json"));
    }

    @Anonymous
    @Operation(summary = "模拟个人客户号映射查询")
    @GetMapping("/customer-map/personal")
    public AjaxResult queryPersonalCustomerMap(@RequestParam("cust_id") String custId)
    {
        return success(randomCustomerMapRecords(custId, "个人客户"));
    }

    @Anonymous
    @Operation(summary = "模拟企业客户号映射查询")
    @GetMapping("/customer-map/corporate")
    public AjaxResult queryCorporateCustomerMap(@RequestParam("cust_id") String custId)
    {
        return success(randomCustomerMapRecords(custId, "企业客户"));
    }

    @Anonymous
    @Operation(summary = "模拟历史贷款合同查询")
    @GetMapping("/history-contract")
    public AjaxResult queryHistoryContract(@RequestParam("cust_isn") String custIsn)
    {
        String normalizedCustIsn = StringUtils.trimWhitespace(custIsn);
        if (!StringUtils.hasText(normalizedCustIsn))
        {
            throw new ServiceException("客户内码不能为空");
        }
        if ("EMPTY_HISTORY".equals(normalizedCustIsn))
        {
            return success(Collections.emptyList());
        }
        List<HistoryLoanContractVO> records = new ArrayList<>();
        HistoryLoanContractVO record = new HistoryLoanContractVO();
        record.setCustIsn(normalizedCustIsn);
        record.setLoanContractHistory("HT" + normalizedCustIsn);
        record.setGuarTypeHistory("信用");
        record.setProductCodeHistory("P001");
        record.setLoanRateHistory("EMPTY_RATE".equals(normalizedCustIsn) ? "" : "3.65");
        record.setLoanAmountHistory("100000");
        record.setLoanSignDateHistory(LocalDate.now().minusMonths(6).toString());
        records.add(record);
        return success(records);
    }

    private ObjectNode loadJsonFromResource(String resourcePath){
        ClassPathResource classPathResource = new ClassPathResource(resourcePath);
        try (InputStream inputStream = classPathResource.getInputStream();){

            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(inputStream, ObjectNode.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<CustomerMapRecordVO> randomCustomerMapRecords(String custId, String namePrefix)
    {
        String normalizedCustId = StringUtils.trimWhitespace(custId);
        if (!StringUtils.hasText(normalizedCustId))
        {
            throw new ServiceException("客户号不能为空");
        }
        if ("HISTORY_EMPTY".equals(normalizedCustId))
        {
            CustomerMapRecordVO record = new CustomerMapRecordVO();
            record.setCustId(normalizedCustId);
            record.setCustIsn("EMPTY_HISTORY");
            record.setCustName(namePrefix + "空历史合同");
            record.setFaithDay("0");
            record.setBalanceAvg("0");
            record.setLoanCountHis("0");
            record.setLastLoanDate("");
            return Collections.singletonList(record);
        }
        if ("HISTORY_EMPTY_RATE".equals(normalizedCustId))
        {
            CustomerMapRecordVO record = new CustomerMapRecordVO();
            record.setCustId(normalizedCustId);
            record.setCustIsn("EMPTY_RATE");
            record.setCustName(namePrefix + "空历史利率");
            record.setFaithDay("30");
            record.setBalanceAvg("10000");
            record.setLoanCountHis("1");
            record.setLastLoanDate(LocalDate.now().minusMonths(3).toString());
            return Collections.singletonList(record);
        }
        int count = ThreadLocalRandom.current().nextInt(1, 4);
        List<CustomerMapRecordVO> records = new ArrayList<>();
        for (int i = 1; i <= count; i++)
        {
            CustomerMapRecordVO record = new CustomerMapRecordVO();
            record.setCustId(normalizedCustId);
            record.setCustIsn(String.valueOf(81000000000L + ThreadLocalRandom.current().nextInt(1000000)));
            record.setCustName(namePrefix + i);
            record.setFaithDay(String.valueOf(ThreadLocalRandom.current().nextInt(1, 365)));
            record.setBalanceAvg(String.valueOf(ThreadLocalRandom.current().nextInt(10000, 900000)));
            record.setLoanCountHis(String.valueOf(ThreadLocalRandom.current().nextInt(0, 10)));
            record.setLastLoanDate(LocalDate.now().minusDays(ThreadLocalRandom.current().nextInt(1, 800)).toString());
            records.add(record);
        }
        return records;
    }

}
