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.MallBargain;
import org.dromara.mall.promotion.domain.MallPromotion;
import org.dromara.mall.promotion.domain.bo.MallBargainBo;
import org.dromara.mall.promotion.domain.vo.MallBargainVo;
import org.dromara.mall.promotion.mapper.MallBargainMapper;
import org.dromara.mall.promotion.mapper.MallPromotionMapper;
import org.dromara.mall.promotion.service.MallBargainService;
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 MallBargainServiceImpl extends ServiceImpl<MallBargainMapper, MallBargain> implements MallBargainService {

    private final MallBargainMapper baseMapper;
    private final MallPromotionMapper promotionMapper;

    /**
     * 查询砍价活动
     */
    @Override
    public MallBargainVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询砍价活动列表
     */
    @Override
    public TableDataInfo<MallBargainVo> queryPageList(MallBargainBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallBargain> lqw = buildQueryWrapper(bo);
        Page<MallBargainVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询砍价活动列表
     */
    @Override
    public List<MallBargainVo> queryList(MallBargainBo bo) {
        LambdaQueryWrapper<MallBargain> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 查询可用的砍价活动列表（移动端）
     */
    @Override
    public List<MallBargainVo> queryAvailableList() {
        LambdaQueryWrapper<MallBargain> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallBargain::getStatus, 0); // 启用状态
        lqw.gt(MallBargain::getBargainStock, 0); // 有库存
        lqw.orderByDesc(MallBargain::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据SKU ID查询砍价活动
     */
    @Override
    public MallBargainVo queryBySkuId(Long skuId) {
        LambdaQueryWrapper<MallBargain> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallBargain::getSkuId, skuId);
        lqw.eq(MallBargain::getStatus, 0); // 启用状态
        lqw.gt(MallBargain::getBargainStock, 0); // 有库存
        lqw.orderByDesc(MallBargain::getCreateTime);
        lqw.last("LIMIT 1");
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 新增砍价活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallBargainBo bo) {
        MallBargain add = MapstructUtils.convert(bo, MallBargain.class);
        validEntityBeforeSave(add);

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

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallBargain entity) {
        // TODO: 可以添加业务校验逻辑，如检查活动是否存在、SKU是否存在等
        if (entity.getOriginalPrice() != null && entity.getBargainPrice() != null) {
            if (entity.getBargainPrice() >= entity.getOriginalPrice()) {
                throw new ServiceException("砍后价必须小于原价");
            }
        }
        if (entity.getMinPrice() != null && entity.getBargainPrice() != null) {
            if (entity.getBargainPrice() < entity.getMinPrice()) {
                throw new ServiceException("砍后价不能小于最低价");
            }
        }
        if (entity.getMinPrice() != null && entity.getOriginalPrice() != null) {
            if (entity.getMinPrice() >= entity.getOriginalPrice()) {
                throw new ServiceException("最低价必须小于原价");
            }
        }
    }

    /**
     * 批量删除砍价活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            Date now = new Date();
            for (Long id : ids) {
                MallBargain bargain = baseMapper.selectById(id);
                if (bargain == null) {
                    continue;
                }
                
                // 检查关联的营销活动是否正在进行中
                if (bargain.getPromotionId() != null) {
                    MallPromotion promotion = promotionMapper.selectById(bargain.getPromotionId());
                    if (promotion != null && promotion.getStartTime() != null && promotion.getEndTime() != null) {
                        // 判断当前时间是否在活动时间范围内（开始时间 <= 当前时间 <= 结束时间）
                        if (!promotion.getStartTime().after(now) && !promotion.getEndTime().before(now)) {
                            throw new ServiceException("砍价活动ID[" + id + "]关联的营销活动正在进行中，不能删除");
                        }
                    }
                }
                
                // 注意：如果有砍价记录表(mall_bargain_record)，还可以检查是否有进行中的砍价记录(status=0)
                // 但由于当前模块中可能还未实现MallBargainRecordMapper，此处暂不添加该检查
                // 如需添加，可注入MallBargainRecordMapper，然后查询count(bargain_id=? AND status=0) > 0
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

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

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

}
