package com.ylx.collect.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylx.base.BaseServiceImpl;
import com.ylx.collect.domain.Collect;
import com.ylx.collect.domain.dto.CollectOperateDTO;
import com.ylx.collect.domain.dto.CollectSearchDTO;
import com.ylx.collect.domain.vo.CollectPageVO;
import com.ylx.collect.mapper.CollectMapper;
import com.ylx.collect.service.CollectService;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CollectServiceImpl extends BaseServiceImpl<CollectMapper, Collect> implements CollectService {

    private static final int NOT_DELETE = 0;
    private static final int DELETE = 1;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCollect(CollectOperateDTO dto) {
        // 1. 直接调用基类方法获取用户ID，无需再手动校验登录状态
        Long userId = getCurrentUserId();

        // 2. 检查是否已存在记录（包括逻辑删除的记录）
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId, userId)
                .eq(Collect::getMerchantId, dto.getMerchantId());

        Collect existCollect = this.getOne(queryWrapper);

        if (ObjectUtil.isNotNull(existCollect)) {
            // 3. 如果存在，判断状态
            if (ObjectUtil.equals(NOT_DELETE, existCollect.getIsDelete())) {
                return true;
            } else {
                // 4. 如果是之前取消收藏过的（逻辑删除状态），则恢复（更新）
                existCollect.setIsDelete(NOT_DELETE);
                existCollect.setUpdateTime(DateUtils.getNowDate());
                existCollect.setUpdateBy(getCurrentUserNickName());
                return this.updateById(existCollect);
            }
        }

        // 5. 执行新增
        Collect collect = new Collect();
        collect.setUserId(userId);
        collect.setMerchantId(dto.getMerchantId());
        collect.setCreateTime(DateUtils.getNowDate());
        collect.setCreateBy(getCurrentUserNickName());
        collect.setIsDelete(NOT_DELETE);
        return this.save(collect);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelCollect(CollectOperateDTO dto) {
        // 1. 获取当前用户
        Long userId = getCurrentUserId();

        Collect updateEntity = new Collect();
        updateEntity.setIsDelete(DELETE);
        updateEntity.setUpdateTime(DateUtils.getNowDate());
        updateEntity.setUpdateBy(getCurrentUserNickName());

        // 2. 构造删除条件
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUserId, userId)
                .eq(Collect::getIsDelete, NOT_DELETE)
                .eq(Collect::getMerchantId, dto.getMerchantId());

        // 3. 执行逻辑删除
        return this.update(updateEntity, wrapper);
    }

    @Override
    public Page<CollectPageVO> page(CollectSearchDTO dto) {

        // 1. 获取当前用户，确保只能查自己的收藏
        Long userId = getCurrentUserId();
        dto.setUserId(userId);

        // 2. 构建分页对象
        Page<CollectPageVO> page = new Page<>(dto.getCurrent(), dto.getSize());
        page = this.baseMapper.selectMyCollectPage(page, dto);

        return page;
    }

    @Override
    public boolean isCollected(Long merchantId) {
        // 1. 获取当前登录用户 ID
        Long userId = getCurrentUserId();

        // 2. 构造查询条件
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUserId, userId)           // 匹配当前用户
                .eq(Collect::getMerchantId, merchantId)   // 匹配商户ID
                .eq(Collect::getIsDelete, NOT_DELETE);    // 必须是未删除状态

        // 3. 使用 exists 判断是否存在记录
        return this.count(wrapper) > 0;
    }

}
