package com.ycwl.basic.controller.pc;

import com.ycwl.basic.integration.profitshare.dto.CalculateResultVO;
import com.ycwl.basic.integration.profitshare.dto.CalculateShareRequest;
import com.ycwl.basic.integration.profitshare.dto.ManualShareRequest;
import com.ycwl.basic.integration.profitshare.dto.TypesVO;
import com.ycwl.basic.integration.profitshare.dto.record.RecordDetailVO;
import com.ycwl.basic.integration.profitshare.dto.record.RecordVO;
import com.ycwl.basic.integration.profitshare.dto.rule.CreateRuleRequest;
import com.ycwl.basic.integration.profitshare.dto.rule.RuleVO;
import com.ycwl.basic.integration.profitshare.service.ProfitShareIntegrationService;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.utils.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 分账管理 V2 版本控制器 - 基于 zt-profitshare 集成服务
 *
 * @author Claude Code
 * @date 2025-01-11
 */
@Slf4j
@RestController
@RequestMapping("/api/profit-share/v2")
@RequiredArgsConstructor
public class ProfitShareV2Controller {

    private final ProfitShareIntegrationService profitShareIntegrationService;

    // ========== 分账规则管理 ==========

    /**
     * 创建分账规则
     */
    @PostMapping("/rules")
    public ApiResponse<RuleVO> createRule(@Valid @RequestBody CreateRuleRequest request) {
        log.info("创建分账规则, scenicId: {}, ruleName: {}, ruleType: {}",
                request.getScenicId(), request.getRuleName(), request.getRuleType());
        try {
            RuleVO rule = profitShareIntegrationService.createRule(request);
            return ApiResponse.success(rule);
        } catch (Exception e) {
            log.error("创建分账规则失败", e);
            return ApiResponse.fail("创建分账规则失败: " + e.getMessage());
        }
    }

