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 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.MallSeckill;
import org.dromara.mall.promotion.domain.bo.MallSeckillBo;
import org.dromara.mall.promotion.domain.vo.MallSeckillVo;
import org.dromara.mall.promotion.mapper.MallSeckillMapper;
import org.dromara.mall.promotion.service.MallSeckillService;
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 MallSeckillServiceImpl implements MallSeckillService {

    private final MallSeckillMapper baseMapper;

    /**
     * 查询秒杀活动
     */
    @Override
    public MallSeckillVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询秒杀活动列表
     */
    @Override
    public TableDataInfo<MallSeckillVo> queryPageList(MallSeckillBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallSeckill> lqw = buildQueryWrapper(bo);
        Page<MallSeckillVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询秒杀活动列表
     */
    @Override
    public List<MallSeckillVo> queryList(MallSeckillBo bo) {
        LambdaQueryWrapper<MallSeckill> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallSeckill> buildQueryWrapper(MallSeckillBo bo) {
        LambdaQueryWrapper<MallSeckill> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPromotionId() != null, MallSeckill::getPromotionId, bo.getPromotionId());
        lqw.eq(bo.getSkuId() != null, MallSeckill::getSkuId, bo.getSkuId());
        lqw.eq(bo.getStatus() != null, MallSeckill::getStatus, bo.getStatus());
        lqw.ge(bo.getStartTime() != null, MallSeckill::getStartTime, bo.getStartTime());
        lqw.le(bo.getEndTime() != null, MallSeckill::getEndTime, bo.getEndTime());
        lqw.orderByDesc(MallSeckill::getCreateTime);
        return lqw;
    }

    /**
     * 查询可用的秒杀活动列表（移动端）
     */
    @Override
    public List<MallSeckillVo> queryAvailableList() {
        LambdaQueryWrapper<MallSeckill> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallSeckill::getStatus, 0); // 启用状态
        Date now = new Date();
        lqw.le(MallSeckill::getStartTime, now); // 已开始
        lqw.ge(MallSeckill::getEndTime, now); // 未结束
        lqw.gt(MallSeckill::getSeckillStock, 0); // 有库存
        lqw.orderByDesc(MallSeckill::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据SKU ID查询秒杀活动
     */
    @Override
    public MallSeckillVo queryBySkuId(Long skuId) {
        LambdaQueryWrapper<MallSeckill> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallSeckill::getSkuId, skuId);
        lqw.eq(MallSeckill::getStatus, 0); // 启用状态
        Date now = new Date();
        lqw.le(MallSeckill::getStartTime, now); // 已开始
        lqw.ge(MallSeckill::getEndTime, now); // 未结束
        lqw.gt(MallSeckill::getSeckillStock, 0); // 有库存
        lqw.orderByDesc(MallSeckill::getCreateTime);
        lqw.last("LIMIT 1");
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 新增秒杀活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallSeckillBo bo) {
        MallSeckill add = MapstructUtils.convert(bo, MallSeckill.class);
        validEntityBeforeSave(add);

        // 设置默认状态
        if (add.getStatus() == null) {
            add.setStatus(0); // 默认启用
        }

        // 校验时间
        validateTimeRange(add.getStartTime(), add.getEndTime());

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

    /**
     * 修改秒杀活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallSeckillBo bo) {
        MallSeckill update = MapstructUtils.convert(bo, MallSeckill.class);
        validEntityBeforeSave(update);

        // 校验时间
        if (update.getStartTime() != null && update.getEndTime() != null) {
            validateTimeRange(update.getStartTime(), update.getEndTime());
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallSeckill entity) {
        // TODO: 可以添加业务校验逻辑，如检查活动是否存在、SKU是否存在等
    }

    /**
     * 校验时间范围
     */
    private void validateTimeRange(Date startTime, Date endTime) {
        if (startTime != null && endTime != null) {
            if (startTime.after(endTime)) {
                throw new ServiceException("开始时间不能晚于结束时间");
            }
        }
    }

    /**
     * 批量删除秒杀活动
     */
    @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) {
        MallSeckill seckill = baseMapper.selectById(id);
        if (seckill == null) {
            throw new ServiceException("秒杀活动不存在");
        }

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

    /**
     * 扣减秒杀库存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reduceStock(Long id, Integer quantity) {
        if (quantity == null || quantity <= 0) {
            throw new ServiceException("扣减数量必须大于0");
        }

        MallSeckill seckill = baseMapper.selectById(id);
        if (seckill == null) {
            throw new ServiceException("秒杀活动不存在");
        }

        if (seckill.getSeckillStock() < quantity) {
            throw new ServiceException("秒杀库存不足");
        }

        int rows = baseMapper.reduceStock(id, quantity);
        return rows > 0;
    }

    /**
     * 恢复秒杀库存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean restoreStock(Long id, Integer quantity) {
        if (quantity == null || quantity <= 0) {
            throw new ServiceException("恢复数量必须大于0");
        }

        MallSeckill seckill = baseMapper.selectById(id);
        if (seckill == null) {
            throw new ServiceException("秒杀活动不存在");
        }

        int rows = baseMapper.restoreStock(id, quantity);
        return rows > 0;
    }

    /**
     * 检查秒杀活动是否可用
     */
    @Override
    public Boolean checkAvailable(Long id) {
        MallSeckill seckill = baseMapper.selectById(id);
        if (seckill == null) {
            return false;
        }

        // 检查状态
        if (seckill.getStatus() != 0) {
            return false;
        }

        // 检查时间
        Date now = new Date();
        if (seckill.getStartTime().after(now) || seckill.getEndTime().before(now)) {
            return false;
        }

        // 检查库存
        if (seckill.getSeckillStock() <= 0) {
            return false;
        }

        return true;
    }

}
