package org.dromara.mall.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.mall.trade.domain.MallAddress;
import org.dromara.mall.trade.domain.bo.MallAddressBo;
import org.dromara.mall.trade.domain.vo.MallAddressVo;
import org.dromara.mall.trade.mapper.MallAddressMapper;
import org.dromara.mall.trade.service.MallAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 收货地址Service业务层处理
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallAddressServiceImpl implements MallAddressService {

    private final MallAddressMapper baseMapper;

    /**
     * 查询收货地址
     */
    @Override
    public MallAddressVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询收货地址列表
     */
    @Override
    public TableDataInfo<MallAddressVo> queryPageList(MallAddressBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallAddress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoPage(pageQuery.build(), lqw);
    }

    /**
     * 查询收货地址列表
     */
    @Override
    public List<MallAddressVo> queryList(MallAddressBo bo) {
        LambdaQueryWrapper<MallAddress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户的收货地址列表
     */
    @Override
    public List<MallAddressVo> queryListByUserId(Long userId) {
        LambdaQueryWrapper<MallAddress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAddress::getUserId, userId);
        lqw.orderByDesc(MallAddress::getIsDefault);
        lqw.orderByDesc(MallAddress::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询用户的默认地址
     */
    @Override
    public MallAddressVo queryDefaultByUserId(Long userId) {
        LambdaQueryWrapper<MallAddress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAddress::getUserId, userId);
        lqw.eq(MallAddress::getIsDefault, 1);
        lqw.last("LIMIT 1");
        List<MallAddressVo> list = baseMapper.selectVoList(lqw);
        return list.isEmpty() ? null : list.get(0);
    }

    private LambdaQueryWrapper<MallAddress> buildQueryWrapper(MallAddressBo bo) {
        LambdaQueryWrapper<MallAddress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getUserId() != null, MallAddress::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getReceiverName()), MallAddress::getReceiverName, bo.getReceiverName());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverPhone()), MallAddress::getReceiverPhone, bo.getReceiverPhone());
        lqw.eq(bo.getIsDefault() != null, MallAddress::getIsDefault, bo.getIsDefault());
        lqw.orderByDesc(MallAddress::getIsDefault);
        lqw.orderByDesc(MallAddress::getCreateTime);
        return lqw;
    }

    /**
     * 新增收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallAddressBo bo) {
        MallAddress add = MapstructUtils.convert(bo, MallAddress.class);
        validEntityBeforeSave(add);

        // 设置用户ID（移动端用户）
        if (add.getUserId() == null) {
            add.setUserId(LoginHelper.getUserId());
        }

        // 如果设置为默认地址，则取消其他默认地址
        if (add.getIsDefault() != null && add.getIsDefault() == 1) {
            cancelOtherDefaultAddress(add.getUserId());
        } else {
            add.setIsDefault(0);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallAddressBo bo) {
        MallAddress update = MapstructUtils.convert(bo, MallAddress.class);
        validEntityBeforeSave(update);

        // 如果设置为默认地址，则取消其他默认地址
        if (update.getIsDefault() != null && update.getIsDefault() == 1) {
            cancelOtherDefaultAddress(update.getUserId(), update.getId());
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallAddress entity) {
        // 可以添加业务校验逻辑，如手机号格式校验等
    }

    /**
     * 取消其他默认地址
     */
    private void cancelOtherDefaultAddress(Long userId) {
        cancelOtherDefaultAddress(userId, null);
    }

    /**
     * 取消其他默认地址（排除指定地址ID）
     */
    private void cancelOtherDefaultAddress(Long userId, Long excludeId) {
        LambdaUpdateWrapper<MallAddress> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MallAddress::getUserId, userId);
        updateWrapper.eq(MallAddress::getIsDefault, 1);
        if (excludeId != null) {
            updateWrapper.ne(MallAddress::getId, excludeId);
        }
        updateWrapper.set(MallAddress::getIsDefault, 0);
        baseMapper.update(null, updateWrapper);
    }

    /**
     * 批量删除收货地址信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 设置默认地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setDefault(Long id) {
        MallAddress address = baseMapper.selectById(id);
        if (address == null) {
            throw new ServiceException("收货地址不存在");
        }

        Long userId = address.getUserId();
        if (userId == null) {
            userId = LoginHelper.getUserId();
        }

        // 取消其他默认地址
        cancelOtherDefaultAddress(userId, id);

        // 设置当前地址为默认地址
        address.setIsDefault(1);
        return baseMapper.updateById(address) > 0;
    }

}
