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.entity.CustomerContact;
import com.erp.customer.repository.CustomerContactRepository;
import com.erp.customer.service.CustomerContactService;
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实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerContactServiceImpl extends ServiceImpl<CustomerContactRepository, CustomerContact> 
        implements CustomerContactService {
    
    private final CustomerContactRepository contactRepository;
    
    @Override
    public List<CustomerContact> getContactsByCustomerId(Long customerId) {
        return contactRepository.findByCustomerId(customerId);
    }
    
    @Override
    public CustomerContact getPrimaryContact(Long customerId) {
        return contactRepository.findPrimaryByCustomerId(customerId);
    }
    
    @Override
    public CustomerContact getContactById(Long id) {
        LambdaQueryWrapper<CustomerContact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContact::getId, id).isNull(CustomerContact::getDeletedAt);
        return contactRepository.selectOne(queryWrapper);
    }
    
    @Override
    @Transactional
    public CustomerContact createContact(Long customerId, CustomerContact contact) {
        if (contact.getTenantId() == null) {
            throw new RuntimeException("租户ID不能为空");
        }
        
        contact.setCustomerId(customerId);
        contact.setCreatedAt(LocalDateTime.now());
        contact.setUpdatedAt(LocalDateTime.now());
        contact.setCreatorId(1L); // TODO: 获取当前登录用户ID
        
        // 如果设置为默认联系人，先取消其他默认
        if (Boolean.TRUE.equals(contact.getIsPrimary())) {
            clearPrimaryByCustomerId(customerId);
        }
        
        contactRepository.insert(contact);
        log.info("客户联系人创建成功: id={}, customerId={}, contactName={}", 
                contact.getId(), customerId, contact.getContactName());
        
        return contact;
    }
    
    @Override
    @Transactional
    public CustomerContact updateContact(Long id, CustomerContact contact) {
        CustomerContact existing = getContactById(id);
        if (existing == null) {
            throw new RuntimeException("联系人不存在: " + id);
        }
        
        if (StringUtils.hasText(contact.getContactName())) {
            existing.setContactName(contact.getContactName());
        }
        if (StringUtils.hasText(contact.getGender())) {
            existing.setGender(contact.getGender());
        }
        if (StringUtils.hasText(contact.getDepartment())) {
            existing.setDepartment(contact.getDepartment());
        }
        if (StringUtils.hasText(contact.getPosition())) {
            existing.setPosition(contact.getPosition());
        }
        if (StringUtils.hasText(contact.getMobile())) {
            existing.setMobile(contact.getMobile());
        }
        if (StringUtils.hasText(contact.getOfficePhone())) {
            existing.setOfficePhone(contact.getOfficePhone());
        }
        if (StringUtils.hasText(contact.getPrivatePhone())) {
            existing.setPrivatePhone(contact.getPrivatePhone());
        }
        if (StringUtils.hasText(contact.getEmail())) {
            existing.setEmail(contact.getEmail());
        }
        if (StringUtils.hasText(contact.getWechat())) {
            existing.setWechat(contact.getWechat());
        }
        if (StringUtils.hasText(contact.getQq())) {
            existing.setQq(contact.getQq());
        }
        if (StringUtils.hasText(contact.getContactType())) {
            existing.setContactType(contact.getContactType());
        }
        if (contact.getIsPrimary() != null) {
            if (Boolean.TRUE.equals(contact.getIsPrimary())) {
                clearPrimaryByCustomerId(existing.getCustomerId());
            }
            existing.setIsPrimary(contact.getIsPrimary());
        }
        if (StringUtils.hasText(contact.getInfluenceLevel())) {
            existing.setInfluenceLevel(contact.getInfluenceLevel());
        }
        if (StringUtils.hasText(contact.getCustomerFeedback())) {
            existing.setCustomerFeedback(contact.getCustomerFeedback());
        }
        if (StringUtils.hasText(contact.getRemark())) {
            existing.setRemark(contact.getRemark());
        }
        
        existing.setUpdatedAt(LocalDateTime.now());
        contactRepository.updateById(existing);
        log.info("客户联系人更新成功: id={}", id);
        
        return getContactById(id);
    }
    
    @Override
    @Transactional
    public void deleteContact(Long id) {
        CustomerContact contact = getContactById(id);
        if (contact == null) {
            throw new RuntimeException("联系人不存在: " + id);
        }
        
        contact.setDeletedAt(LocalDateTime.now());
        contactRepository.updateById(contact);
        log.info("客户联系人删除成功: id={}", id);
    }
    
    @Override
    @Transactional
    public CustomerContact setPrimaryContact(Long id) {
        CustomerContact contact = getContactById(id);
        if (contact == null) {
            throw new RuntimeException("联系人不存在: " + id);
        }
        
        clearPrimaryByCustomerId(contact.getCustomerId());
        
        contact.setIsPrimary(true);
        contact.setUpdatedAt(LocalDateTime.now());
        contactRepository.updateById(contact);
        
        log.info("设置主要联系人: id={}, customerId={}", id, contact.getCustomerId());
        return getContactById(id);
    }
    
    @Override
    public CustomerContact getContactByMobile(String mobile) {
        return contactRepository.findByMobile(mobile);
    }
    
    @Override
    public CustomerContact getContactByEmail(String email) {
        return contactRepository.findByEmail(email);
    }
    
    @Override
    public Long countContactsByCustomerId(Long customerId) {
        return contactRepository.countByCustomerId(customerId);
    }
    
    @Override
    public List<CustomerContact> getHighInfluenceContacts(Long customerId) {
        return contactRepository.findHighInfluenceByCustomerId(customerId);
    }
    
    /**
     * 清除客户的所有默认联系人标记
     */
    private void clearPrimaryByCustomerId(Long customerId) {
        LambdaQueryWrapper<CustomerContact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContact::getCustomerId, customerId)
                   .eq(CustomerContact::getIsPrimary, true)
                   .isNull(CustomerContact::getDeletedAt);
        
        List<CustomerContact> primaryContacts = contactRepository.selectList(queryWrapper);
        for (CustomerContact contact : primaryContacts) {
            contact.setIsPrimary(false);
            contact.setUpdatedAt(LocalDateTime.now());
            contactRepository.updateById(contact);
        }
    }
}
