package com.ruoyi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.base.service.IBaseCityService;
import com.ruoyi.common.core.domain.DlBaseEntity;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.member.domain.MemberAddress;
import com.ruoyi.member.mapper.MemberAddressMapper;
import com.ruoyi.member.service.IMemberAddressService;
import com.ruoyi.member.vo.MemberUniVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 博主收货地址Service业务层处理
 *
 * @author pqz
 * @date 2025-03-17
 */
@Service
public class MemberAddressServiceImpl extends ServiceImpl<MemberAddressMapper, MemberAddress> implements IMemberAddressService {
    @Autowired
    private MemberAddressMapper memberAddressMapper;
    @Resource
    private IBaseCityService cityService;


    /**
     * 根据用户id查询
     *
     * @param userId 用户id
     * @return java.util.List<com.ruoyi.member.domain.MemberAddress>
     * @author PQZ
     * @date 10:40 2025/3/29
     **/
    @Override
    public List<MemberAddress> listByUserId(Long userId) {
        LambdaQueryWrapper<MemberAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DlBaseEntity::getDelFlag, 0)
                .eq(MemberAddress::getUserId, userId)
                .orderByDesc(MemberAddress::getIsDefault)
                .orderByDesc(DlBaseEntity::getCreateTime);
        return list(lambdaQueryWrapper);
    }

    /**
     * 保存博主地址信息
     *
     * @param address {@link MemberAddress}
     * @author PQZ
     * @date 10:12 2025/4/3
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMemberAddress(MemberAddress address) {
        Long userId = SecurityUtils.getUserId();
        address.setUserId(userId);
        if (address.getCityId() != null) {
            String cityName = cityService.getCityName(address.getCityId());
            address.setCityName(cityName);
        }
        //默认地址情况，需要修改原来的默认地址为不默认
        if ("1".equals(address.getIsDefault())) {
            updateIsDefault(userId);
        }
        //保存
        saveOrUpdate(address);
    }

    /**
     * 设置地址为默认地址
     *
     * @param id id
     * @author PQZ
     * @date 11:07 2025/4/3
     **/
    @Override
    public void setDefault(String id) {
        MemberAddress address = getById(id);
        //修改原有地址的默认状态
        updateIsDefault(address.getUserId());
        //设置现有地址默认状态
        address.setIsDefault("1");
        updateById(address);
    }

    /**
     * uniApp选择地址使用
     *
     * @return java.util.List<com.ruoyi.member.vo.MemberUniVO>
     * @author PQZ
     * @date 14:14 2025/4/3
     **/
    @Override
    public List<MemberUniVO> uniSelectList() {
        //查询当前登录用户地址
        Long userId = SecurityUtils.getUserId();
        List<MemberAddress> addresses = listByUserId(userId);
        //类型转换
        return addresses.stream().map(item -> new MemberUniVO(item.getId(),item.getCityName()+item.getDetail())).collect(Collectors.toList());
    }

    /**
     * 修改原有地址的默认状态
     *
     * @param userId 用户id
     * @author PQZ
     * @date 10:15 2025/4/3
     **/
    private void updateIsDefault(Long userId) {
        LambdaQueryWrapper<MemberAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(MemberAddress::getIsDefault, "1")
                .eq(DlBaseEntity::getDelFlag, 0)
                .eq(MemberAddress::getUserId, userId);
        List<MemberAddress> list = list(lambdaQueryWrapper);
        //存在默认地址情况，更新为非默认状态
        if (!list.isEmpty()) {
            list.forEach(item -> {
                item.setIsDefault("0");
            });
            updateBatchById(list);
        }
    }
}
