package com.izouma.jiashanxia.service;

import cn.hutool.core.collection.CollUtil;
import com.izouma.jiashanxia.domain.*;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.OrderInfoStatus;
import com.izouma.jiashanxia.enums.PayMethod;
import com.izouma.jiashanxia.enums.TransactionType;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.*;
import com.izouma.jiashanxia.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
@AllArgsConstructor
public class OrderInfoService {

    private OrderInfoRepo        orderInfoRepo;
    private SetMealRepo          setMealRepo;
    private SetGoodsRepo         setGoodsRepo;
    private UserSetRepo          userSetRepo;
    private UserRepo             userRepo;
    private SysConfigService     sysConfigService;
    private CommissionRecordRepo commissionRecordRepo;
    private UserSetService       userSetService;

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

    /*
    下订单
     */
    public OrderInfo order(Long userId, Long setInfoId, PayMethod payMethod) {
        SetMeal setInfo = setMealRepo.findById(setInfoId).orElseThrow(new BusinessException("无套餐"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String localTime = df.format(LocalDateTime.now());
        String num = String.format("%05d", orderInfoRepo.orderNum() + 1);

        OrderInfo order = OrderInfo.builder()
                .setMealId(setInfoId)
                .status(OrderInfoStatus.UNPAID)
                .userId(userId)
                .payMethod(payMethod)
                .orderNumber(localTime + num)
                .price(setInfo.getAmount())
                .name(setInfo.getName())
                .build();
        return orderInfoRepo.save(order);
    }

    /*
    完成付款
     */
    public void completed(Long orderInfoId, String transactionId) {
        // 修改订单状态
        OrderInfo order = orderInfoRepo.findById(orderInfoId).orElseThrow(new BusinessException("无订单"));
        order.setStatus(OrderInfoStatus.PAID);
        order.setTransactionId(transactionId);
        order.setPaidAt(LocalDateTime.now());
        orderInfoRepo.save(order);

        // 套餐内商品
        List<SetGoods> setGoodsList = setGoodsRepo.findAllBySetMealId(order.getSetMealId());
        // 加入套餐商品
        Long userId = order.getUserId();
        userSetService.joinUserSet(userId, setGoodsList);

    }

    /*
    分销
     */
    public void distribution(Long userId, Long parent, String transactionId) {
        List<UserSet> parentSets = userSetRepo.findAllByUserId(parent);
        if (CollUtil.isEmpty(parentSets)) {
            return;
        }

        User user = userRepo.findById(parent).orElseThrow(new BusinessException("无用户"));
        BigDecimal personalAmount = sysConfigService.getBigDecimal("PERSONAL_AMOUNT");
        user.setAmount(user.getAmount().add(personalAmount));

        // 个人佣金流水
        commissionRecordRepo.save(CommissionRecord.builder()
                .userId(parent)
                .amount(personalAmount)
                .payMethod(PayMethod.YUE)
                .fromUserId(userId)
                .transactionType(TransactionType.INCOME)
                .transactionId(transactionId)
                .build());


    }
}
