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

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


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.Order;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupActivityDto;
import com.yami.shop.groupbuy.comment.dao.GroupOrderMapper;
import com.yami.shop.groupbuy.comment.dao.GroupTeamMapper;
import com.yami.shop.groupbuy.comment.enums.GroupOrderStatusEnum;
import com.yami.shop.groupbuy.comment.enums.TeamStatusEnum;
import com.yami.shop.groupbuy.comment.model.GroupOrder;
import com.yami.shop.groupbuy.comment.model.GroupProd;
import com.yami.shop.groupbuy.comment.model.GroupTeam;
import com.yami.shop.groupbuy.comment.service.GroupActivityService;
import com.yami.shop.groupbuy.comment.service.GroupPayService;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * 拼团支付
 */
@Service
@AllArgsConstructor
@Slf4j
public class GroupPayServiceImpl implements GroupPayService {

    private final OrderMapper orderMapper;
    private final GroupTeamMapper groupTeamMapper;
    private final GroupOrderMapper groupOrderMapper;
    private final GroupActivityService groupActivityService;
    private final GroupProdService groupProdService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccessNoticeHandle(Order order) {
        log.info("处理拼团订单 订单编号：{}", order.getOrderNumber());
        orderMapper.updateToWaitGroup(order.getOrderNumber());

        // 获取用户拼团订单信息
        GroupOrder groupOrder = groupOrderMapper.selectOne(new LambdaQueryWrapper<GroupOrder>()
                .eq(GroupOrder::getOrderNumber, order.getOrderNumber()));
        // 获取拼团团队订单
        GroupTeam groupTeam = groupTeamMapper.selectById(groupOrder.getGroupTeamId());

        GroupProd groupProd = groupProdService.getGroupProdById(groupTeam.getGroupProdId());
        ApiGroupActivityDto apiGroupActivityInfo = groupActivityService.getApiGroupActivityInfo(groupTeam.getGroupActivityId(), groupProd.getProdId());

        Date now = new Date();
        // 如果为团长则直接开团，否则判断是否拼团已满
        if (Objects.equals(groupOrder.getIdentityType(), 1)) {
            groupTeam.setJoinNum(1);
            groupTeam.setUpdateTime(now);
            groupTeam.setStatus(TeamStatusEnum.IN_GROUP.value());
            groupTeam.setTotalPrice(groupOrder.getPayPrice());
            groupTeam.setStartTime(now);
            groupTeam.setEndTime(DateUtil.offsetMinute(now, apiGroupActivityInfo.getGroupValidTime()));
            groupTeamMapper.updateById(groupTeam);

            groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
            groupOrderMapper.updateById(groupOrder);
        } else {
            // 参团
            // 判断团是否已满，如果已满则重新开团，如果不是则继续参团
            if (Objects.equals(groupTeam.getStatus(), TeamStatusEnum.SUCCESS.value())) {
                // 满员开团
                GroupTeam newGroupTeam = new GroupTeam();
                newGroupTeam.setJoinNum(1);
                newGroupTeam.setCreateTime(now);
                newGroupTeam.setUpdateTime(now);
                newGroupTeam.setStartTime(now);
                newGroupTeam.setShopId(groupTeam.getShopId());
                groupTeam.setTotalPrice(groupOrder.getPayPrice());
                newGroupTeam.setShareUserId(groupOrder.getUserId());
                newGroupTeam.setStatus(TeamStatusEnum.IN_GROUP.value());
                newGroupTeam.setGroupProdId(groupTeam.getGroupProdId());
                newGroupTeam.setGroupActivityId(groupTeam.getGroupActivityId());
                newGroupTeam.setEndTime(DateUtil.offsetMinute(now, apiGroupActivityInfo.getGroupValidTime()));
                groupTeamMapper.insert(newGroupTeam);

                groupOrder.setIdentityType(1);
                groupOrder.setGroupTeamId(newGroupTeam.getGroupTeamId());
                groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
                groupOrderMapper.updateById(groupOrder);
            } else if (Objects.equals(groupTeam.getStatus(), TeamStatusEnum.IN_GROUP.value())) {
                // 参团
                groupTeam.setUpdateTime(now);
                groupTeam.setJoinNum(groupTeam.getJoinNum() + 1);
                groupTeam.setTotalPrice(Arith.add(groupTeam.getTotalPrice(), groupOrder.getPayPrice()));
                // 是否已达人数,则修改团信息及订单信息
                if (groupTeam.getJoinNum() >= apiGroupActivityInfo.getGroupNumber()) {
                    // 更新拼团成功
                    groupTeam.setStatus(TeamStatusEnum.SUCCESS.value());
                    // 更新将所有的订单订单待发货
                    if (orderMapper.updateToWaitDelivery(groupTeam.getGroupTeamId()) <= 0) {
                        throw new GlobalException("更新拼团订单为待发货失败，请稍后重试");
                    }
                }
                groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
                groupTeamMapper.updateById(groupTeam);
                groupOrderMapper.updateById(groupOrder);
                // 如果满团更新统计信息
                if (groupTeam.getJoinNum() >= apiGroupActivityInfo.getGroupNumber()) {
                    // 更新已成团订单数
                    groupProd.setGroupOrderCount(groupProd.getGroupOrderCount() + groupTeam.getJoinNum());
                    // 更新已成团人数
                    Long count = groupOrderMapper.getHadGroupNumberCount(groupProd.getGroupActivityId(), groupProd.getGroupProdId());
                    groupProd.setGroupNumberCount(count);
                    groupProdService.updateById(groupProd);
                }
            }
        }
    }
}
