package com.sqx.modules.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.activity.dao.ActivityPartRecordDao;
import com.sqx.modules.activity.dto.ActivityPartRecordQueryDTO;
import com.sqx.modules.activity.entity.ActivityPartRecord;
import com.sqx.modules.activity.service.ActivityPartRecordService;
import com.sqx.modules.activity.vo.ActivityPartRecordVO;
import com.sqx.modules.activity.vo.OrderSuitActivityVO;
import com.sqx.modules.order.entity.TbOrder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 活动参与记录
 * @author : codingliang
 * @date : 2024-6-24
 */
@Service
@RequiredArgsConstructor
public class ActivityPartRecordServiceImpl extends ServiceImpl<ActivityPartRecordDao, ActivityPartRecord> implements ActivityPartRecordService {

    @Override
    public PageUtils page(ActivityPartRecordQueryDTO queryDTO) {
        Page<ActivityPartRecord> pages = new Page<>(queryDTO.getPage(), queryDTO.getLimit());

        IPage<ActivityPartRecordVO> pageResult = baseMapper.pageByQuery(pages, queryDTO);
        return new PageUtils(pageResult);
    }

    @Override
    public void saveByOrderAndSuitActivityVO(TbOrder order, OrderSuitActivityVO orderBestActivity) {
        // 先清空当前活动已有的活动参与记录
        LambdaQueryWrapper<ActivityPartRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ActivityPartRecord::getOrderId, order.getOrderId());
        this.remove(queryWrapper);

        ActivityPartRecord record = new ActivityPartRecord();
        record.setOrderId(order.getOrderId());
        record.setActivityId(orderBestActivity.getActivityId());
        record.setDiscountAmount(new BigDecimal(orderBestActivity.getDiscountAmount()));
        record.setUserId(order.getUserId());
        record.setCreateTime(new Date());
        record.setGoodsId(orderBestActivity.getGoodsIds().stream().map(String::valueOf).collect(Collectors.joining(",")));
        record.setGoodsName(orderBestActivity.getGoodsNames().stream().map(String::valueOf).collect(Collectors.joining(",")));

        this.save(record);
    }

    @Override
    public ActivityPartRecordVO getVoById(Long recordId) {
        return baseMapper.getVoById(recordId);
    }

    @Override
    public ActivityPartRecord getByOrderId(Long orderId) {
        LambdaQueryWrapper<ActivityPartRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ActivityPartRecord::getOrderId, orderId);
        return this.getOne(queryWrapper);
    }
}
