package com.erp.platformsync.controller.orderpull;

import com.erp.common.core.model.ApiResponse;
import com.erp.platformsync.dto.orderpull.OrderPullConfigDTO;
import com.erp.platformsync.dto.orderpull.OrderPullConfigRequest;
import com.erp.platformsync.dto.orderpull.OrderPullLogDTO;
import com.erp.platformsync.dto.orderpull.OrderPullLogQueryRequest;
import com.erp.platformsync.service.orderpull.OrderPullService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单拉取配置控制器
 * 
 * API路由：
 * - GET    /order-pull/config          获取拉单配置列表
 * - PUT    /order-pull/config          保存拉单配置
 * - POST   /order-pull/pull-now        立即拉单
 * - GET    /order-pull/logs            拉单日志
 * - DELETE /order-pull/{id}            删除拉单配置
 * - POST   /order-pull/{id}/trigger    触发拉单
 */
@Slf4j
@RestController
@RequestMapping("/order-pull")
@RequiredArgsConstructor
public class OrderPullController {

    private final OrderPullService orderPullService;

    /**
     * 获取拉单配置列表
     * GET /order-pull/config
     */
    @GetMapping("/config")
    public ApiResponse<List<OrderPullConfigDTO>> getConfigList() {
        try {
            List<OrderPullConfigDTO> configs = orderPullService.getConfigList();
            return ApiResponse.success(configs);
        } catch (Exception e) {
            log.error("获取拉单配置列表异常: {}", e.getMessage(), e);
            return ApiResponse.error("获取配置列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个拉单配置
     * GET /order-pull/config/{id}
     */
    @GetMapping("/config/{id}")
    public ApiResponse<OrderPullConfigDTO> getConfig(@PathVariable Long id) {
        try {
            OrderPullConfigDTO config = orderPullService.getConfig(id);
            if (config == null) {
                return ApiResponse.notFound("配置不存在");
            }
            return ApiResponse.success(config);
        } catch (Exception e) {
            log.error("获取拉单配置异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("获取配置失败: " + e.getMessage());
        }
    }

    /**
     * 保存拉单配置
     * PUT /order-pull/config
     */
    @PutMapping("/config")
    public ApiResponse<OrderPullConfigDTO> saveConfig(@Valid @RequestBody OrderPullConfigRequest request) {
        try {
            OrderPullConfigDTO config = orderPullService.saveConfig(request);
            return ApiResponse.success("保存成功", config);
        } catch (Exception e) {
            log.error("保存拉单配置异常: {}", e.getMessage(), e);
            return ApiResponse.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 删除拉单配置
     * DELETE /order-pull/{id}
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteConfig(@PathVariable Long id) {
        try {
            boolean deleted = orderPullService.deleteConfig(id);
            if (deleted) {
                return ApiResponse.success("删除成功");
            } else {
                return ApiResponse.notFound("配置不存在");
            }
        } catch (Exception e) {
            log.error("删除拉单配置异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 触发拉单
     * POST /order-pull/{id}/trigger
     */
    @PostMapping("/{id}/trigger")
    public ApiResponse<OrderPullLogDTO> triggerPull(@PathVariable Long id) {
        try {
            OrderPullLogDTO log = orderPullService.triggerPull(id);
            return ApiResponse.success("触发成功", log);
        } catch (Exception e) {
            log.error("触发拉单异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("触发失败: " + e.getMessage());
        }
    }

    /**
     * 立即拉单
     * POST /order-pull/pull-now
     */
    @PostMapping("/pull-now")
    public ApiResponse<OrderPullLogDTO> pullNow(@Valid @RequestBody OrderPullConfigRequest request) {
        try {
            OrderPullLogDTO log = orderPullService.pullNow(request);
            return ApiResponse.success("拉单完成", log);
        } catch (Exception e) {
            log.error("立即拉单异常: {}", e.getMessage(), e);
            return ApiResponse.error("拉单失败: " + e.getMessage());
        }
    }

    /**
     * 获取拉单日志
     * GET /order-pull/logs
     */
    @GetMapping("/logs")
    public ApiResponse<List<OrderPullLogDTO>> getLogs(OrderPullLogQueryRequest queryRequest) {
        try {
            List<OrderPullLogDTO> logs = orderPullService.getLogs(queryRequest);
            return ApiResponse.success(logs);
        } catch (Exception e) {
            log.error("获取拉单日志异常: {}", e.getMessage(), e);
            return ApiResponse.error("获取日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取配置的最新日志
     * GET /order-pull/{id}/logs
     */
    @GetMapping("/{id}/logs")
    public ApiResponse<List<OrderPullLogDTO>> getConfigLogs(@PathVariable Long id, @RequestParam(defaultValue = "20") int limit) {
        try {
            List<OrderPullLogDTO> logs = orderPullService.getLatestLogs(id, limit);
            return ApiResponse.success(logs);
        } catch (Exception e) {
            log.error("获取配置日志异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("获取日志失败: " + e.getMessage());
        }
    }

    /**
     * 启用配置
     * POST /order-pull/{id}/enable
     */
    @PostMapping("/{id}/enable")
    public ApiResponse<Void> enableConfig(@PathVariable Long id) {
        try {
            boolean success = orderPullService.enableConfig(id);
            if (success) {
                return ApiResponse.success("启用成功");
            } else {
                return ApiResponse.notFound("配置不存在");
            }
        } catch (Exception e) {
            log.error("启用配置异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("启用失败: " + e.getMessage());
        }
    }

    /**
     * 禁用配置
     * POST /order-pull/{id}/disable
     */
    @PostMapping("/{id}/disable")
    public ApiResponse<Void> disableConfig(@PathVariable Long id) {
        try {
            boolean success = orderPullService.disableConfig(id);
            if (success) {
                return ApiResponse.success("禁用成功");
            } else {
                return ApiResponse.notFound("配置不存在");
            }
        } catch (Exception e) {
            log.error("禁用配置异常: id={}, error={}", id, e.getMessage(), e);
            return ApiResponse.error("禁用失败: " + e.getMessage());
        }
    }
}
