package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.OrderDetail;
import com.ruoyi.system.domain.ShopGoodsSku;
import com.ruoyi.system.domain.vo.OrderQuery;
import com.ruoyi.system.mapper.ShopGoodsSkuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OrderMapper;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.IOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-04-28
 */
@Service
public class OrderServiceImpl implements IOrderService 
{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShopGoodsSkuMapper shopGoodsSkuMapper;



    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(String id)
    {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(OrderQuery order)
    {
        return null;
    }

    /**
     * 新增订单
     * 
     *
     * @param loginUser
     * @param order 订单
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertOrder(LoginUser loginUser, Order order)
    {
        AjaxResult result = check(order);
        if(HttpStatus.SUCCESS != (int)result.get(result.CODE_TAG)){
            return result;
        }
        order.setState("1");
        order.setCreatedAt(new Date());
        order.setOrderNum(getOrderNum(order.getShopId()));
        order.setOrderNo(getOrderNo(order.getSource()));
        int  i = orderMapper.insertOrder(order);
        List<OrderDetail> orderDetails = order.getOrderDetails();
        if(orderDetails !=null && !orderDetails.isEmpty()){
            for (OrderDetail orderDetail : orderDetails) {
                orderDetail.setOrderId(order.getId());
                orderDetail.setCreatedAt(new Date());
                orderDetail.setUpdatedAt(new Date());
            }
        }
        return AjaxResult.success();
        //调用微信支付
    }

    /**
     * 修改订单
     * 
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(String[] ids)
    {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(String id)
    {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public AjaxResult check(Order order) {
        //验证订单状态
        List<OrderDetail> orderDetails = order.getOrderDetails();
        if(orderDetails==null ||orderDetails.isEmpty()){
            return AjaxResult.error("订单信息不能为空");
        }

        for (OrderDetail orderDetail : orderDetails) {
            ShopGoodsSku shopGoodsSku = new ShopGoodsSku();
            shopGoodsSku.setSkuId(Long.parseLong(orderDetail.getSkuId()));
            shopGoodsSku.setMachineId(orderDetail.getMachineId());
            shopGoodsSku.setIsDeleted("0");
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuMapper.selectShopGoodsSkuList(shopGoodsSku);
            if(shopGoodsSkus ==null ||shopGoodsSkus.isEmpty()){
                return AjaxResult.error("该商品已不存在："+orderDetail.getGoodsName());
            }
            ShopGoodsSku shopGoodsSku1 = shopGoodsSkus.get(0);
            if(!"1".equals(shopGoodsSku1)){
                return AjaxResult.error("该商品所选种类已经告罄，请重新进行选择："+orderDetail.getGoodsName());
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取机器顺序号
     * @param shopId
     * @return
     */
    private String getOrderNum(String shopId){
        Calendar calendar = Calendar.getInstance();
        String key = calendar.getTime().toString().substring(0,3);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String redisKey = "shopId"+format+shopId;
        RedisAtomicInteger redisAtomicInteger = new RedisAtomicInteger(redisKey,SpringUtils.getBean(StringRedisTemplate.class).getConnectionFactory());
        redisAtomicInteger.set(40);
        redisAtomicInteger.expire(1, TimeUnit.DAYS);
        int andIncrement = redisAtomicInteger.getAndIncrement();
        return key+andIncrement;
    }
    //获取订单号
    private String getOrderNo(String source){
        String channel = "M";
        if(StringUtils.isNotEmpty(source)){
            if("1".equals(source)){
                channel="A";
            }else{
                channel="B";
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HH");
        String format = simpleDateFormat.format(new Date());
        String key = "orderNo";
        RedisAtomicInteger redisAtomicInteger = new RedisAtomicInteger(key,SpringUtils.getBean(StringRedisTemplate.class).getConnectionFactory());
        int andIncrement = redisAtomicInteger.getAndIncrement();
        if(andIncrement>9999){
            redisAtomicInteger.set(0);
            andIncrement = 0;
        }
        String format1 = String.format("%04d", andIncrement);
        int randomNumber = new Random().nextInt(99);
        return "N"+format+channel+format1+randomNumber;
    }
}
