package com.izouma.jiashanxia.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.izouma.jiashanxia.domain.SetGoods;
import com.izouma.jiashanxia.domain.UserSet;
import com.izouma.jiashanxia.domain.UserSetFlow;
import com.izouma.jiashanxia.dto.GoodsDTO;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.FlowType;
import com.izouma.jiashanxia.repo.UserSetFlowRepo;
import com.izouma.jiashanxia.repo.UserSetRepo;
import com.izouma.jiashanxia.utils.JpaUtils;
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 UserSetService {

    private UserSetRepo     userSetRepo;
    private UserSetFlowRepo userSetFlowRepo;

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

    /*
    加入套餐
    */
    public void joinUserSet(Long userId, List<SetGoods> setGoodsList) {
        // 用户已有套餐
        Map<Long, UserSet> userSetMap = userSetRepo.findAllByUserId(userId)
                .stream()
                .collect(Collectors.toMap(UserSet::getGoodsInfoId, userSet -> userSet));

        // 加入用户套餐
        setGoodsList.forEach(setGoods -> {
            UserSet goods = userSetMap.get(setGoods.getGoodsInfoId());
            if (ObjectUtil.isNotEmpty(goods)) {
                goods.setNum(goods.getNum() + setGoods.getNum());
                goods.setRemark(setGoods.getRemark());
            } else {
                goods = UserSet.builder()
                        .userId(userId)
                        .goodsInfoId(setGoods.getGoodsInfoId())
                        .num(setGoods.getNum())
                        .remark(setGoods.getRemark())
                        .build();
            }
            userSetRepo.save(goods);
        });

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