package com.izouma.jiashanxia.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.izouma.jiashanxia.domain.PackageGoods;
import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.domain.UserPackage;
import com.izouma.jiashanxia.domain.UserPackageFlow;
import com.izouma.jiashanxia.dto.GoodsDTO;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.FlowType;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.UserRepo;
import com.izouma.jiashanxia.repo.UserPackageFlowRepo;
import com.izouma.jiashanxia.repo.UserPackageRepo;
import com.izouma.jiashanxia.utils.JpaUtils;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class UserPackageService {

    private UserPackageRepo     userPackageRepo;
    private UserPackageFlowRepo userPackageFlowRepo;

    public Page<UserPackage> all(PageQuery pageQuery) {
        return userPackageRepo.findAll(JpaUtils.toSpecification(pageQuery, UserPackage.class), JpaUtils.toPageRequest(pageQuery));
    }

    /*
    加入套餐

    用户套餐和企业套餐重叠怎么办？
    */
    public void joinUserPackage(Long userId, List<PackageGoods> packageGoodsList, Integer num) {
        // 用户已有套餐
        Map<Long, UserPackage> userPackageMap = userPackageRepo.findAllByUserId(userId)
                .stream()
                .collect(Collectors.toMap(UserPackage::getGoodsInfoId, userSet -> userSet));

        // 加入用户套餐
        packageGoodsList.forEach(setGoods -> {
            UserPackage goods = userPackageMap.get(setGoods.getGoodsInfoId());
            if (ObjectUtil.isNotEmpty(goods)) {
                goods.setNum(goods.getNum() + setGoods.getNum() * num);
                goods.setRemark(setGoods.getRemark());

            } else {
                goods = UserPackage.builder()
                        .userId(userId)
                        .goodsInfoId(setGoods.getGoodsInfoId())
                        .num(setGoods.getNum() * num)
                        .remark(setGoods.getRemark())
                        .build();
            }
            userPackageRepo.save(goods);
        });

        // 记录套餐流水
        List<GoodsDTO> goodsDTOS = JSONObject.parseArray(JSONObject.toJSONString(packageGoodsList), GoodsDTO.class);
        userPackageFlowRepo.save(UserPackageFlow.builder()
                .userId(userId)
                .type(FlowType.BUY)
                .content(JSONObject.toJSONString(goodsDTOS))
                .build());
    }
}
