package com.erp.supplier.controller;

import com.erp.supplier.dto.request.*;
import com.erp.supplier.dto.response.*;
import com.erp.supplier.service.SupplierService;
import com.erp.supplier.service.SupplierService.OperatorInfo;
import com.erp.supplier.service.SupplierService.StatusOption;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

import java.util.Arrays;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping("/api/suppliers")
@RequiredArgsConstructor
public class SupplierController {

    private final SupplierService supplierService;

    // ============ 供应商基础管理 ============

    @GetMapping
    public ApiResponse<PageResponse<SupplierResponse>> listSuppliers(SupplierQueryRequest request) {
        return ApiResponse.success(supplierService.listSuppliers(request));
    }

    @GetMapping("/{id}")
    public ApiResponse<SupplierResponse> getSupplier(@PathVariable("id") Long id) {
        return ApiResponse.success(supplierService.getSupplier(id));
    }

    @PostMapping
    public ApiResponse<SupplierResponse> createSupplier(
            @Valid @RequestBody SupplierCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("供应商创建成功", supplierService.createSupplier(request, operator));
    }

    @PutMapping("/{id}")
    public ApiResponse<SupplierResponse> updateSupplier(
            @PathVariable("id") Long id,
            @Valid @RequestBody SupplierUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("供应商更新成功", supplierService.updateSupplier(id, request, operator));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteSupplier(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        supplierService.deleteSupplier(id, operator);
        return ApiResponse.<Void>success("供应商删除成功", null);
    }

    @PostMapping("/{id}/audit")
    public ApiResponse<SupplierResponse> auditSupplier(
            @PathVariable("id") Long id,
            @Valid @RequestBody SupplierAuditRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        SupplierResponse result = supplierService.auditSupplier(id, request, operator);
        String message = "approve".equals(request.getAction()) ? "审核通过" : "审核驳回";
        return ApiResponse.success(message, result);
    }

    // ============ 供应商联系人管理 ============

    @GetMapping("/{supplierId}/contacts")
    public ApiResponse<List<SupplierContactResponse>> listContacts(@PathVariable("supplierId") Long supplierId) {
        return ApiResponse.success(supplierService.listContacts(supplierId));
    }

    @PostMapping("/{supplierId}/contacts")
    public ApiResponse<SupplierContactResponse> createContact(
            @PathVariable("supplierId") Long supplierId,
            @Valid @RequestBody SupplierContactCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("联系人添加成功", supplierService.createContact(supplierId, request, operator));
    }

    @PutMapping("/{supplierId}/contacts/{contactId}")
    public ApiResponse<SupplierContactResponse> updateContact(
            @PathVariable("supplierId") Long supplierId,
            @PathVariable("contactId") Long contactId,
            @Valid @RequestBody SupplierContactUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("联系人更新成功", supplierService.updateContact(supplierId, contactId, request, operator));
    }

    @DeleteMapping("/{supplierId}/contacts/{contactId}")
    public ApiResponse<Void> deleteContact(
            @PathVariable("supplierId") Long supplierId,
            @PathVariable("contactId") Long contactId,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        supplierService.deleteContact(supplierId, contactId, operator);
        return ApiResponse.<Void>success("联系人删除成功", null);
    }

    // ============ 供应商银行账户管理 ============

    @GetMapping("/{supplierId}/bank-accounts")
    public ApiResponse<List<SupplierBankAccountResponse>> listBankAccounts(@PathVariable("supplierId") Long supplierId) {
        return ApiResponse.success(supplierService.listBankAccounts(supplierId));
    }

    @PostMapping("/{supplierId}/bank-accounts")
    public ApiResponse<SupplierBankAccountResponse> createBankAccount(
            @PathVariable("supplierId") Long supplierId,
            @Valid @RequestBody SupplierBankAccountCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("银行账户添加成功", supplierService.createBankAccount(supplierId, request, operator));
    }

    @PutMapping("/{supplierId}/bank-accounts/{accountId}")
    public ApiResponse<SupplierBankAccountResponse> updateBankAccount(
            @PathVariable("supplierId") Long supplierId,
            @PathVariable("accountId") Long accountId,
            @Valid @RequestBody SupplierBankAccountUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("银行账户更新成功", supplierService.updateBankAccount(supplierId, accountId, request, operator));
    }

    @DeleteMapping("/{supplierId}/bank-accounts/{accountId}")
    public ApiResponse<Void> deleteBankAccount(
            @PathVariable("supplierId") Long supplierId,
            @PathVariable("accountId") Long accountId,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        supplierService.deleteBankAccount(supplierId, accountId, operator);
        return ApiResponse.<Void>success("银行账户删除成功", null);
    }

    @PutMapping("/{supplierId}/bank-accounts/{accountId}/default")
    public ApiResponse<Void> setDefaultBankAccount(
            @PathVariable("supplierId") Long supplierId,
            @PathVariable("accountId") Long accountId,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        supplierService.setDefaultBankAccount(supplierId, accountId, operator);
        return ApiResponse.<Void>success("默认账户设置成功", null);
    }

    // ============ 供应商评级管理 ============

    @GetMapping("/ratings")
    public ApiResponse<PageResponse<SupplierRatingResponse>> listRatings(SupplierRatingQueryRequest request) {
        return ApiResponse.success(supplierService.listRatings(request));
    }

    @GetMapping("/ratings/{id}")
    public ApiResponse<SupplierRatingResponse> getRating(@PathVariable("id") Long id) {
        return ApiResponse.success(supplierService.getSupplierRating(id));
    }

    @GetMapping("/{supplierId}/ratings/latest")
    public ApiResponse<SupplierRatingResponse> getLatestRating(@PathVariable("supplierId") Long supplierId) {
        return ApiResponse.success(supplierService.getLatestRatingBySupplierId(supplierId));
    }

    @PostMapping("/ratings")
    public ApiResponse<SupplierRatingResponse> createRating(
            @Valid @RequestBody SupplierRatingCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("评级创建成功", supplierService.createRating(request, operator));
    }

    // ============ 采购询价管理 ============

    @GetMapping("/inquiries")
    public ApiResponse<PageResponse<ProcurementInquiryResponse>> listInquiries(ProcurementInquiryQueryRequest request) {
        return ApiResponse.success(supplierService.listInquiries(request));
    }

    @GetMapping("/inquiries/{id}")
    public ApiResponse<ProcurementInquiryResponse> getInquiry(@PathVariable("id") Long id) {
        return ApiResponse.success(supplierService.getInquiry(id));
    }

    @PostMapping("/inquiries")
    public ApiResponse<ProcurementInquiryResponse> createInquiry(
            @Valid @RequestBody ProcurementInquiryCreateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("询价单创建成功", supplierService.createInquiry(request, operator));
    }

    @PutMapping("/inquiries/{id}")
    public ApiResponse<ProcurementInquiryResponse> updateInquiry(
            @PathVariable("id") Long id,
            @Valid @RequestBody ProcurementInquiryUpdateRequest request,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("询价单更新成功", supplierService.updateInquiry(id, request, operator));
    }

    @PostMapping("/inquiries/{id}/send")
    public ApiResponse<ProcurementInquiryResponse> sendInquiry(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("询价单已发送", supplierService.sendInquiry(id, operator));
    }

    @PostMapping("/inquiries/{id}/reply")
    public ApiResponse<ProcurementInquiryResponse> replyInquiry(
            @PathVariable("id") Long id,
            @RequestParam("quotedPrice") BigDecimal quotedPrice,
            @RequestParam(value = "quoteValidUntil", required = false) String quoteValidUntil,
            @RequestParam(value = "deliveryCycle", required = false) Integer deliveryCycle,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("报价成功", supplierService.replyInquiry(id, quotedPrice, quoteValidUntil, deliveryCycle, operator));
    }

    @PostMapping("/inquiries/{id}/confirm")
    public ApiResponse<ProcurementInquiryResponse> confirmInquiry(
            @PathVariable("id") Long id,
            @RequestParam(value = "selectionReason", required = false) String selectionReason,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("询价单已确认", supplierService.confirmInquiry(id, selectionReason, operator));
    }

    @PostMapping("/inquiries/{id}/cancel")
    public ApiResponse<ProcurementInquiryResponse> cancelInquiry(
            @PathVariable("id") Long id,
            HttpServletRequest httpRequest) {
        OperatorInfo operator = buildOperatorInfo(httpRequest);
        return ApiResponse.success("询价单已取消", supplierService.cancelInquiry(id, operator));
    }

    // ============ 统计分析 ============

    @GetMapping("/statistics")
    public ApiResponse<SupplierStatisticsResponse> getStatistics() {
        return ApiResponse.success(supplierService.getStatistics());
    }

    // ============ 选项接口 ============

    @GetMapping("/options/status")
    public ApiResponse<List<StatusOption>> getStatusOptions() {
        return ApiResponse.success(Arrays.asList(
                StatusOption.builder().value("pending").label("待合作").build(),
                StatusOption.builder().value("active").label("合作中").build(),
                StatusOption.builder().value("inactive").label("已停用").build(),
                StatusOption.builder().value("blacklist").label("黑名单").build()));
    }

    @GetMapping("/options/grade")
    public ApiResponse<List<StatusOption>> getGradeOptions() {
        return ApiResponse.success(Arrays.asList(
                StatusOption.builder().value("A").label("A级(优秀)").build(),
                StatusOption.builder().value("B").label("B级(良好)").build(),
                StatusOption.builder().value("C").label("C级(一般)").build(),
                StatusOption.builder().value("D").label("D级(较差)").build()));
    }

    @GetMapping("/options/type")
    public ApiResponse<List<StatusOption>> getTypeOptions() {
        return ApiResponse.success(Arrays.asList(
                StatusOption.builder().value("manufacturer").label("生产厂商").build(),
                StatusOption.builder().value("trader").label("贸易商").build(),
                StatusOption.builder().value("agent").label("代理商").build(),
                StatusOption.builder().value("individual").label("个体户").build()));
    }

    // ============ Helper ============

    private OperatorInfo buildOperatorInfo(HttpServletRequest request) {
        return OperatorInfo.builder()
                .operatorId(0L)
                .operatorName("API")
                .ip(getClientIp(request))
                .userAgent(request.getHeader("User-Agent"))
                .build();
    }

    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;
    }
}
