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 org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.mall.promotion.domain.MallPromotion;
import org.dromara.mall.promotion.domain.bo.MallPromotionBo;
import org.dromara.mall.promotion.domain.vo.MallPromotionVo;
import org.dromara.mall.promotion.mapper.MallPromotionMapper;
import org.dromara.mall.promotion.service.MallPromotionService;
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
 */
@Service
public class MallPromotionServiceImpl extends ServiceImpl<MallPromotionMapper, MallPromotion> implements MallPromotionService {

    /**
     * 查询营销活动
     */
    @Override
    public MallPromotionVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询营销活动列表
     */
    @Override
    public TableDataInfo<MallPromotionVo> queryPageList(MallPromotionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallPromotion> lqw = buildQueryWrapper(bo);
        Page<MallPromotionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询营销活动列表
     */
    @Override
    public List<MallPromotionVo> queryList(MallPromotionBo bo) {
        LambdaQueryWrapper<MallPromotion> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallPromotion> buildQueryWrapper(MallPromotionBo bo) {
        LambdaQueryWrapper<MallPromotion> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), MallPromotion::getName, bo.getName());
        lqw.eq(bo.getType() != null, MallPromotion::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, MallPromotion::getStatus, bo.getStatus());
        lqw.ge(bo.getStartTime() != null, MallPromotion::getStartTime, bo.getStartTime());
        lqw.le(bo.getEndTime() != null, MallPromotion::getEndTime, bo.getEndTime());
        lqw.orderByDesc(MallPromotion::getCreateTime);
        return lqw;
    }

    /**
     * 新增营销活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallPromotionBo bo) {
        MallPromotion add = MapstructUtils.convert(bo, MallPromotion.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(MallPromotionBo bo) {
        MallPromotion update = MapstructUtils.convert(bo, MallPromotion.class);
        validEntityBeforeSave(update);

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

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallPromotion entity) {
        // TODO: 可以添加业务校验逻辑，如活动类型校验等
    }

    /**
     * 校验时间范围
     */
    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) {
        MallPromotion promotion = baseMapper.selectById(id);
        if (promotion == null) {
            throw new ServiceException("营销活动不存在");
        }

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

    /**
     * 根据活动类型查询活动列表
     */
    @Override
    public List<MallPromotionVo> queryListByType(Integer type) {
        LambdaQueryWrapper<MallPromotion> lqw = Wrappers.lambdaQuery();
        lqw.eq(MallPromotion::getType, type);
        lqw.eq(MallPromotion::getStatus, 0); // 只查询启用的活动
        Date now = new Date();
        lqw.le(MallPromotion::getStartTime, now); // 开始时间已到
        lqw.ge(MallPromotion::getEndTime, now); // 结束时间未到
        lqw.orderByDesc(MallPromotion::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

}
