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.CustomerAddress;
import com.erp.customer.repository.CustomerAddressRepository;
import com.erp.customer.service.CustomerAddressService;
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 CustomerAddressServiceImpl extends ServiceImpl<CustomerAddressRepository, CustomerAddress> 
        implements CustomerAddressService {
    
    private final CustomerAddressRepository addressRepository;
    
    @Override
    public List<CustomerAddress> getAddressesByCustomerId(Long customerId) {
        return addressRepository.findByCustomerId(customerId);
    }
    
    @Override
    public CustomerAddress getDefaultAddress(Long customerId) {
        return addressRepository.findDefaultByCustomerId(customerId);
    }
    
    @Override
    public CustomerAddress getAddressById(Long id) {
        LambdaQueryWrapper<CustomerAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerAddress::getId, id).isNull(CustomerAddress::getDeletedAt);
        return addressRepository.selectOne(queryWrapper);
    }
    
    @Override
    @Transactional
    public CustomerAddress createAddress(Long customerId, CustomerAddress address) {
        if (address.getTenantId() == null) {
            throw new RuntimeException("租户ID不能为空");
        }
        
        address.setCustomerId(customerId);
        address.setCreatedAt(LocalDateTime.now());
        address.setUpdatedAt(LocalDateTime.now());
        address.setCreatorId(1L); // TODO: 获取当前登录用户ID
        
        // 如果设置为默认地址，先取消其他默认
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            clearDefaultByCustomerId(customerId);
        }
        
        // 自动拼接完整地址
        if (StringUtils.hasText(address.getProvince()) && StringUtils.hasText(address.getCity()) 
            && StringUtils.hasText(address.getDistrict())) {
            address.setFullAddress(address.getProvince() + address.getCity() + address.getDistrict() 
                    + (StringUtils.hasText(address.getStreet()) ? address.getStreet() : ""));
        }
        
        addressRepository.insert(address);
        log.info("客户地址创建成功: id={}, customerId={}, fullAddress={}", 
                address.getId(), customerId, address.getFullAddress());
        
        return address;
    }
    
    @Override
    @Transactional
    public CustomerAddress updateAddress(Long id, CustomerAddress address) {
        CustomerAddress existing = getAddressById(id);
        if (existing == null) {
            throw new RuntimeException("地址不存在: " + id);
        }
        
        if (StringUtils.hasText(address.getReceiverName())) {
            existing.setReceiverName(address.getReceiverName());
        }
        if (StringUtils.hasText(address.getReceiverPhone())) {
            existing.setReceiverPhone(address.getReceiverPhone());
        }
        if (StringUtils.hasText(address.getReceiverMobile())) {
            existing.setReceiverMobile(address.getReceiverMobile());
        }
        if (StringUtils.hasText(address.getProvince())) {
            existing.setProvince(address.getProvince());
        }
        if (StringUtils.hasText(address.getCity())) {
            existing.setCity(address.getCity());
        }
        if (StringUtils.hasText(address.getDistrict())) {
            existing.setDistrict(address.getDistrict());
        }
        if (StringUtils.hasText(address.getStreet())) {
            existing.setStreet(address.getStreet());
        }
        if (StringUtils.hasText(address.getPostalCode())) {
            existing.setPostalCode(address.getPostalCode());
        }
        if (StringUtils.hasText(address.getAddressType())) {
            existing.setAddressType(address.getAddressType());
        }
        if (address.getLongitude() != null) {
            existing.setLongitude(address.getLongitude());
        }
        if (address.getLatitude() != null) {
            existing.setLatitude(address.getLatitude());
        }
        if (address.getIsDefault() != null) {
            if (Boolean.TRUE.equals(address.getIsDefault())) {
                clearDefaultByCustomerId(existing.getCustomerId());
            }
            existing.setIsDefault(address.getIsDefault());
        }
        if (StringUtils.hasText(address.getRemark())) {
            existing.setRemark(address.getRemark());
        }
        
        // 更新完整地址
        existing.setFullAddress(existing.getProvince() + existing.getCity() + existing.getDistrict() 
                + (StringUtils.hasText(existing.getStreet()) ? existing.getStreet() : ""));
        
        existing.setUpdatedAt(LocalDateTime.now());
        addressRepository.updateById(existing);
        log.info("客户地址更新成功: id={}", id);
        
        return getAddressById(id);
    }
    
    @Override
    @Transactional
    public void deleteAddress(Long id) {
        CustomerAddress address = getAddressById(id);
        if (address == null) {
            throw new RuntimeException("地址不存在: " + id);
        }
        
        address.setDeletedAt(LocalDateTime.now());
        addressRepository.updateById(address);
        log.info("客户地址删除成功: id={}", id);
    }
    
    @Override
    @Transactional
    public CustomerAddress setDefaultAddress(Long id) {
        CustomerAddress address = getAddressById(id);
        if (address == null) {
            throw new RuntimeException("地址不存在: " + id);
        }
        
        clearDefaultByCustomerId(address.getCustomerId());
        
        address.setIsDefault(true);
        address.setUpdatedAt(LocalDateTime.now());
        addressRepository.updateById(address);
        
        log.info("设置默认地址: id={}, customerId={}", id, address.getCustomerId());
        return getAddressById(id);
    }
    
    @Override
    public List<CustomerAddress> getDeliveryAddresses(Long customerId) {
        return addressRepository.findDeliveryAddresses(customerId);
    }
    
    @Override
    public List<CustomerAddress> getAddressesByType(Long customerId, String addressType) {
        return addressRepository.findByCustomerIdAndAddressType(customerId, addressType);
    }
    
    @Override
    public Long countAddressesByCustomerId(Long customerId) {
        return addressRepository.countByCustomerId(customerId);
    }
    
    /**
     * 清除客户的所有默认地址标记
     */
    private void clearDefaultByCustomerId(Long customerId) {
        LambdaQueryWrapper<CustomerAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerAddress::getCustomerId, customerId)
                   .eq(CustomerAddress::getIsDefault, true)
                   .isNull(CustomerAddress::getDeletedAt);
        
        List<CustomerAddress> defaultAddresses = addressRepository.selectList(queryWrapper);
        for (CustomerAddress address : defaultAddresses) {
            address.setIsDefault(false);
            address.setUpdatedAt(LocalDateTime.now());
            addressRepository.updateById(address);
        }
    }
}
