package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.exception.enums.GlobalErrorCodeConstants;
import com.gxwebsoft.common.core.utils.LoginUserUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.ShopFlashSaleActivity;
import com.gxwebsoft.shop.entity.ShopGoods;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.mapper.ShopFlashSaleActivityMapper;
import com.gxwebsoft.shop.mapper.ShopGoodsMapper;
import com.gxwebsoft.shop.mapper.ShopOrderMapper;
import com.gxwebsoft.shop.param.ShopFlashSaleActivityParam;
import com.gxwebsoft.shop.service.ShopFlashSaleActivityService;
import com.gxwebsoft.shop.vo.ShopFlashSaleActivityVO;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 秒杀活动Service实现
 *
 * @author xm
 * @since 2026-04-22 17:18:17
 */
@Service
@AllArgsConstructor
public class ShopFlashSaleActivityServiceImpl extends ServiceImpl<ShopFlashSaleActivityMapper, ShopFlashSaleActivity> implements ShopFlashSaleActivityService {

    private ShopGoodsMapper shopGoodsMapper;

    private ShopOrderMapper shopOrderMapper;

    @Override
    public PageResult<ShopFlashSaleActivityVO> pageRel(ShopFlashSaleActivityParam param) {
        PageParam<ShopFlashSaleActivity, ShopFlashSaleActivityParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ShopFlashSaleActivityVO> list = baseMapper.selectPageRel(page, param);
        if(CollectionUtils.isNotEmpty(list)){
            List<Integer> goodsIdList = list.stream().map(ShopFlashSaleActivityVO::getGoodsId).distinct().collect(Collectors.toList());
            List<ShopGoods> shopGoods = shopGoodsMapper.selectBatchIds(goodsIdList);
            list.forEach(shopFlashSaleActivityVO -> {
                ShopGoods shopGood = shopGoods.stream().filter(goods -> shopFlashSaleActivityVO.getGoodsId().equals(goods.getGoodsId())).findFirst().orElse(null);
                if(shopGood != null){
                    shopFlashSaleActivityVO.setGoodsPrice(shopGood.getPrice());
                    shopFlashSaleActivityVO.setGoodsTotalPrice(shopGood.getPrice().multiply(new BigDecimal(shopFlashSaleActivityVO.getNum())));
                    shopFlashSaleActivityVO.setGoodsName(shopGood.getName());
                    shopFlashSaleActivityVO.setImage(shopGood.getImage());
                    shopFlashSaleActivityVO.setUnitName(shopGood.getUnitName());
                }
            });
        }
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ShopFlashSaleActivity> listRel(ShopFlashSaleActivityParam param) {
        List<ShopFlashSaleActivity> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ShopFlashSaleActivity, ShopFlashSaleActivityParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ShopFlashSaleActivity getByIdRel(Integer id) {
        ShopFlashSaleActivityParam param = new ShopFlashSaleActivityParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public List<ShopFlashSaleActivityVO> getMyActive(Integer tenantId) {
        List<ShopFlashSaleActivityVO> resultVOList = new ArrayList<>();
        User loginUser = LoginUserUtil.getLoginUser();
        if(loginUser == null){
            throw new BusinessException(GlobalErrorCodeConstants.UNAUTHORIZED.getMsg());
        }


        Boolean newUser = true;
        //判断是否为新用户【只要未成功下单都判定为新用户】
        LambdaQueryWrapper<ShopOrder> shopOrderLambdaQueryWrapper = new LambdaQueryWrapper<ShopOrder>().eq(ShopOrder::getUserId, loginUser.getUserId()).eq(ShopOrder::getPayStatus, 1)
                .in(ShopOrder::getOrderStatus, Arrays.asList(0, 1));
        List<ShopOrder> shopOrderList = shopOrderMapper.selectList(shopOrderLambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(shopOrderList)){
            newUser = false;
        }

        //查询满足条件的活动数据
        LambdaQueryChainWrapper<ShopFlashSaleActivity> activityWrapper = lambdaQuery().eq(ShopFlashSaleActivity::getStatus, 0).gt(ShopFlashSaleActivity::getStock, 0).eq(ShopFlashSaleActivity::getTenantId, tenantId)
                .apply("NOW() BETWEEN start_time AND end_time");

        Map<Integer, Integer> activityMap = new HashMap<>();
        if(!newUser){
            //查询当前用户是否有下过秒杀活动订单数据【判断下单数量是否超过限制】
            List<Integer> activityIdList = activityWrapper.list().stream().map(ShopFlashSaleActivity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<ShopOrder> shopOrderWrapper = new LambdaQueryWrapper<ShopOrder>().select(ShopOrder::getOrderId, ShopOrder::getActivityId, ShopOrder::getTotalNum)
                    .eq(ShopOrder::getUserId, loginUser.getUserId()).in(ShopOrder::getActivityId, activityIdList).in(ShopOrder::getOrderStatus, Arrays.asList(0, 1));
            activityMap = shopOrderMapper.selectList(shopOrderWrapper).stream().collect(Collectors.groupingBy(ShopOrder::getActivityId, Collectors.summingInt(ShopOrder::getTotalNum)));

            activityWrapper.eq(ShopFlashSaleActivity::getDisplayType, 0);
        }
        activityWrapper.orderByAsc(ShopFlashSaleActivity::getSortNumber);
        List<ShopFlashSaleActivity> activityList = activityWrapper.list();

        if(CollectionUtils.isNotEmpty(activityList)){
            resultVOList = BeanUtil.copyToList(activityList, ShopFlashSaleActivityVO.class);
            List<Integer> goodsIdList = resultVOList.stream().map(ShopFlashSaleActivityVO::getGoodsId).distinct().collect(Collectors.toList());
            List<ShopGoods> shopGoods = shopGoodsMapper.selectBatchIds(goodsIdList);
            resultVOList.forEach(activity -> {
                ShopGoods shopGood = shopGoods.stream().filter(goods -> activity.getGoodsId().equals(goods.getGoodsId())).findFirst().orElse(null);
                if(shopGood != null){
                    activity.setGoodsPrice(shopGood.getPrice());
                    activity.setGoodsTotalPrice(shopGood.getPrice().multiply(new BigDecimal(activity.getNum())));
                    activity.setGoodsName(shopGood.getName());
                    activity.setImage(shopGood.getImage());
                    activity.setUnitName(shopGood.getUnitName());
                }
            });
        }

        //过滤超下单数量活动
        if(!activityMap.isEmpty()){
            Iterator<ShopFlashSaleActivityVO> iterator = resultVOList.iterator();
            while (iterator.hasNext()){
                ShopFlashSaleActivityVO vo = iterator.next();
                Integer orderTotalNum = activityMap.get(vo.getId());
                if(orderTotalNum != null && orderTotalNum >= vo.getSaleLimit()){
                    iterator.remove();
                }
            }
        }

        return resultVOList;
    }

    @Override
    public Boolean updateStatus(Integer id) {
        ShopFlashSaleActivity saleActivity = baseMapper.selectById(id);
        if(saleActivity != null){
            if (saleActivity.getStatus() == 0){
                saleActivity.setStatus(1);
            }else {
                saleActivity.setStatus(0);
            }
            User loginUser = LoginUserUtil.getLoginUser();
            if(loginUser != null){
                saleActivity.setUpdater(loginUser.getUserId().toString());
            }
            saleActivity.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(saleActivity);
            return Boolean.TRUE;
        }else {
            throw new BusinessException(GlobalErrorCodeConstants.NOT_FOUND.getMsg());
        }
    }

    @Override
    public Boolean updateSortNumber(Integer id, Integer sortNumber) {
        ShopFlashSaleActivity saleActivity = baseMapper.selectById(id);
        if(saleActivity != null){
            saleActivity.setSortNumber(sortNumber);
            saleActivity.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(saleActivity);
            return Boolean.TRUE;
        }else {
            throw new BusinessException(GlobalErrorCodeConstants.NOT_FOUND.getMsg());
        }
    }

}
