package com.erp.tenant.service.customer.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.tenant.entity.customer.Customer;
import com.erp.tenant.repository.customer.CustomerRepository;
import com.erp.tenant.service.customer.CustomerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租户端客户服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl implements CustomerService {

    private final CustomerRepository customerRepository;

    @Override
    public IPage<Customer> getCustomerPage(Long tenantId, String keyword, String level,
                                           Integer status, int page, int pageSize) {
        return customerRepository.findPage(
                new Page<>(page, pageSize),
                tenantId, keyword, level, status
        );
    }

    @Override
    public Customer getCustomerDetail(Long tenantId, Long customerId) {
        return customerRepository.findById(customerId, tenantId);
    }

    @Override
    @Transactional
    public Customer createCustomer(Long tenantId, Long operatorId, Customer customer) {
        customer.setTenantId(tenantId);
        customer.setCreatedBy(operatorId);
        customer.setStatus(1);
        customerRepository.insert(customer);
        return customer;
    }

    @Override
    @Transactional
    public boolean updateCustomer(Long tenantId, Long operatorId, Customer customer) {
        Customer existing = customerRepository.findById(customer.getId(), tenantId);
        if (existing == null) {
            return false;
        }
        customer.setTenantId(tenantId);
        customer.setUpdatedBy(operatorId);
        customerRepository.updateById(customer);
        return true;
    }

    @Override
    @Transactional
    public boolean deleteCustomer(Long tenantId, Long customerId) {
        Customer customer = customerRepository.findById(customerId, tenantId);
        if (customer == null) {
            return false;
        }
        customerRepository.deleteById(customerId);
        return true;
    }

    @Override
    @Transactional
    public boolean toggleCustomerStatus(Long tenantId, Long customerId, Integer status) {
        int rows = customerRepository.updateStatus(customerId, tenantId, status);
        return rows > 0;
    }

    @Override
    public CustomerStats getCustomerStats(Long tenantId) {
        CustomerStats stats = new CustomerStats();
        stats.total = customerRepository.countByStatus(tenantId, null);
        stats.active = customerRepository.countByStatus(tenantId, 1);
        stats.disabled = customerRepository.countByStatus(tenantId, 0);
        return stats;
    }
}
