package com.erp.aftersale.controller;

import com.erp.aftersale.dto.request.AfterSaleCreateRequest;
import com.erp.aftersale.dto.request.AfterSaleQueryRequest;
import com.erp.aftersale.dto.request.AfterSaleStatusUpdateRequest;
import com.erp.aftersale.dto.response.*;
import com.erp.aftersale.service.AfterSaleService;
import com.erp.aftersale.service.AfterSaleService.OperatorInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.erp.common.core.model.PageResponse;
import com.erp.common.core.model.ApiResponse;

@Slf4j
@RestController
@RequestMapping("/after-sales")
@RequiredArgsConstructor
public class AfterSaleController {

    private final AfterSaleService afterSaleService;

    // ============ 售后查询 ============

    /**
     * GET /after-sales - 售后列表（分页）
     */
    @GetMapping
    public ApiResponse<PageResponse<AfterSaleResponse>> listAfterSales(AfterSaleQueryRequest request) {
        return ApiResponse.success(afterSaleService.listAfterSales(request));
    }

    /**
     * GET /after-sales/{id} - 售后单详情
     */
    @GetMapping("/{id}")
    public ApiResponse<AfterSaleResponse> getAfterSale(@PathVariable("id") Long id) {
        return ApiResponse.success(afterSaleService.getAfterSale(id));
    }

    /**
     * GET /after-sales/stats - 售后统计
     */
    @GetMapping("/stats")
    public ApiResponse<AfterSaleStatsResponse> getStats() {
        return ApiResponse.success(afterSaleService.getStats());
    }

    // ============ 可售后订单 ============

    /**
     * GET /after-sales/available-orders - 获取可售后的订单（已发货）
     */
    @GetMapping("/available-orders")
    public ApiResponse<PageResponse<?>> getAvailableOrders(AfterSaleQueryRequest request) {
        return ApiResponse.success(afterSaleService.getAvailableOrders(request));
    }

    /**
     * GET /after-sales/all-available-orders - 获取所有可售后订单（含未发货的仅退款）
     */
    @GetMapping("/all-available-orders")
    public ApiResponse<PageResponse<?>> getAllAvailableOrders(AfterSaleQueryRequest request) {
        return ApiResponse.success(afterSaleService.getAllAvailableOrders(request));
    }

    // ============ 售后操作 ============

    /**
     * POST /after-sales - 创建售后单
     */
    @PostMapping
    public ApiResponse<AfterSaleResponse> createAfterSale(
            @Valid @RequestBody AfterSaleCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("售后单创建成功", afterSaleService.createAfterSale(request, operator));
    }

    /**
     * PUT /after-sales/{id}/status - 更新售后状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<AfterSaleResponse> updateStatus(
            @PathVariable("id") Long id,
            @RequestBody AfterSaleStatusUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("状态更新成功", afterSaleService.updateStatus(id, request, operator));
    }

    /**
     * DELETE /after-sales/{id} - 删除售后单
     */
    @DeleteMapping("/{id}")
    public ApiResponse<?> deleteAfterSale(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        afterSaleService.deleteAfterSale(id, operator);
        return ApiResponse.success("售后单已删除");
    }

    /**
     * GET /after-sales/{id}/logs - 获取操作日志
     */
    @GetMapping("/{id}/logs")
    public ApiResponse<List<OperationLogResponse>> getLogs(@PathVariable("id") Long id) {
        return ApiResponse.success(afterSaleService.getLogs(id));
    }

    // ============ 售后审核快捷接口 ============

    /**
     * POST /after-sales/{id}/approve - 审核通过
     */
    @PostMapping("/{id}/approve")
    public ApiResponse<AfterSaleResponse> approve(
            @PathVariable("id") Long id,
            @RequestBody AfterSaleStatusUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("审核通过", afterSaleService.approve(id, request, operator));
    }

    /**
     * POST /after-sales/{id}/reject - 审核驳回
     */
    @PostMapping("/{id}/reject")
    public ApiResponse<AfterSaleResponse> reject(
            @PathVariable("id") Long id,
            @RequestBody AfterSaleStatusUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("已驳回", afterSaleService.reject(id, request, operator));
    }

    /**
     * POST /after-sales/{id}/refund - 执行退款
     */
    @PostMapping("/{id}/refund")
    public ApiResponse<AfterSaleResponse> executeRefund(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("退款已提交", afterSaleService.executeRefund(id, operator));
    }

    // ============ 辅助方法 ============

    private OperatorInfo buildOperatorInfo(HttpServletRequest request) {
        return OperatorInfo.builder()
                .operatorId(getLongHeader(request, "X-Operator-Id"))
                .operatorName(request.getHeader("X-Operator-Name"))
                .ip(getClientIp(request))
                .userAgent(request.getHeader("User-Agent"))
                .build();
    }

    private Long getLongHeader(HttpServletRequest request, String name) {
        String val = request.getHeader(name);
        if (val == null || val.isEmpty()) {
            return 0L;
        }
        try {
            return Long.parseLong(val);
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty()) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
