package com.ruoyi.credit.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.credit.domain.DigitalCredit;
import com.ruoyi.credit.service.ICreditService;

/**
 * 数字债权管理API控制器
 * 
 * 提供数字债权凭证的生成、验证、查询等RESTful API接口
 * 
 * @author ruoyi
 * @date 2025-12-19
 */
@RestController
@RequestMapping("/api/credit/credits")
public class DigitalCreditController extends BaseController
{
    @Autowired
    private ICreditService creditService;

    /**
     * 生成数字债权凭证
     * 
     * @param digitalCredit 债权数据
     * @return 生成结果
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:add')")
    @Log(title = "数字债权", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult generateCredit(@RequestBody @Validated DigitalCredit digitalCredit)
    {
        try {
            // 设置创建者信息 - 添加调试日志
            String currentUser = getUsername();
            Long currentDeptId = getDeptId();
            logger.info("控制器层获取到的当前用户: {}, 部门ID: {}", currentUser, currentDeptId);
            
            digitalCredit.setCreateBy(currentUser);
            digitalCredit.setDeptId(currentDeptId);
            
            logger.info("准备生成债权，数据: contractId={}, createBy={}, deptId={}", 
                    digitalCredit.getContractId(), digitalCredit.getCreateBy(), digitalCredit.getDeptId());
            
            DigitalCredit credit = creditService.generateCredit(digitalCredit);
            return success(credit);
        } catch (Exception e) {
            logger.error("生成债权凭证失败", e);
            return error("生成债权凭证失败: " + e.getMessage());
        }
    }

    /**
     * 获取债权凭证详情
     * 如果债权不存在，尝试根据ID重新生成
     * 
     * @param id 债权ID
     * @return 债权详情
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:query')")
    @GetMapping("/{id}")
    public AjaxResult getCredit(@PathVariable("id") Long id)
    {
        try {
            DigitalCredit credit = creditService.selectDigitalCreditByCreditId(id);
            if (credit != null) {
                return success(credit);
            } else {
                // 债权不存在，尝试重新生成
                logger.info("债权凭证不存在，尝试重新生成，债权ID: {}", id);
                try {
                    credit = creditService.regenerateCreditById(id);
                    if (credit != null) {
                        logger.info("成功重新生成债权凭证，债权ID: {}", id);
                        return success(credit);
                    } else {
                        return error("债权凭证不存在且无法重新生成");
                    }
                } catch (Exception regenerateException) {
                    logger.error("重新生成债权凭证失败，债权ID: {}", id, regenerateException);
                    return error("债权凭证不存在且重新生成失败: " + regenerateException.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("查询债权凭证失败", e);
            return error("查询债权凭证失败: " + e.getMessage());
        }
    }

    /**
     * 查询债权列表
     * 
     * @param digitalCredit 查询条件
     * @return 债权列表
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:list')")
    @GetMapping
    public TableDataInfo getCreditList(DigitalCredit digitalCredit)
    {
        try {
            startPage();
            List<DigitalCredit> list = creditService.selectDigitalCreditList(digitalCredit);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("查询债权列表失败", e);
            return getDataTable(null);
        }
    }

    /**
     * 更新债权状态
     * 
     * @param id 债权ID
     * @param status 新状态
     * @return 更新结果
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:edit')")
    @Log(title = "数字债权", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/status")
    public AjaxResult updateCreditStatus(@PathVariable("id") Long id, 
                                       @RequestParam("status") String status)
    {
        try {
            boolean result = creditService.updateCreditStatus(id, status);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("更新债权状态失败", e);
            return error("更新债权状态失败: " + e.getMessage());
        }
    }

    /**
     * 验证债权有效性（后端自动验证）
     * 不需要前端提供验证参数，后端自动执行完整验证
     * 验证成功后自动通知银行系统进行贷款审批
     * 
     * @param id 债权ID
     * @return 验证结果
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:query')")
    @PostMapping("/{id}/validate")
    public AjaxResult validateCredit(@PathVariable("id") Long id)
    {
        try {
            // 后端自动验证，不依赖前端参数
            Map<String, Object> result = creditService.validateCredit(id);
            
            if ((Boolean) result.get("valid")) {
                // 在结果中添加成功消息
                result.put("successMessage", "债权验证成功，已通知银行系统");
                return success(result);
            } else {
                return error("债权验证失败: " + result.get("message"));
            }
        } catch (Exception e) {
            logger.error("验证债权有效性失败", e);
            return error("验证债权有效性失败: " + e.getMessage());
        }
    }


    /**
     * 获取数字签名
     * 
     * @param id 债权ID
     * @return 数字签名
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:query')")
    @GetMapping("/{id}/signature")
    public AjaxResult getDigitalSignature(@PathVariable("id") Long id)
    {
        try {
            DigitalCredit credit = creditService.selectDigitalCreditByCreditId(id);
            if (credit != null) {
                return success(credit.getDigitalSignature());
            } else {
                return error("债权凭证不存在");
            }
        } catch (Exception e) {
            logger.error("获取数字签名失败", e);
            return error("获取数字签名失败: " + e.getMessage());
        }
    }

    /**
     * 根据合同ID查询债权
     * 
     * @param contractId 合同ID
     * @return 债权信息
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:query')")
    @GetMapping("/contract/{contractId}")
    public AjaxResult getCreditByContractId(@PathVariable("contractId") Long contractId)
    {
        try {
            DigitalCredit credit = creditService.selectDigitalCreditByContractId(contractId);
            if (credit != null) {
                return success(credit);
            } else {
                return error("该合同暂无债权凭证");
            }
        } catch (Exception e) {
            logger.error("根据合同ID查询债权失败", e);
            return error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据债权编号查询债权
     * 
     * @param creditNumber 债权编号
     * @return 债权信息
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:query')")
    @GetMapping("/number/{creditNumber}")
    public AjaxResult getCreditByNumber(@PathVariable("creditNumber") String creditNumber)
    {
        try {
            DigitalCredit credit = creditService.selectDigitalCreditByCreditNumber(creditNumber);
            if (credit != null) {
                return success(credit);
            } else {
                return error("债权凭证不存在");
            }
        } catch (Exception e) {
            logger.error("根据债权编号查询失败", e);
            return error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询即将到期的债权
     * 
     * @param days 提前天数
     * @return 债权列表
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:list')")
    @GetMapping("/expiring")
    public AjaxResult getExpiringCredits(@RequestParam(value = "days", defaultValue = "30") int days)
    {
        try {
            List<DigitalCredit> list = creditService.selectExpiringCredits(days);
            return success(list);
        } catch (Exception e) {
            logger.error("查询即将到期债权失败", e);
            return error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 删除债权
     * 
     * @param ids 债权ID数组
     * @return 删除结果
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:remove')")
    @Log(title = "数字债权", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult deleteCredit(@PathVariable Long[] ids)
    {
        try {
            int result = creditService.deleteDigitalCreditByCreditIds(ids);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("删除债权失败", e);
            return error("删除债权失败: " + e.getMessage());
        }
    }

    /**
     * 导出债权数据
     * 
     * @param response HTTP响应
     * @param digitalCredit 查询条件
     */
    @PreAuthorize("@ss.hasPermi('credit:credit:export')")
    @Log(title = "数字债权", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DigitalCredit digitalCredit)
    {
        try {
            List<DigitalCredit> list = creditService.selectDigitalCreditList(digitalCredit);
            ExcelUtil<DigitalCredit> util = new ExcelUtil<>(DigitalCredit.class);
            util.exportExcel(response, list, "数字债权数据");
        } catch (Exception e) {
            logger.error("导出债权数据失败", e);
        }
    }
}