/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.groupbuy.comment.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.SpringContextUtils;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupProdDto;
import com.yami.shop.groupbuy.comment.dao.GroupProdMapper;
import com.yami.shop.groupbuy.comment.dao.GroupSkuMapper;
import com.yami.shop.groupbuy.comment.dto.GroupProdAndSkuListDto;
import com.yami.shop.groupbuy.comment.dto.GroupProdDto;
import com.yami.shop.groupbuy.comment.enums.GroupProdStatusEnum;
import com.yami.shop.groupbuy.comment.model.GroupProd;
import com.yami.shop.groupbuy.comment.model.GroupSku;
import com.yami.shop.groupbuy.comment.model.GroupTeam;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import com.yami.shop.groupbuy.comment.service.GroupTeamService;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 拼团活动商品表
 *
 * @author LGH
 * @date 2019-08-27 17:55:57
 */
@Service
@AllArgsConstructor
public class GroupProdServiceImpl extends ServiceImpl<GroupProdMapper, GroupProd> implements GroupProdService {

    private final GroupProdMapper groupProdMapper;
    private final SkuService skuService;
    private final GroupSkuMapper groupSkuMapper;
    private final ProductService productService;
    private final OrderRefundService orderRefundService;

    @Override
    public IPage<GroupProdDto> getGroupProdPage(PageParam<GroupProd> page, GroupProd groupProd) {
        return groupProdMapper.getGroupProdPage(page, groupProd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> saveByProdIds(Long shopId, Long groupActivityId, List<Long> prodIds) {
        List<Long> needSaveProdIds = Lists.newArrayList();
        List<GroupProd> groupProdList = Lists.newArrayList();
        List<GroupSku> groupSkuList = Lists.newArrayList();
        // 原有的商品
        List<GroupProd> hadProds = groupProdMapper.selectList(new LambdaQueryWrapper<GroupProd>().eq(GroupProd::getGroupActivityId, groupActivityId));
        for (Long prodId : prodIds) {
            long count = hadProds.stream().filter(item -> Objects.equals(item.getProdId(), prodId)).count();
            if (count == 0) {
                needSaveProdIds.add(prodId);
            }
        }
        if (CollectionUtil.isNotEmpty(needSaveProdIds)) {
            for (Long prodId : needSaveProdIds) {
                GroupProd groupProd = new GroupProd();
                groupProd.setCreateTime(new Date());
                groupProd.setProdId(prodId);
                groupProd.setGroupActivityId(groupActivityId);
                groupProd.setGroupOrderCount(0L);
                groupProd.setGroupNumberCount(0L);
                groupProd.setStatus(1);
                groupProd.setShopId(shopId);
                groupProdList.add(groupProd);
            }
            // 保存活动商品
            groupProdMapper.saveBatchGroupProd(groupProdList);
        }
        for (GroupProd groupProd : groupProdList) {
            List<Sku> skuList = skuService.listByProdId(groupProd.getProdId());
            // 获取状态正常的skuId
            List<Sku> needSaveSku = skuList.stream().filter(item -> item.getStatus() == 1).collect(Collectors.toList());
            for (Sku sku : needSaveSku) {
                // 获取所有的sku
                GroupSku groupSku = new GroupSku();
                groupSku.setActPrice(sku.getPrice());
                groupSku.setLeaderPrice(sku.getPrice());
                groupSku.setSkuId(sku.getSkuId());
                groupSku.setGroupProdId(groupProd.getGroupProdId());
                groupSku.setSellNum(0L);
                groupSkuList.add(groupSku);
            }
        }
        // 保存所有的sku
        groupSkuMapper.saveBatchGroupSku(groupSkuList);
        // 更新商品为活动商品
        productService.updateProductToGroup(groupActivityId, prodIds);
        return prodIds;

    }

    @Override
    public GroupProdAndSkuListDto getGroupProdAndSkuListById(Long groupProdId) {
        return groupProdMapper.getGroupProdAndSkuListById(groupProdId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupProdToDelByGroupProd(GroupProd groupProd) {
        // 更新活动商品为已删除状态
        groupProdMapper.updateStatusToDelById(groupProd.getGroupProdId());
        // 更新商品为非拼团商品
        productService.updateProductToUnGroup(groupProd.getProdId());
    }

    /**
     * API-活动商品列表
     *
     * @param page 分页对象
     * @return 分页数据
     */
    @Override
    public IPage<ApiGroupProdDto> getApiGroupProdPage(PageParam<OrderRefundDto> page) {
        return groupProdMapper.getApiGroupProdPage(page, new Date());
    }

    @Override
    public GroupProd getGroupProdByGroupSkuId(Long groupSkuId) {
        return groupProdMapper.getGroupProdByGroupSkuId(groupSkuId);
    }

    /**
     * 获取活动商品信息
     *
     * @param groupProdId 活动商品ID
     * @return ApiGroupProdDto对象
     */
    @Override
    public ApiGroupProdDto getApiGroupProdDto(Long groupProdId) {
        return groupProdMapper.getApiGroupProdDto(groupProdId);
    }

    @Override
    @Cacheable(cacheNames = "groupProd", key = "#groupProdId")
    public GroupProd getGroupProdById(Long groupProdId) {
        return groupProdMapper.selectById(groupProdId);
    }

    @Override
    @CacheEvict(cacheNames = "groupProd", key = "#groupProdId")
    public void removeGroupProdCache(Long groupProdId) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delGroupProd(GroupProd groupProd) {
        groupProdMapper.deleteById(groupProd.getGroupProdId());
        groupSkuMapper.delete(new LambdaQueryWrapper<GroupSku>()
                .eq(GroupSku::getGroupProdId, groupProd.getGroupProdId()));

        // 更新商品为非拼团商品
        productService.updateProductToUnGroup(groupProd.getProdId());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void invalidGroupProd(GroupProd groupProd) {
        GroupTeamService groupTeamService = SpringContextUtils.getBean(GroupTeamService.class);
        groupProd.setStatus(GroupProdStatusEnum.EXPIRED.value());
        groupProdMapper.updateById(groupProd);

        // 更新商品为非拼团商品
        productService.updateProductToUnGroup(groupProd.getProdId());

        // 获取未成团的团队
        List<GroupTeam> groupTeamList = groupTeamService.getNotGroupTeamsByActivityIdAndGroupProdId(groupProd.getGroupActivityId(), groupProd.getGroupProdId());
        // 处理未成团的拼团团队
        for (GroupTeam groupTeam : groupTeamList) {
            groupTeamService.updateNotGroupTeam(groupTeam);
        }
    }

    @Override
    public void invalidGroupProdByActivityId(List<Long> groupActivityIds) {
        groupProdMapper.invalidGroupProdByActivityId(groupActivityIds);
    }

}
