package com.ruoyi.model.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.applet.pojo.dto.AuditRequest;
import com.ruoyi.applet.service.impl.AppletAmountService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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.enums.BusinessType;
import com.ruoyi.model.domain.AppletAmountLog;
import com.ruoyi.model.service.IAppletAmountLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 金额明细Controller
 * 
 * @author ruoyi
 * @date 2025-03-28
 */
@RestController
@RequestMapping("/model/AppletAmountLog")
public class AppletAmountLogController extends BaseController
{
    @Autowired
    private IAppletAmountLogService appletAmountLogService;
    @Autowired
    private AppletAmountService appletAmountService;

    /**
     * 查询金额明细列表
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppletAmountLog appletAmountLog)
    {
        startPage();
        List<AppletAmountLog> list = appletAmountLogService.selectAppletAmountLogList(appletAmountLog);
        return getDataTable(list);
    }

    /**
     * 导出金额明细列表
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:export')")
    @Log(title = "金额明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppletAmountLog appletAmountLog)
    {
//        List<AppletAmountLog> list = appletAmountLogService.selectAppletAmountLogList(appletAmountLog);
//        ExcelUtil<AppletAmountLog> util = new ExcelUtil<AppletAmountLog>(AppletAmountLog.class);
//        util.exportExcel(response, list, "金额明细数据");
    }

    /**
     * 获取金额明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(appletAmountLogService.selectAppletAmountLogById(id));
    }

    /**
     * 新增金额明细
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:add')")
    @Log(title = "金额明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppletAmountLog appletAmountLog)
    {
        return toAjax(appletAmountLogService.insertAppletAmountLog(appletAmountLog));
    }

    /**
     * 修改金额明细
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:edit')")
    @Log(title = "金额明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppletAmountLog appletAmountLog)
    {
        return toAjax(appletAmountLogService.updateAppletAmountLog(appletAmountLog));
    }

    /**
     * 删除金额明细
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:remove')")
    @Log(title = "金额明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appletAmountLogService.deleteAppletAmountLogByIds(ids));
    }

    /**
     * 审核金额明细
     */
    @PreAuthorize("@ss.hasPermi('model:AppletAmountLog:audit')")
    @Log(title = "金额明细审核", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    public AjaxResult audit(@RequestBody AuditRequest auditRequest)
    {
        try {
            // 参数校验
            if (auditRequest.getAuditStatus() == null) {
                return error("审核状态不能为空");
            }
//            if (auditRequest.getAuditRemark() == null || auditRequest.getAuditRemark().trim().isEmpty()) {
//                return error("审核备注不能为空");
//            }

            int successCount = 0;
            int failCount = 0;
            StringBuilder errorMsg = new StringBuilder();

            // 处理单个审核
            if (auditRequest.getId() != null) {
                AppletAmountLog appletAmountLog = appletAmountLogService.selectAppletAmountLogById(auditRequest.getId());
                if (appletAmountLog == null) {
                    return error("提现记录不存在");
                }
                if (appletAmountLog.getAuditStatus() != 0) {
                    return error("该记录已经审核过了");
                }

                boolean result = processAudit(appletAmountLog, auditRequest.getAuditStatus(), auditRequest.getAuditRemark());
                if (result) {
                    successCount++;
                } else {
                    failCount++;
                    errorMsg.append("ID:").append(auditRequest.getId()).append("审核失败;");
                }
            }
            // 处理批量审核
            else if (auditRequest.getIds() != null && auditRequest.getIds().length > 0) {
                for (Long id : auditRequest.getIds()) {
                    AppletAmountLog appletAmountLog = appletAmountLogService.selectAppletAmountLogById(id);
                    if (appletAmountLog == null || appletAmountLog.getAuditStatus() != 0) {
                        failCount++;
                        errorMsg.append("ID:").append(id).append("记录不存在或已审核;");
                        continue;
                    }

                    boolean result = processAudit(appletAmountLog, auditRequest.getAuditStatus(), auditRequest.getAuditRemark());
                    if (result) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("ID:").append(id).append("审核失败;");
                    }
                }
            } else {
                return error("请选择要审核的记录");
            }

            // 返回结果
            if (failCount == 0) {
                return success(String.format("审核成功，共处理%d条记录", successCount));
            } else {
                return error(String.format("审核完成，成功%d条，失败%d条。失败原因：%s", 
                    successCount, failCount, errorMsg.toString()));
            }

        } catch (Exception e) {
            logger.error("审核处理异常", e);
            return error("审核处理失败：" + e.getMessage());
        }
    }

    /**
     * 处理单个审核
     */
    private boolean processAudit(AppletAmountLog appletAmountLog, Integer auditStatus, String auditRemark) {
        try {
            if (auditStatus == 1) {
                // 审核通过
                return appletAmountService.auditApprove(appletAmountLog, auditRemark);
            } else if (auditStatus == 2) {
                // 审核不通过
                return appletAmountService.auditReject(appletAmountLog, auditRemark);
            }
            return false;
        } catch (Exception e) {
            logger.error("处理审核失败", e);
            return false;
        }
    }
}
