package shop.alien.storeplatform.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreCashOutRecord;
import shop.alien.storeplatform.annotation.PreventDuplicateSubmit;
import shop.alien.storeplatform.dto.CashOutDTO;
import shop.alien.storeplatform.service.IncomeManageService;
import shop.alien.storeplatform.util.LoginUserUtil;

import java.util.Map;

/**
 * web端商户收入管理 前端控制器
 *
 * @author ssk
 * @since 2025-11-14
 */
@Slf4j
@Api(tags = {"web端商户收入管理"})
@CrossOrigin
@RestController
@RequestMapping("/incomeManage")
@RequiredArgsConstructor
public class IncomeManageController {

    private final IncomeManageService incomeManageService;

    @ApiOperation("账期查询")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "incomeType", value = "收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentType", value = "账期类型, 0:未到, 1:已到", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getPaymentCycle")
    public R<JSONObject> getPaymentCycle(
            @RequestParam(value = "incomeType", required = false) Integer incomeType,
            @RequestParam(value = "paymentType", required = false) Integer paymentType,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        log.info("IncomeManageController.getPaymentCycle? incomeType={}, paymentType={}, startTime={}, endTime={}, page={}, size={}",
                incomeType, paymentType, startTime, endTime, page, size);
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            JSONObject result = incomeManageService.getPaymentCycle(storeId, incomeType, paymentType, startTime, endTime, page, size);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getPaymentCycle ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("查询账户余额")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getAccountBalance")
    public R<Map<String, Object>> getAccountBalance() {
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            Map<String, Object> result = incomeManageService.getAccountBalance(storeId);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getAccountBalance ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("提现申请")
    @ApiOperationSupport(order = 3)
    @PreventDuplicateSubmit(expireSeconds = 5, message = "提现操作过于频繁，请稍后再试")
    @PostMapping("/cashOut")
    public R<?> cashOut(@RequestBody CashOutDTO cashOutDTO) {
        log.info("IncomeManageController.cashOut? payPassword=***, withdrawalMoney={}",
                 cashOutDTO.getWithdrawalMoney());
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            return incomeManageService.cashOut(storeId, cashOutDTO.getPayPassword(), cashOutDTO.getWithdrawalMoney());
        } catch (Exception e) {
            log.error("IncomeManageController.cashOut ERROR: {}", e.getMessage(), e);
            return R.fail("提现失败：" + e.getMessage());
        }
    }

    @ApiOperation("提现记录查询")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "cashOutStartTime", value = "开始时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cashOutEndTime", value = "结束时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "paymentStatus", value = "提现状态（1-待审核, 2-审核不通过, 3-已通过, 4-已打款, 5-打款失败）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getCashOutRecordList")
    public R<?> getCashOutRecordList(
            @RequestParam(value = "cashOutStartTime", required = false) String cashOutStartTime,
            @RequestParam(value = "cashOutEndTime", required = false) String cashOutEndTime,
            @RequestParam(value = "paymentStatus", required = false) String paymentStatus,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        log.info("IncomeManageController.getCashOutRecordList? cashOutStartTime={}, cashOutEndTime={}, paymentStatus={}, page={}, size={}",
                 cashOutStartTime, cashOutEndTime, paymentStatus, page, size);
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            Object result = incomeManageService.getCashOutRecordList(storeId, cashOutStartTime, cashOutEndTime, paymentStatus, page, size);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getCashOutRecordList ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("提现记录详情查询")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提现记录ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getCashOutRecordDetail")
    public R<StoreCashOutRecord> getCashOutRecordDetail(@RequestParam("id") Integer id) {
        log.info("IncomeManageController.getCashOutRecordDetail?id={}", id);
        try {
            StoreCashOutRecord result = incomeManageService.getCashOutRecordDetail(id);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getCashOutRecordDetail ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 今日收益查询
     * <p>
     * 接口迁移来源: App端 /alienStore/storeIncomeDetailsRecord/groupIncome
     * 原接口参数: date, storeId, incomeType, page, size
     * Web端变更: storeId 从 JWT Token 中自动获取
     * </p>
     *
     * @param date 日期（格式：yyyy-MM-dd）
     * @param incomeType 收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡
     * @param page 页码
     * @param size 每页条数
     * @return 今日收益数据
     */
    @ApiOperation("今日收益查询")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期（格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "incomeType", value = "收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getGroupIncome")
    public R<?> getGroupIncome(
            @RequestParam("date") String date,
            @RequestParam(value = "incomeType", required = false) Integer incomeType,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        log.info("IncomeManageController.getGroupIncome?date={}, incomeType={}, page={}, size={}",
                date, incomeType, page, size);
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            Object result = incomeManageService.getGroupIncome(storeId, date, incomeType, page, size);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getGroupIncome ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("快速提现申请")
    @ApiOperationSupport(order = 7)
    @PreventDuplicateSubmit(expireSeconds = 5, message = "快速提现操作过于频繁，请稍后再试")
    @PostMapping("/applyFastCashOut")
    public R<?> applyFastCashOut(@RequestBody CashOutDTO cashOutDTO) {
        log.info("IncomeManageController.applyFastCashOut? payPassword=***, withdrawalMoney={}",
                cashOutDTO.getWithdrawalMoney());
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            return incomeManageService.applyFastCashOut(storeId, cashOutDTO.getPayPassword(), cashOutDTO.getWithdrawalMoney());
        } catch (Exception e) {
            log.error("IncomeManageController.applyFastCashOut ERROR: {}", e.getMessage(), e);
            return R.fail("快速提现失败：" + e.getMessage());
        }
    }

    @ApiOperation("已入账/未入账详情查询")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "incomeType", value = "收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentType", value = "账期类型, 0:未入账, 1:已入账", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "startTime", value = "开始时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间（格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "page", value = "页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getPaymentDetails")
    public R<com.alibaba.fastjson2.JSONObject> getPaymentDetails(
            @RequestParam(value = "incomeType", required = false) Integer incomeType,
            @RequestParam("paymentType") Integer paymentType,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        log.info("IncomeManageController.getPaymentDetails? incomeType={}, paymentType={}, startTime={}, endTime={}, page={}, size={}",
                incomeType, paymentType, startTime, endTime, page, size);
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            com.alibaba.fastjson2.JSONObject result = incomeManageService.getPaymentDetails(
                    storeId, incomeType, paymentType, startTime, endTime, page, size);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getPaymentDetails ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("收入汇总统计")
    @ApiOperationSupport(order = 9)
    @GetMapping("/getIncomeSummary")
    public R<Map<String, Object>> getIncomeSummary() {
        log.info("IncomeManageController.getIncomeSummary - 查询收入汇总统计");
        try {
            Integer storeId = LoginUserUtil.getCurrentStoreId();
            Map<String, Object> result = incomeManageService.getIncomeSummary(storeId);
            return R.data(result);
        } catch (Exception e) {
            log.error("IncomeManageController.getIncomeSummary ERROR: {}", e.getMessage(), e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }
}

