package com.erp.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erp.customer.dto.CustomerRelationshipRequest;
import com.erp.customer.entity.Customer;
import com.erp.customer.entity.CustomerRelationship;
import com.erp.customer.repository.CustomerRelationshipRepository;
import com.erp.customer.repository.CustomerRepository;
import com.erp.customer.service.CustomerRelationshipService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 客户关系Service实现（8级客户关系）
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerRelationshipServiceImpl extends ServiceImpl<CustomerRelationshipRepository, CustomerRelationship> 
        implements CustomerRelationshipService {
    
    private final CustomerRelationshipRepository relationshipRepository;
    private final CustomerRepository customerRepository;
    
    @Override
    public List<CustomerRelationship> getRelationshipsByCustomerId(Long customerId) {
        return relationshipRepository.findByCustomerId(customerId);
    }
    
    @Override
    public CustomerRelationship getRelationshipById(Long id) {
        LambdaQueryWrapper<CustomerRelationship> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerRelationship::getId, id).isNull(CustomerRelationship::getDeletedAt);
        return relationshipRepository.selectOne(queryWrapper);
    }
    
    @Override
    @Transactional
    public CustomerRelationship createRelationship(CustomerRelationshipRequest request) {
        CustomerRelationship relationship = new CustomerRelationship();
        relationship.setTenantId(request.getTenantId());
        relationship.setCustomerId(request.getCustomerId());
        relationship.setParentCustomerId(request.getParentCustomerId());
        relationship.setRelationshipLevel(request.getRelationshipLevel());
        relationship.setRelationshipType(request.getRelationshipType());
        relationship.setIsHeadquarters(request.getIsHeadquarters() != null ? request.getIsHeadquarters() : false);
        relationship.setGroupName(request.getGroupName());
        relationship.setGroupCode(request.getGroupCode());
        relationship.setIsDirectRelationship(request.getIsDirectRelationship() != null ? request.getIsDirectRelationship() : true);
        relationship.setRelationshipDesc(request.getRelationshipDesc());
        relationship.setStatus("ACTIVE");
        relationship.setAssociationStartAt(LocalDateTime.now());
        relationship.setCreatorId(1L); // TODO: 获取当前登录用户ID
        relationship.setCreatedAt(LocalDateTime.now());
        relationship.setUpdatedAt(LocalDateTime.now());
        
        // 获取客户和父客户信息
        Customer customer = getCustomerById(request.getCustomerId());
        if (customer != null) {
            relationship.setCustomerName(customer.getCustomerName());
        }
        
        if (request.getParentCustomerId() != null) {
            Customer parent = getCustomerById(request.getParentCustomerId());
            if (parent != null) {
                relationship.setParentCustomerName(parent.getCustomerName());
                
                // 构建层级路径
                if (StringUtils.hasText(parent.getLevelPath())) {
                    relationship.setLevelPath(parent.getLevelPath() + request.getCustomerId() + "/");
                } else {
                    relationship.setLevelPath("/" + request.getParentCustomerId() + "/" + request.getCustomerId() + "/");
                }
                
                // 计算深度
                relationship.setDepth(countDepth(relationship.getLevelPath()));
            }
        } else {
            // 顶级，总店
            relationship.setLevelPath("/" + request.getCustomerId() + "/");
            relationship.setDepth(1);
        }
        
        relationshipRepository.insert(relationship);
        log.info("客户关系创建成功: id={}, customerId={}, parentId={}", 
                relationship.getId(), relationship.getCustomerId(), relationship.getParentCustomerId());
        
        // 更新客户表的层级信息
        updateCustomerRelationshipInfo(request.getCustomerId(), relationship);
        
        return relationship;
    }
    
    @Override
    @Transactional
    public CustomerRelationship updateRelationship(Long id, CustomerRelationshipRequest request) {
        CustomerRelationship existing = getRelationshipById(id);
        if (existing == null) {
            throw new RuntimeException("客户关系不存在: " + id);
        }
        
        if (request.getRelationshipLevel() != null) {
            existing.setRelationshipLevel(request.getRelationshipLevel());
        }
        if (StringUtils.hasText(request.getRelationshipType())) {
            existing.setRelationshipType(request.getRelationshipType());
        }
        if (request.getIsHeadquarters() != null) {
            existing.setIsHeadquarters(request.getIsHeadquarters());
        }
        if (StringUtils.hasText(request.getGroupName())) {
            existing.setGroupName(request.getGroupName());
        }
        if (StringUtils.hasText(request.getGroupCode())) {
            existing.setGroupCode(request.getGroupCode());
        }
        if (request.getIsDirectRelationship() != null) {
            existing.setIsDirectRelationship(request.getIsDirectRelationship());
        }
        if (StringUtils.hasText(request.getRelationshipDesc())) {
            existing.setRelationshipDesc(request.getRelationshipDesc());
        }
        if (StringUtils.hasText(request.getStatus())) {
            existing.setStatus(request.getStatus());
        }
        if (StringUtils.hasText(request.getRemark())) {
            existing.setRemark(request.getRemark());
        }
        
        existing.setUpdatedAt(LocalDateTime.now());
        relationshipRepository.updateById(existing);
        log.info("客户关系更新成功: id={}", id);
        
        return getRelationshipById(id);
    }
    
    @Override
    @Transactional
    public void deleteRelationship(Long id) {
        CustomerRelationship relationship = getRelationshipById(id);
        if (relationship == null) {
            throw new RuntimeException("客户关系不存在: " + id);
        }
        
        relationship.setDeletedAt(LocalDateTime.now());
        relationshipRepository.updateById(relationship);
        log.info("客户关系删除成功: id={}", id);
    }
    
    @Override
    @Transactional
    public CustomerRelationship terminateRelationship(Long id) {
        CustomerRelationship relationship = getRelationshipById(id);
        if (relationship == null) {
            throw new RuntimeException("客户关系不存在: " + id);
        }
        
        relationship.setStatus("TERMINATED");
        relationship.setAssociationEndAt(LocalDateTime.now());
        relationship.setUpdatedAt(LocalDateTime.now());
        relationshipRepository.updateById(relationship);
        
        log.info("客户关系解除: id={}, customerId={}", id, relationship.getCustomerId());
        return getRelationshipById(id);
    }
    
    @Override
    public List<CustomerRelationship> getBranchesByCustomerId(Long customerId) {
        return relationshipRepository.findActiveBranchesByParentId(customerId);
    }
    
    @Override
    public List<CustomerRelationship> getAllBranchesByHeadquartersId(Long headquartersId) {
        return relationshipRepository.findAllBranchesByHeadquartersId(headquartersId);
    }
    
    @Override
    public CustomerRelationship getParentByCustomerId(Long customerId) {
        LambdaQueryWrapper<CustomerRelationship> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerRelationship::getCustomerId, customerId)
                   .eq(CustomerRelationship::getStatus, "ACTIVE")
                   .isNull(CustomerRelationship::getDeletedAt);
        
        List<CustomerRelationship> relationships = relationshipRepository.selectList(queryWrapper);
        if (relationships.isEmpty()) {
            return null;
        }
        
        // 返回直接上级（层级路径最短的那个）
        return relationships.stream()
                .filter(r -> r.getLevelPath() != null)
                .reduce((first, second) -> 
                    first.getLevelPath().length() < second.getLevelPath().length() ? first : second)
                .orElse(relationships.get(0));
    }
    
    @Override
    public CustomerRelationship getDirectParentByCustomerId(Long customerId) {
        LambdaQueryWrapper<CustomerRelationship> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerRelationship::getCustomerId, customerId)
                   .eq(CustomerRelationship::getIsDirectRelationship, true)
                   .eq(CustomerRelationship::getStatus, "ACTIVE")
                   .isNull(CustomerRelationship::getDeletedAt);
        
        List<CustomerRelationship> relationships = relationshipRepository.selectList(queryWrapper);
        return relationships.isEmpty() ? null : relationships.get(0);
    }
    
    @Override
    public List<CustomerRelationship> getAllHeadquarters(Long tenantId) {
        return relationshipRepository.findAllHeadquarters(tenantId);
    }
    
    @Override
    public List<CustomerRelationship> getByGroupName(Long tenantId, String groupName) {
        return relationshipRepository.findByGroupName(tenantId, groupName);
    }
    
    @Override
    public Long countBranchesByCustomerId(Long customerId) {
        return relationshipRepository.countActiveBranchesByCustomerId(customerId);
    }
    
    @Override
    public List<CustomerRelationship> getAllRelatedRelationships(Long customerId) {
        return relationshipRepository.findRelatedByLevelPath(customerId);
    }
    
    @Override
    @Transactional
    public CustomerRelationship transferCustomer(Long customerId, Long newParentId, Integer newLevel) {
        CustomerRelationship relationship = getRelationshipById(customerId);
        if (relationship == null) {
            // 如果关系不存在，创建新的
            CustomerRelationshipRequest request = new CustomerRelationshipRequest();
            request.setCustomerId(customerId);
            request.setParentCustomerId(newParentId);
            request.setRelationshipLevel(newLevel);
            request.setIsDirectRelationship(true);
            return createRelationship(request);
        }
        
        // 更新层级路径
        if (newParentId != null) {
            Customer parent = getCustomerById(newParentId);
            if (parent != null && StringUtils.hasText(parent.getLevelPath())) {
                relationship.setLevelPath(parent.getLevelPath() + customerId + "/");
            }
            relationship.setParentCustomerId(newParentId);
        }
        
        if (newLevel != null) {
            relationship.setRelationshipLevel(newLevel);
        }
        
        relationship.setDepth(countDepth(relationship.getLevelPath()));
        relationship.setUpdatedAt(LocalDateTime.now());
        relationshipRepository.updateById(relationship);
        
        log.info("客户转移成功: customerId={}, newParentId={}, newLevel={}", customerId, newParentId, newLevel);
        return relationship;
    }
    
    /**
     * 获取客户信息
     */
    private Customer getCustomerById(Long customerId) {
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getId, customerId).isNull(Customer::getDeletedAt);
        return customerRepository.selectOne(queryWrapper);
    }
    
    /**
     * 计算层级深度
     */
    private Integer countDepth(String levelPath) {
        if (levelPath == null || levelPath.isEmpty()) {
            return 1;
        }
        return (int) levelPath.chars().filter(ch -> ch == '/').count() - 1;
    }
    
    /**
     * 更新客户表的层级信息
     */
    private void updateCustomerRelationshipInfo(Long customerId, CustomerRelationship relationship) {
        Customer customer = getCustomerById(customerId);
        if (customer != null) {
            customer.setParentId(relationship.getParentCustomerId());
            customer.setRelationshipLevel(relationship.getRelationshipLevel());
            customer.setIsHeadquarters(relationship.getIsHeadquarters());
            customer.setGroupName(relationship.getGroupName());
            customer.setLevelPath(relationship.getLevelPath());
            customerRepository.updateById(customer);
        }
    }
}
