package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.mapper.ShopDealerRefereeMapper;
import com.gxwebsoft.shop.entity.ShopDealerUser;
import com.gxwebsoft.shop.mapper.ShopOrderMapper;
import com.gxwebsoft.shop.service.ShopDealerUserService;
import com.gxwebsoft.shop.service.ShopDealerRefereeService;
import com.gxwebsoft.shop.entity.ShopDealerReferee;
import com.gxwebsoft.shop.param.ShopDealerRefereeParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分销商推荐关系表Service实现
 *
 * @author 科技小王子
 * @since 2025-08-11 23:51:41
 */
@Service
public class ShopDealerRefereeServiceImpl extends ServiceImpl<ShopDealerRefereeMapper, ShopDealerReferee> implements ShopDealerRefereeService {

    @Resource
    private ShopDealerUserService shopDealerUserService;

    @Resource
    private ShopOrderMapper shopOrderMapper;

    @Override
    public PageResult<ShopDealerReferee> pageRel(ShopDealerRefereeParam param) {
        PageParam<ShopDealerReferee, ShopDealerRefereeParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<ShopDealerReferee> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public PageResult<ShopDealerReferee> appPage(ShopDealerRefereeParam param) {
        PageParam<ShopDealerReferee, ShopDealerRefereeParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<ShopDealerReferee> list = baseMapper.selectPageRel(page, param);

        if(CollectionUtils.isNotEmpty(list)){
            List<Integer> userIdList = list.stream().map(ShopDealerReferee::getUserId).distinct().collect(Collectors.toList());

            Map<Integer, Long> refereeMap = lambdaQuery().select(ShopDealerReferee::getDealerId, ShopDealerReferee::getUserId).in(ShopDealerReferee::getDealerId, userIdList).list()
                    .stream().collect(Collectors.groupingBy(ShopDealerReferee::getDealerId, Collectors.counting()));

            LambdaQueryWrapper<ShopOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<ShopOrder>().select(ShopOrder::getOrderId, ShopOrder::getUserId, ShopOrder::getMoney).in(ShopOrder::getUserId, userIdList)
                    .in(ShopOrder::getOrderStatus, Arrays.asList(0, 1, 3, 4, 5, 7));
            List<ShopOrder> shopOrderList = shopOrderMapper.selectList(orderLambdaQueryWrapper);

            Map<Integer, Long> userOrderCountMap = new HashMap<>();
            Map<Integer, BigDecimal> userAmountMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(shopOrderList)){
                userOrderCountMap = shopOrderList.stream().collect(Collectors.groupingBy(ShopOrder::getUserId, Collectors.counting()));
                userAmountMap = shopOrderList.stream().collect(Collectors.groupingBy(ShopOrder::getUserId, Collectors.reducing(BigDecimal.ZERO, ShopOrder::getMoney, BigDecimal::add)));
            }

            Map<Integer, Long> finalUserOrderCountMap = userOrderCountMap;
            Map<Integer, BigDecimal> finalUserAmountMap = userAmountMap;
            list.forEach(shopDealerReferee -> {
                Long teamNum = refereeMap.get(shopDealerReferee.getUserId());
                if(teamNum != null){
                    shopDealerReferee.setTeamNum(teamNum.intValue());
                }else {
                    shopDealerReferee.setTeamNum(0);
                }

                Long orderNum = finalUserOrderCountMap.get(shopDealerReferee.getUserId());
                if(orderNum != null){
                    shopDealerReferee.setOrderNum(orderNum.intValue());
                }else {
                    shopDealerReferee.setOrderNum(0);
                }

                BigDecimal orderAmount = finalUserAmountMap.get(shopDealerReferee.getUserId());
                if(orderAmount != null){
                    shopDealerReferee.setOrderAmount(orderAmount);
                }else {
                    shopDealerReferee.setOrderAmount(BigDecimal.ZERO);
                }
            });
        }
        return new PageResult<>(list, page.getTotal());
    }

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

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

    @Override
    public ShopDealerReferee getByUserIdRel(Integer userId) {
      ShopDealerRefereeParam param = new ShopDealerRefereeParam();
      param.setUserId(userId);
      param.setLevel(1);
      return param.getOne(baseMapper.selectListRel(param));
  }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean bindFirstLevel(Integer dealerId, Integer userId, Integer tenantId, String source, String scene) {
        if (dealerId == null || dealerId <= 0) {
            throw new BusinessException("dealerId不能为空");
        }
        if (userId == null || userId <= 0) {
            throw new BusinessException("userId不能为空");
        }
        if (tenantId == null || tenantId <= 0) {
            throw new BusinessException("TenantId不能为空");
        }
        if (dealerId.equals(userId)) {
            throw new BusinessException("禁止绑定自己");
        }

        // 已绑定则直接返回(幂等，不改绑)
        ShopDealerReferee existed = getOne(new LambdaQueryWrapper<ShopDealerReferee>()
            .eq(ShopDealerReferee::getTenantId, tenantId)
            .eq(ShopDealerReferee::getUserId, userId)
            .eq(ShopDealerReferee::getLevel, 1)
            .last("limit 1"));
        if (existed != null) {
            return false;
        }

        // 校验邀请人(分销商)存在且有效
        ShopDealerUser dealerUser = shopDealerUserService.getOne(new LambdaQueryWrapper<ShopDealerUser>()
            .eq(ShopDealerUser::getTenantId, tenantId)
            .eq(ShopDealerUser::getUserId, dealerId)
            .eq(ShopDealerUser::getIsDelete, 0)
            .last("limit 1"));
        if (dealerUser == null) {
            throw new BusinessException("邀请人不存在或已失效");
        }

        LocalDateTime now = LocalDateTime.now();
        ShopDealerReferee entity = new ShopDealerReferee();
        entity.setDealerId(dealerId);
        entity.setUserId(userId);
        entity.setLevel(1);
        entity.setTenantId(tenantId);
        entity.setSource(source);
        entity.setScene(scene);
        entity.setCreateTime(now);
        entity.setUpdateTime(now);

        try {
            // 并发下依赖唯一索引保证幂等；重复写入视为已绑定
            return save(entity);
        } catch (DuplicateKeyException e) {
            return false;
        } catch (DataIntegrityViolationException e) {
            return false;
        }
    }

}
