package com.erp.tenant.controller.customer;

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;

/**
 * 租户端客户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/tenant/customers")
@RequiredArgsConstructor
public class CustomerController {

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

    /**
     * 客户列表
     * GET /api/tenant/customers
     */
    @GetMapping
    public ApiResponse<PageResponse<CustomerItemDTO>> getCustomerList(
            @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 tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

        IPage<Customer> customerPage = customerService.getCustomerPage(
                tenantId, 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/tenant/customers/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<CustomerItemDTO> getCustomerDetail(@PathVariable Long id) {
        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }

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

    /**
     * 创建客户
     * POST /api/tenant/customers
     */
    @PostMapping
    public ApiResponse<CustomerItemDTO> createCustomer(@Valid @RequestBody Customer customer) {
        Long tenantId = TenantContext.getCurrentTenantId();
        Long operatorId = 0L;

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

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

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

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

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

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

    /**
     * 客户统计
     * GET /api/tenant/customers/stats
     */
    @GetMapping("/stats")
    public ApiResponse<?> getCustomerStats() {
        Long tenantId = TenantContext.getCurrentTenantId();
        if (tenantId == null) {
            return ApiResponse.error(401, "未获取到租户信息");
        }
        CustomerService.CustomerStats stats = customerService.getCustomerStats(tenantId);
        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();
    }
}
