package modules.address;

import com.jfinal.plugin.activerecord.Db;
import common.model.Address;

import java.util.List;

public class AddressService {

    // 定义每个用户最大地址数量限制
    private static final int MAX_ADDRESS_COUNT = 20;
    
    private final Address dao = new Address().dao();

    public List<Address> findByUserId(Long userId) {
        return dao.find("select * from t_address where user_id = ? and is_deleted = 0 order by is_default desc, id desc", userId);
    }

    public Address findById(int id, Long userId) {
        return dao.findFirst("select * from t_address where id = ? and user_id = ? and is_deleted = 0", id, userId);
    }

    /**
     * 保存地址，如果地址数量超过上限会抛出异常
     * @param address 地址对象
     * @return 保存结果
     * @throws RuntimeException 当地址数量超过上限时抛出异常
     */
    public boolean save(Address address) throws RuntimeException {
        // 检查用户地址数量是否已达上限
        List<Address> existingAddresses = findByUserId(address.getUserId().longValue());
        if (existingAddresses != null && existingAddresses.size() >= MAX_ADDRESS_COUNT) {
            // 如果地址数量已达上限，抛出异常
            throw new RuntimeException("地址数量已达上限（最多" + MAX_ADDRESS_COUNT + "个）");
        }
        
        // 设置初始状态
        address.setIsDeleted(0);
        
        // 设置创建时间和更新时间
        long currentTime = System.currentTimeMillis();
        address.setCreateTime(currentTime);
        address.setUpdateTime(currentTime);
        
        // 检查用户是否有现有地址
        if (existingAddresses == null || existingAddresses.isEmpty()) {
            // 如果用户没有地址，则自动将新地址设为默认地址
            address.setIsDefault(1);
        }
        
        if (address.getIsDefault() == 1) {
            // 如果将当前地址设为默认，则将该用户其他地址设为非默认
            Db.update("update t_address set is_default = 0, update_time = ? where user_id = ?", 
                    currentTime, address.getUserId());
        }
        return address.save();
    }

    public boolean update(Address address) {
        // 设置更新时间
        address.setUpdateTime(System.currentTimeMillis());
        
        if (address.getIsDefault() == 1) {
            // 如果将当前地址设为默认，则将该用户其他地址设为非默认
            Db.update("update t_address set is_default = 0, update_time = ? where user_id = ?", 
                    System.currentTimeMillis(), address.getUserId());
        }
        return address.update();
    }

    public boolean delete(int id, Long userId) {
        Address address = findById(id, userId);
        if (address == null) {
            return false;
        }
        
        address.setIsDeleted(1);
        return address.update();
    }

    public Address findDefaultByUserId(Long userId) {
        return dao.findFirst("select * from t_address where user_id = ? and is_default = 1 and is_deleted = 0", userId);
    }

    public boolean setDefault(int id, Long userId) {
        // 开启事务
        return Db.tx(() -> {
            long currentTime = System.currentTimeMillis();
            // 先将该用户所有地址设为非默认
            Db.update("update t_address set is_default = 0, update_time = ? where user_id = ?", currentTime, userId);
            // 再将指定地址设为默认
            return Db.update("update t_address set is_default = 1, update_time = ? where id = ? and user_id = ?", currentTime, id, userId) > 0;
        });
    }
}