package com.bawei.mall.car.service.impl;

import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.car.domain.*;
import com.bawei.mall.car.mapper.CarMapper;
import com.bawei.mall.car.mapper.OrderMapper;
import com.bawei.mall.car.service.OrderService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @program: mall_cloud
 * @ClassName: OrderServiceImpl
 * @author: Gyc
 * @create: 2024-05-10 19:34
 **/
@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMolder;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Object addOrder(List<Integer> skuIds) {
        String token = SecurityUtils.getToken();
        String userId = JwtUtils.getUserId(token);
        String carId = carMapper.queryCar(Long.valueOf(userId));
        if (carId == null){
            throw new RuntimeException("购物车为空");
        }
        String orderId = generateOrderId();
        ArrayList<CarBySku> carBySkus = new ArrayList<>();
        List<ProductSkuInfo> productSkuInfoList = carMapper.querySkus(skuIds, carId);
        List<Order> orderList = productSkuInfoList.stream()
                .map(productSkuInfo -> {
                    Order order = new Order();
                    Order build = order.builder()
                            .skuId(Math.toIntExact(productSkuInfo.getSkuId()))
                            .productUrl(productSkuInfo.getImage())
                            .productPrice(productSkuInfo.getSkuPrice())
                            .productName(productSkuInfo.getTitle())
                            .productSku(productSkuInfo.getSkuName())
                            .orderId(orderId)
                            .productNum(productSkuInfo.getNumber())
                            .buyNumber(productSkuInfo.getBuyNumber())
                            .build();
                    return build;
                })
                .collect(Collectors.toList());
            orderMolder.insertOrder(orderList);
       //查询需要购买的数量
        skuIds.forEach(skuId -> {
            CarBySku carBySku = carMapper.showCarBySkuId(skuId, carId);
            carBySkus.add(carBySku);
        });
        for (int i = 0; i < carBySkus.size() - 1; i++) {
            //比较商品数量
            if (carBySkus.get(i).getNumber()>orderList.get(i).getBuyNumber()){
                throw new RuntimeException("商品数量不足");
            }
        }
//        orderMapper.insertOrderByUser(orderId,userId);

        OrderByUser orderByUser = new OrderByUser();
        OrderByUser build = orderByUser.builder()
                .orderId(orderId)
                .userId(Integer.valueOf(userId))
                .status(0)
                .createTime(new Date())
                //TODO 没有优惠卷
                .discountId(0)
                .build();
        getVIP(orderList,build);
        OrderByUserInfo orderByUserInfo = new OrderByUserInfo();
        orderByUserInfo.setOrderList(orderList);
        orderByUserInfo.setOrderByUser(build);
        orderMapper.insertOrderByUser(build);
        return orderByUserInfo;
    }

    /**
     * 计算价格
     *
     * @param orderList
     * @param orderByUser
     */
    private void getVIP(List<Order> orderList, OrderByUser orderByUser) {
        orderByUser.setTotalPrice(new BigDecimal(0));
        orderByUser.setDiscountPrice(new BigDecimal(0));
        orderByUser.setPayPrice(new BigDecimal(0));
        BigDecimal bigDecimal = new BigDecimal(0);
        for (Order order : orderList) {
            BigDecimal skuPrice = order.getProductPrice();
            BigDecimal number = BigDecimal.valueOf(order.getProductNum());
            // 使用bigDecimal的add()方法，并将结果保存回bigDecimal
            bigDecimal = bigDecimal.add(skuPrice.multiply(number));
            orderByUser.setTotalPrice(bigDecimal);

        }
        if (orderByUser.getDiscountId()!=0){
            //TODO 进行优惠
        }
        //TODO 假设有个VIP
        String token = SecurityUtils.getToken();
        Claims claims = JwtUtils.parseToken(token);
        log.info("claims:{}",claims);
        String VIP="admin";
        if (VIP.equals(JwtUtils.getUserName(claims))){
            // 计算VIP折扣后的价格
            BigDecimal vipDiscountRate = new BigDecimal("0.99");
            BigDecimal afterDiscounts =orderByUser.getTotalPrice().multiply(vipDiscountRate);
            orderByUser.setPayPrice(afterDiscounts);

            // 计算VIP优惠与原价的差距
            BigDecimal specialOffer = orderByUser.getTotalPrice().subtract(afterDiscounts);
            orderByUser.setDiscountPrice(specialOffer);
        }

    }

    /**
     * 生成基于时间戳和十个随机数字的订单ID。
     *
     * @return 订单ID字符串
     */
    public static String generateOrderId() {
        // 获取当前时间的毫秒时间戳
        long timestamp = Instant.now().toEpochMilli();

        // 创建一个随机数生成器
        Random random = new Random();

        // 生成十个0-9之间的随机数字，拼接成一个字符串
        StringBuilder randomNumbers = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            randomNumbers.append(random.nextInt(10));
        }

        // 将时间戳和随机数字拼接成订单ID，这里以某种格式组合，例如：时间戳_随机数
        // 注意根据实际需要调整格式，确保唯一性和长度控制
        String orderId = timestamp + randomNumbers.toString();

        return orderId;
    }
}










































