package com.erp.tenant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import com.erp.tenant.config.TenantContext;
import com.erp.tenant.dto.customer.CustomerPageResponse;
import com.erp.tenant.dto.customer.CustomerPageResponse.CustomerItemDTO;
import com.erp.tenant.entity.customer.Customer;
import com.erp.tenant.service.customer.CustomerService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户端客户管理控制器 - 根路径API
 * 路由: /api/customers
 * 
 * 此控制器提供租户后台所需的 /api/customers 端点
 * 对应PHP后台的客户管理功能
 */
@Slf4j
@RestController
@RequestMapping("/api/customers")
@RequiredArgsConstructor
public class TenantCustomerApiController {

    private final CustomerService customerService;
    private static final DateTimeFormatter DT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 客户列表
     * GET /api/customers
     */
    @GetMapping
    public ApiResponse<PageResponse<CustomerItemDTO>> getCustomerList(
            @RequestParam(required = false) Long tenantId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        Long currentTenantId = TenantContext.getCurrentTenantId();
        // 如果前端传递了tenant_id参数，优先使用前端的
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        
        if (currentTenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        IPage<Customer> customerPage = customerService.getCustomerPage(
                currentTenantId, keyword, level, status, page, pageSize);

        var items = customerPage.getRecords().stream()
                .map(this::toCustomerItemDTO)
                .collect(Collectors.toList());

        PageResponse<CustomerItemDTO> response = PageResponse.<CustomerItemDTO>builder()
                .list(items)
                .total(customerPage.getTotal())
                .page(customerPage.getCurrent())
                .pageSize(customerPage.getSize())
                .totalPages(customerPage.getPages())
                .build();

        return ApiResponse.success(response);
    }

    /**
     * 客户详情
     * GET /api/customers/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<CustomerItemDTO> getCustomerDetail(
            @RequestParam(required = false) Long tenantId,
            @PathVariable Long id) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        
        if (currentTenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        Customer customer = customerService.getCustomerDetail(currentTenantId, id);
        if (customer == null) {
            return ApiResponse.error(404, "客户不存在");
        }
        return ApiResponse.success(toCustomerItemDTO(customer));
    }

    /**
     * 创建客户
     * POST /api/customers
     */
    @PostMapping
    public ApiResponse<CustomerItemDTO> createCustomer(
            @RequestParam(required = false) Long tenantId,
            @Valid @RequestBody Customer customer) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        Long operatorId = 0L;

        Customer created = customerService.createCustomer(currentTenantId, operatorId, customer);
        return ApiResponse.success("创建成功", toCustomerItemDTO(created));
    }

    /**
     * 更新客户
     * PUT /api/customers/{id}
     */
    @PutMapping("/{id}")
    public ApiResponse<?> updateCustomer(
            @RequestParam(required = false) Long tenantId,
            @PathVariable Long id, 
            @Valid @RequestBody Customer customer) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        Long operatorId = 0L;

        customer.setId(id);
        boolean success = customerService.updateCustomer(currentTenantId, operatorId, customer);
        if (!success) {
            return ApiResponse.error(404, "客户不存在");
        }
        return ApiResponse.success("更新成功", null);
    }

    /**
     * 删除客户
     * DELETE /api/customers/{id}
     */
    @DeleteMapping("/{id}")
    public ApiResponse<?> deleteCustomer(
            @RequestParam(required = false) Long tenantId,
            @PathVariable Long id) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        
        boolean success = customerService.deleteCustomer(currentTenantId, id);
        if (!success) {
            return ApiResponse.error(404, "客户不存在");
        }
        return ApiResponse.success("删除成功", null);
    }

    /**
     * 启用/禁用客户
     * POST /api/customers/{id}/toggle-status
     */
    @PostMapping("/{id}/toggle-status")
    public ApiResponse<?> toggleStatus(
            @RequestParam(required = false) Long tenantId,
            @PathVariable Long id,
            @RequestBody Map<String, Integer> body) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        Integer status = body.get("status");

        if (status == null) {
            return ApiResponse.error(422, "状态不能为空");
        }
        boolean success = customerService.toggleCustomerStatus(currentTenantId, id, status);
        if (!success) {
            return ApiResponse.error(404, "客户不存在");
        }
        return ApiResponse.success("状态更新成功", null);
    }

    /**
     * 客户统计
     * GET /api/customers/stats
     */
    @GetMapping("/stats")
    public ApiResponse<?> getCustomerStats(@RequestParam(required = false) Long tenantId) {
        
        Long currentTenantId = TenantContext.getCurrentTenantId();
        if (tenantId != null) {
            currentTenantId = tenantId;
        }
        
        if (currentTenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }
        
        CustomerService.CustomerStats stats = customerService.getCustomerStats(currentTenantId);
        return ApiResponse.success(Map.of(
                "total", stats.total,
                "active", stats.active,
                "disabled", stats.disabled
        ));
    }

    private CustomerItemDTO toCustomerItemDTO(Customer customer) {
        return CustomerItemDTO.builder()
                .id(customer.getId())
                .customerCode(customer.getCustomerCode() != null ? customer.getCustomerCode() : "")
                .name(customer.getName() != null ? customer.getName() : "")
                .contact(customer.getContact() != null ? customer.getContact() : "")
                .phone(customer.getPhone() != null ? customer.getPhone() : "")
                .tel(customer.getTel() != null ? customer.getTel() : "")
                .email(customer.getEmail() != null ? customer.getEmail() : "")
                .address(customer.getAddress() != null ? customer.getAddress() : "")
                .level(customer.getLevel() != null ? customer.getLevel() : "")
                .category(customer.getCategory() != null ? customer.getCategory() : "")
                .receivableBalance(customer.getReceivableBalance() != null ? customer.getReceivableBalance() : BigDecimal.ZERO)
                .totalConsumed(customer.getTotalConsumed() != null ? customer.getTotalConsumed() : BigDecimal.ZERO)
                .creditLimit(customer.getCreditLimit() != null ? customer.getCreditLimit() : BigDecimal.ZERO)
                .status(customer.getStatus() != null ? customer.getStatus() : 0)
                .statusText(customer.getStatusText() != null ? customer.getStatusText() : "")
                .lastOrderAt(customer.getLastOrderAt() != null ? customer.getLastOrderAt().format(DT_FORMAT) : null)
                .remark(customer.getRemark() != null ? customer.getRemark() : "")
                .createdAt(customer.getCreatedAt() != null ? customer.getCreatedAt().format(DT_FORMAT) : null)
                .updatedAt(customer.getUpdatedAt() != null ? customer.getUpdatedAt().format(DT_FORMAT) : null)
                .build();
    }
}
