package com.ruoyi.system.service.impl;

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

import com.alibaba.fastjson.JSONObject;
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.Machine;
import com.ruoyi.system.domain.OrderDetail;
import com.ruoyi.system.domain.ShopGoodsSku;
import com.ruoyi.system.service.IOrderService;
import com.ruoyi.system.domain.vo.OrderQuery;
import com.ruoyi.system.mapper.*;
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.domain.Order;
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;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MachineMapper machineMapper;
    @Autowired
    private RobotServiceImpl robotService;
    @Autowired
    private ShopMapper shopMapper;



    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(String id)
    {
        Order order = orderMapper.selectOrderById(id);
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailList(orderDetail);
        for (OrderDetail detail : orderDetails) {
            detail.setGoods(goodsMapper.selectGoodsById(detail.getGoodsId()));
        }
        return order;
    }

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

    /**
     * 新增订单
     * 
     *
     * @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.setUserId(loginUser.getOpenId());
        order.setUserName(loginUser.getUsername());
        order.setCreatedAt(new Date());
        order.setOrderNum(getOrderNum(order.getShopId()));
        order.setOrderNo(getOrderNo(order.getSource()));
        String machineId = null;
        if(StringUtils.isEmpty(order.getMachineId())){
            Machine machine =new Machine();
            machine.setShopId(Long.parseLong(order.getShopId()));
            List<Machine> machines = machineMapper.selectMachineList(machine);
            if(machines!=null &&!machines.isEmpty()){
                Machine machine1 = machines.get(0);
                if(!"1".equals(machine1.getState())){
                    return AjaxResult.error("机器暂时不可用");
                }
                machineId = machine1.getCode();
                order.setMachineId(machine1.getCode());
            }else{
                return AjaxResult.error("该店铺暂无绑定机器");
            }
        }
        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.setMachineId(machineId);
                orderDetail.setUpdatedAt(new Date());
            }
        }
        //发送数据给机器
        //robotService.createOrder(order);
        return AjaxResult.success(order.getOrderNo());

    }

    /**
     * 修改订单
     * 
     * @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.getState())){
                return AjaxResult.error("该商品所选种类已经告罄，请重新进行选择："+orderDetail.getGoodsName());
            }
        }
        return AjaxResult.success();
    }

    @Override
    public List<Order> getMyOrder(String openId) {
        List<Order> orders = orderMapper.selectByUserId(openId);
        for (Order order : orders) {
            order.setShop(shopMapper.selectShopById(order.getShopId()));
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailList(orderDetail);
            for (OrderDetail detail : orderDetails) {
                detail.setGoods(goodsMapper.selectGoodsById(detail.getGoodsId()));
            }
        }
        return orders;
    }

    /**
     * 获取机器顺序号
     * @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());
        if(0 == redisAtomicInteger.getAndIncrement()){
            redisAtomicInteger.set(30);
        }
        redisAtomicInteger.expire(1, TimeUnit.DAYS);
        int andIncrement = redisAtomicInteger.getAndIncrement();
        return key+String.format("%03d",andIncrement);
    }
    //获取订单号
    private String getOrderNo(String source){
        String channel = "M";
        if(StringUtils.isNotEmpty(source)){
            if("1".equals(source)){
                channel="A";
            }else if("2".equals(source)){
                channel="B";
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHH");
        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;
    }

    public  List<JSONObject>  getOrderInfo(String machineCode) {
        List<String> status = Arrays.asList("3","4","5");
        List<Order> orders = orderMapper.selectOrder(status, machineCode);
        Map<String, List<Order>> collect = orders.stream().collect(Collectors.groupingBy(Order::getState));
        List<JSONObject> objects = new ArrayList<>();
        for(String key:collect.keySet()){
            JSONObject jsonObject =new JSONObject();
            objects.add(jsonObject);
            jsonObject.put("state",key);
            List<Order> orders1 = collect.get(key);
            List<JSONObject> jsonObjects = new ArrayList<>();
            jsonObject.put("orders",jsonObjects);
            for (Order order : orders1) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObjects.add(jsonObject1);
                jsonObject1.put("orderId",order.getId());
                jsonObject1.put("orderNum",order.getOrderNum());
                jsonObject1.put("orderNo",order.getOrderNo());
            }
        }
        return objects;

    }


    public String refundOrder(String orderId) {
        Order order = orderMapper.selectOrderById(orderId);
        List<String> status = Arrays.asList("2","3");
        if(status.contains(order.getState())){
            //todo 创建退款单，进行退款
        }else{
            //todo 创建退款单

        }
        return null;
    }
}
