package com.github.wxiaoqi.security.admin.handler;


import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.biz.AppUserSellingWaterBiz;
import com.github.wxiaoqi.security.admin.dto.OrderGoodsDTO;
import com.github.wxiaoqi.security.admin.dto.OrderWaterDTO;
import com.rabbitmq.client.Channel;
import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.OrderItem;
import com.xxfc.platform.order.pojo.mq.OrderMQDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.github.wxiaoqi.security.admin.config.RabbitAdminConfig.*;
import static com.xxfc.platform.order.pojo.mq.OrderMQDTO.*;

@Component
@Slf4j
public class WaterMQHandler {

    @Autowired
    AppUserSellingWaterBiz waterBiz;

    /**
     * 佣金
     * @param
     */
    @RabbitListener(queues = ORDER_WATER_QUEUE)
    public void integralHandler(Message message, @Headers Map<String, Object> headers, Channel channel) {
        log.info("拥金队列 messageJson："+ JSONUtil.parse(message));
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String messageId = message.getMessageProperties().getMessageId();
                    String msg = new String(message.getBody(), "UTF-8");
                    OrderMQDTO orderMQDTO = JSONUtil.toBean(msg, OrderMQDTO.class);
                    OrderWaterDTO orderWaterDTO = new OrderWaterDTO() {{
                        setUserId(orderMQDTO.getUserId());
                        setOrderNo(orderMQDTO.getNo());
                        setOrderId(orderMQDTO.getId());
                    }};
                    switch (orderMQDTO.getSign()) {
                        case ORDER_PAY:
                            orderWaterDTO.setStatus(1);
                            break;
                        case ORDER_FINISH:
                            orderWaterDTO.setStatus(2);
                            break;
                        case ORDER_PART_DEPOSIT:
                            orderWaterDTO.setStatus(2);
                            break;
                        case ORDER_CANCEL:
                            orderWaterDTO.setStatus(3);
                            break;
                        default:
                            break;
                    }
                    switch (OrderTypeEnum.get(orderMQDTO.getType())) {
                        case RENT_VEHICLE:
                            //租车订单finlish不处理，退还第一部分押金后再处理
                            if(orderMQDTO.getSign().equals(ORDER_FINISH)) {
                                //直接结束
                                return;
                            }
                            orderMQDTO.getItemByTypeEnum(ItemTypeEnum.VEHICLE_MODEL);
                            orderWaterDTO.setGoodsDTOList(
                                    new ArrayList<OrderGoodsDTO>() {{
                                        add(new OrderGoodsDTO() {{
                                            setGoodId(orderMQDTO.getOrderRentVehicleDetail().getModelId());
                                            setGoodNumber(1);
                                            setImg(orderMQDTO.getPicture());
                                            setPrice(orderMQDTO.getItemByTypeEnum(ItemTypeEnum.VEHICLE_MODEL).getLastAmount());
                                            setTitle(orderMQDTO.getName());
                                            setType(OrderGoodsDTO.TYPE_RENT);
                                        }});
                                    }}
                            );
                            break;
                        case TOUR:
                            OrderItem tourAdultItem = orderMQDTO.getItemByTypeEnum(ItemTypeEnum.TOUR_ADULT);
                            OrderItem tourChildItem = orderMQDTO.getItemByTypeEnum(ItemTypeEnum.TOUR_CHILD);
                            orderWaterDTO.setGoodsDTOList(
                                    new ArrayList<OrderGoodsDTO>() {{
                                        add(new OrderGoodsDTO() {{
                                            setGoodId(orderMQDTO.getOrderTourDetail().getGoodId());
                                            setGoodNumber(1);
                                            setImg(orderMQDTO.getPicture());
                                            setPrice(tourAdultItem.getRealAmount().add(null == tourChildItem?
                                                    BigDecimal.ZERO:tourChildItem.getRealAmount()));
                                            setTitle(orderMQDTO.getName());
                                            setType(OrderGoodsDTO.TYPE_TOUR);
                                        }});
                                    }}
                            );
                            break;
                        case MEMBER:
                            orderWaterDTO.setGoodsDTOList(
                                    new ArrayList<OrderGoodsDTO>() {{
                                        add(new OrderGoodsDTO() {{
                                            setGoodId(orderMQDTO.getOrderMemberDetail().getMemberLevelId());
                                            setGoodNumber(1);
                                            setImg(orderMQDTO.getPicture());
                                            setPrice(orderMQDTO.getItemByTypeEnum(ItemTypeEnum.MEMBER).getRealAmount());
                                            setTitle(orderMQDTO.getName());
                                            setType(OrderGoodsDTO.TYPE_MEMBER);
                                        }});
                                    }}
                            );
                            break;
                        default:
                            break;
                    }

                    waterBiz.orderWater(orderWaterDTO);

                    executorService.shutdown();
                    Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
                    // 手动签收
                    channel.basicAck(deliveryTag, false);
                } catch (Exception e) {
                    log.info("接收到的消息失败");
                    try {
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                    } catch (IOException i) {
                        log.error(e.getMessage(), i);
                    }
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}