    /**
     * 查询分账规则列表
     */
    @GetMapping("/rules")
    public ApiResponse<PageResponse<RuleVO>> listRules(
            @RequestParam(required = false) Long scenicId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String ruleType,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("查询分账规则列表, scenicId: {}, status: {}, ruleType: {}, page: {}, pageSize: {}",
                scenicId, status, ruleType, page, pageSize);

        // 参数验证：限制pageSize最大值为100
        if (pageSize > 100) {
            pageSize = 100;
        }

        try {
            PageResponse<RuleVO> response = profitShareIntegrationService.listRules(scenicId, status, ruleType, page, pageSize);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("查询分账规则列表失败", e);
            return ApiResponse.fail("查询分账规则列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取分账规则详情
     */
    @GetMapping("/rules/{id}")
    public ApiResponse<RuleVO> getRule(@PathVariable Long id) {
        log.info("获取分账规则详情, id: {}", id);
        try {
            RuleVO rule = profitShareIntegrationService.getRule(id);
            return ApiResponse.success(rule);
        } catch (Exception e) {
            log.error("获取分账规则详情失败, id: {}", id, e);
            return ApiResponse.fail("获取分账规则详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新分账规则
     */
    @PutMapping("/rules/{id}")
    public ApiResponse<RuleVO> updateRule(@PathVariable Long id, @Valid @RequestBody CreateRuleRequest request) {
        log.info("更新分账规则, id: {}", id);
        try {
            RuleVO rule = profitShareIntegrationService.updateRule(id, request);
            return ApiResponse.success(rule);
        } catch (Exception e) {
            log.error("更新分账规则失败, id: {}", id, e);
            return ApiResponse.fail("更新分账规则失败: " + e.getMessage());
        }
    }

    /**
     * 启用分账规则
     */
    @PutMapping("/rules/{id}/enable")
    public ApiResponse<String> enableRule(@PathVariable Long id) {
        log.info("启用分账规则, id: {}", id);
        try {
            profitShareIntegrationService.enableRule(id);
            return ApiResponse.success("规则已启用");
        } catch (Exception e) {
            log.error("启用分账规则失败, id: {}", id, e);
            return ApiResponse.fail("启用分账规则失败: " + e.getMessage());
        }
    }

    /**
     * 禁用分账规则
     */
    @PutMapping("/rules/{id}/disable")
    public ApiResponse<String> disableRule(@PathVariable Long id) {
        log.info("禁用分账规则, id: {}", id);
        try {
            profitShareIntegrationService.disableRule(id);
            return ApiResponse.success("规则已禁用");
        } catch (Exception e) {
            log.error("禁用分账规则失败, id: {}", id, e);
            return ApiResponse.fail("禁用分账规则失败: " + e.getMessage());
        }
    }

    /**
     * 删除分账规则
     */
    @DeleteMapping("/rules/{id}")
    public ApiResponse<String> deleteRule(@PathVariable Long id) {
        log.info("删除分账规则, id: {}", id);
        try {
            profitShareIntegrationService.deleteRule(id);
            return ApiResponse.success("规则已删除");
        } catch (Exception e) {
            log.error("删除分账规则失败, id: {}", id, e);
            return ApiResponse.fail("删除分账规则失败: " + e.getMessage());
        }
    }

    // ========== 分账记录查询 ==========

    /**
     * 查询景区分账记录
     */
    @GetMapping("/records/scenic/{scenicId}")
    public ApiResponse<PageResponse<RecordVO>> getRecordsByScenic(
            @PathVariable Long scenicId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("查询景区分账记录, scenicId: {}, page: {}, pageSize: {}", scenicId, page, pageSize);

        // 参数验证：限制pageSize最大值为100
        if (pageSize > 100) {
            pageSize = 100;
        }

        try {
            PageResponse<RecordVO> response = profitShareIntegrationService.getRecordsByScenic(scenicId, page, pageSize);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("查询景区分账记录失败, scenicId: {}", scenicId, e);
            return ApiResponse.fail("查询景区分账记录失败: " + e.getMessage());
        }
    }

    /**
     * 查询分账记录详情
     */
    @GetMapping("/records/{id}")
    public ApiResponse<RecordDetailVO> getRecordById(@PathVariable Long id) {
        log.info("查询分账记录详情, id: {}", id);
        try {
            RecordDetailVO record = profitShareIntegrationService.getRecordById(id);
            return ApiResponse.success(record);
        } catch (Exception e) {
            log.error("查询分账记录详情失败, id: {}", id, e);
            return ApiResponse.fail("查询分账记录详情失败: " + e.getMessage());
        }
    }

    /**
     * 按订单ID查询分账记录
     */
    @GetMapping("/records/order/{orderId}")
    public ApiResponse<RecordDetailVO> getRecordByOrderId(@PathVariable String orderId) {
        log.info("按订单ID查询分账记录, orderId: {}", orderId);
        try {
            RecordDetailVO record = profitShareIntegrationService.getRecordByOrderId(orderId);
            return ApiResponse.success(record);
        } catch (Exception e) {
            log.error("按订单ID查询分账记录失败, orderId: {}", orderId, e);
            return ApiResponse.fail("按订单ID查询分账记录失败: " + e.getMessage());
        }
    }

    // ========== 手动分账与计算 ==========

    /**
     * 手动触发分账
     */
    @PostMapping("/manual")
    public ApiResponse<String> manualShare(@Valid @RequestBody ManualShareRequest request) {
        log.info("手动触发分账, orderId: {}", request.getOrderId());
        try {
            profitShareIntegrationService.manualShare(request.getOrderId());
            return ApiResponse.success("手动分账触发成功");
        } catch (Exception e) {
            log.error("手动触发分账失败, orderId: {}", request.getOrderId(), e);
            return ApiResponse.fail("手动触发分账失败: " + e.getMessage());
        }
    }

    /**
     * 计算分账结果（不执行）
     */
    @PostMapping("/calculate")
    public ApiResponse<CalculateResultVO> calculateShare(@Valid @RequestBody CalculateShareRequest request) {
        log.info("计算分账结果, scenicId: {}, totalAmount: {}", request.getScenicId(), request.getTotalAmount());
        try {
            CalculateResultVO result = profitShareIntegrationService.calculateShare(request);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("计算分账结果失败", e);
            return ApiResponse.fail("计算分账结果失败: " + e.getMessage());
        }
    }

    // ========== 类型查询 ==========

    /**
     * 获取支持的类型列表
     */
    @GetMapping("/types")
    public ApiResponse<TypesVO> getSupportedTypes() {
        log.info("获取支持的类型列表");
        try {
            TypesVO types = profitShareIntegrationService.getSupportedTypes();
            return ApiResponse.success(types);
        } catch (Exception e) {
            log.error("获取支持的类型列表失败", e);
            return ApiResponse.fail("获取支持的类型列表失败: " + e.getMessage());
        }
    }
}
