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.CustomerFollowUpRequest;
import com.erp.customer.entity.Customer;
import com.erp.customer.entity.CustomerFollowUp;
import com.erp.customer.repository.CustomerFollowUpRepository;
import com.erp.customer.repository.CustomerRepository;
import com.erp.customer.service.CustomerFollowUpService;
import com.erp.customer.service.CustomerService;
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 CustomerFollowUpServiceImpl extends ServiceImpl<CustomerFollowUpRepository, CustomerFollowUp> 
        implements CustomerFollowUpService {
    
    private final CustomerFollowUpRepository followUpRepository;
    private final CustomerRepository customerRepository;
    private final CustomerService customerService;
    
    @Override
    public List<CustomerFollowUp> listFollowUps(Long tenantId, Long customerId, String followType,
                                                 Long userId, String status, Integer page, Integer size) {
        int offset = (page - 1) * size;
        
        LambdaQueryWrapper<CustomerFollowUp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(CustomerFollowUp::getDeletedAt);
        
        if (tenantId != null) {
            queryWrapper.eq(CustomerFollowUp::getTenantId, tenantId);
        }
        if (customerId != null) {
            queryWrapper.eq(CustomerFollowUp::getCustomerId, customerId);
        }
        if (StringUtils.hasText(followType)) {
            queryWrapper.eq(CustomerFollowUp::getFollowType, followType);
        }
        if (userId != null) {
            queryWrapper.eq(CustomerFollowUp::getFollowUpUserId, userId);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(CustomerFollowUp::getStatus, status);
        }
        
        queryWrapper.orderByDesc(CustomerFollowUp::getFollowUpAt);
        queryWrapper.last("LIMIT " + offset + ", " + size);
        
        return followUpRepository.selectList(queryWrapper);
    }
    
    @Override
    public CustomerFollowUp getFollowUpById(Long id) {
        LambdaQueryWrapper<CustomerFollowUp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerFollowUp::getId, id).isNull(CustomerFollowUp::getDeletedAt);
        return followUpRepository.selectOne(queryWrapper);
    }
    
    @Override
    @Transactional
    public CustomerFollowUp createFollowUp(CustomerFollowUpRequest request) {
        CustomerFollowUp followUp = new CustomerFollowUp();
        followUp.setTenantId(request.getTenantId());
        followUp.setCustomerId(request.getCustomerId());
        followUp.setCustomerName(request.getCustomerName());
        followUp.setFollowType(request.getFollowType());
        followUp.setSubject(request.getSubject());
        followUp.setContent(request.getContent());
        followUp.setResult(request.getResult());
        followUp.setIntentionLevel(request.getIntentionLevel());
        followUp.setNextFollowUpAt(request.getNextFollowUpAt());
        followUp.setNextFollowUpPlan(request.getNextFollowUpPlan());
        followUp.setAttachments(request.getAttachments());
        followUp.setStatus(request.getStatus() != null ? request.getStatus() : "PENDING");
        followUp.setFollowUpUserId(request.getFollowUpUserId());
        followUp.setFollowUpUserName(request.getFollowUpUserName());
        followUp.setDepartment(request.getDepartment());
        followUp.setRemark(request.getRemark());
        followUp.setFollowUpAt(LocalDateTime.now());
        followUp.setCreatedAt(LocalDateTime.now());
        followUp.setUpdatedAt(LocalDateTime.now());
        
        followUpRepository.insert(followUp);
        log.info("客户跟进记录创建成功: id={}, customerId={}", followUp.getId(), followUp.getCustomerId());
        
        // 更新客户最近联系时间
        if (request.getCustomerId() != null) {
            customerService.updateLastContactTime(request.getCustomerId());
        }
        
        return followUp;
    }
    
    @Override
    @Transactional
    public CustomerFollowUp updateFollowUp(Long id, CustomerFollowUpRequest request) {
        CustomerFollowUp existing = getFollowUpById(id);
        if (existing == null) {
            throw new RuntimeException("跟进记录不存在: " + id);
        }
        
        if (StringUtils.hasText(request.getFollowType())) {
            existing.setFollowType(request.getFollowType());
        }
        if (StringUtils.hasText(request.getSubject())) {
            existing.setSubject(request.getSubject());
        }
        if (StringUtils.hasText(request.getContent())) {
            existing.setContent(request.getContent());
        }
        if (StringUtils.hasText(request.getResult())) {
            existing.setResult(request.getResult());
        }
        if (StringUtils.hasText(request.getIntentionLevel())) {
            existing.setIntentionLevel(request.getIntentionLevel());
        }
        if (request.getNextFollowUpAt() != null) {
            existing.setNextFollowUpAt(request.getNextFollowUpAt());
        }
        if (StringUtils.hasText(request.getNextFollowUpPlan())) {
            existing.setNextFollowUpPlan(request.getNextFollowUpPlan());
        }
        if (StringUtils.hasText(request.getAttachments())) {
            existing.setAttachments(request.getAttachments());
        }
        if (StringUtils.hasText(request.getStatus())) {
            existing.setStatus(request.getStatus());
        }
        if (StringUtils.hasText(request.getRemark())) {
            existing.setRemark(request.getRemark());
        }
        
        existing.setUpdatedAt(LocalDateTime.now());
        followUpRepository.updateById(existing);
        log.info("客户跟进记录更新成功: id={}", id);
        
        return getFollowUpById(id);
    }
    
    @Override
    @Transactional
    public void deleteFollowUp(Long id) {
        CustomerFollowUp followUp = getFollowUpById(id);
        if (followUp == null) {
            throw new RuntimeException("跟进记录不存在: " + id);
        }
        
        followUp.setDeletedAt(LocalDateTime.now());
        followUpRepository.updateById(followUp);
        log.info("客户跟进记录删除成功: id={}", id);
    }
    
    @Override
    @Transactional
    public CustomerFollowUp completeFollowUp(Long id) {
        CustomerFollowUp followUp = getFollowUpById(id);
        if (followUp == null) {
            throw new RuntimeException("跟进记录不存在: " + id);
        }
        
        followUp.setStatus("DONE");
        followUp.setUpdatedAt(LocalDateTime.now());
        followUpRepository.updateById(followUp);
        log.info("客户跟进记录完成: id={}", id);
        
        return getFollowUpById(id);
    }
    
    @Override
    @Transactional
    public CustomerFollowUp cancelFollowUp(Long id) {
        CustomerFollowUp followUp = getFollowUpById(id);
        if (followUp == null) {
            throw new RuntimeException("跟进记录不存在: " + id);
        }
        
        followUp.setStatus("CANCELLED");
        followUp.setUpdatedAt(LocalDateTime.now());
        followUpRepository.updateById(followUp);
        log.info("客户跟进记录取消: id={}", id);
        
        return getFollowUpById(id);
    }
    
    @Override
    public List<CustomerFollowUp> getFollowUpsByCustomerId(Long customerId, Integer limit) {
        return followUpRepository.findByCustomerId(customerId, 0L, limit);
    }
    
    @Override
    public CustomerFollowUp getLatestFollowUp(Long customerId) {
        return followUpRepository.findLatestByCustomerId(customerId);
    }
    
    @Override
    public List<CustomerFollowUp> getPendingFollowUps(Long tenantId) {
        return followUpRepository.findPendingFollowUps(tenantId, LocalDateTime.now().plusDays(7));
    }
    
    @Override
    public List<CustomerFollowUp> getTodayFollowUps(Long tenantId) {
        return followUpRepository.findTodayFollowUps(tenantId, LocalDateTime.now());
    }
    
    @Override
    public Long countFollowUpsByCustomerId(Long customerId) {
        return followUpRepository.countByCustomerId(customerId);
    }
    
    @Override
    public Long countFollowUpsByUserId(Long tenantId, Long userId) {
        return followUpRepository.countByFollowUpUserId(tenantId, userId);
    }
    
    @Override
    public List<CustomerFollowUp> getFollowUpsByDateRange(Long tenantId, LocalDateTime startAt, LocalDateTime endAt) {
        return followUpRepository.findByDateRange(tenantId, startAt, endAt);
    }
}
