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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.mall.promotion.domain.MallGroupBuy;
import org.dromara.mall.promotion.domain.bo.MallGroupBuyBo;
import org.dromara.mall.promotion.domain.vo.MallGroupBuyVo;
import org.dromara.mall.promotion.mapper.MallGroupBuyMapper;
import org.dromara.mall.promotion.service.MallGroupBuyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 拼团活动Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class MallGroupBuyServiceImpl extends ServiceImpl<MallGroupBuyMapper, MallGroupBuy> implements MallGroupBuyService {

    private final MallGroupBuyMapper baseMapper;

    /**
     * 查询拼团活动
     */
    @Override
    public MallGroupBuyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询拼团活动列表
     */
    @Override
    public TableDataInfo<MallGroupBuyVo> queryPageList(MallGroupBuyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallGroupBuy> lqw = buildQueryWrapper(bo);
        Page<MallGroupBuyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询拼团活动列表
     */
    @Override
    public List<MallGroupBuyVo> queryList(MallGroupBuyBo bo) {
        LambdaQueryWrapper<MallGroupBuy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallGroupBuy> buildQueryWrapper(MallGroupBuyBo bo) {
        LambdaQueryWrapper<MallGroupBuy> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPromotionId() != null, MallGroupBuy::getPromotionId, bo.getPromotionId());
        lqw.eq(bo.getSkuId() != null, MallGroupBuy::getSkuId, bo.getSkuId());
        lqw.eq(bo.getStatus() != null, MallGroupBuy::getStatus, bo.getStatus());
        lqw.orderByDesc(MallGroupBuy::getCreateTime);
        return lqw;
    }

    /**
     * 查询可用的拼团活动列表（移动端）
     */
    @Override
    public List<MallGroupBuyVo> queryAvailableList() {
        LambdaQueryWrapper<MallGroupBuy> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallGroupBuy::getStatus, 0); // 启用状态
        lqw.orderByDesc(MallGroupBuy::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据SKU ID查询拼团活动
     */
    @Override
    public MallGroupBuyVo queryBySkuId(Long skuId) {
        LambdaQueryWrapper<MallGroupBuy> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallGroupBuy::getSkuId, skuId);
        lqw.eq(MallGroupBuy::getStatus, 0); // 启用状态
        lqw.orderByDesc(MallGroupBuy::getCreateTime);
        lqw.last("LIMIT 1");
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 新增拼团活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallGroupBuyBo bo) {
        MallGroupBuy add = MapstructUtils.convert(bo, MallGroupBuy.class);
        validEntityBeforeSave(add);

        // 设置默认值
        if (add.getStatus() == null) {
            add.setStatus(0); // 默认启用
        }
        if (add.getDurationHours() == null) {
            add.setDurationHours(24); // 默认24小时
        }

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

    /**
     * 修改拼团活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallGroupBuyBo bo) {
        MallGroupBuy update = MapstructUtils.convert(bo, MallGroupBuy.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallGroupBuy entity) {
        // TODO: 可以添加业务校验逻辑，如检查活动是否存在、SKU是否存在等
        if (entity.getGroupSize() != null && entity.getGroupSize() < 2) {
            throw new ServiceException("成团人数至少为2人");
        }
    }

    /**
     * 批量删除拼团活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO: 可以添加业务校验逻辑，如检查是否有进行中的拼团活动等
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 启用/禁用拼团活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeStatus(Long id, Integer status) {
        MallGroupBuy groupBuy = baseMapper.selectById(id);
        if (groupBuy == null) {
            throw new ServiceException("拼团活动不存在");
        }

        MallGroupBuy update = new MallGroupBuy();
        update.setId(id);
        update.setStatus(status);
        return baseMapper.updateById(update) > 0;
    }

}
