package com.younike.web.core.config;

import com.rabbitmq.client.Channel;
import com.younike.common.exception.GlobalException;
import com.younike.system.domain.FamilyParam;
import com.younike.system.domain.Member;
import com.younike.system.domain.Order;
import com.younike.system.domain.OrderRecord;
import com.younike.system.service.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;

import static com.younike.common.constant.Constants.PREFIX_NO_PAY_ORDER;


/**
 * @author chenpengfei
 */
@Component
@Log4j2
public class DelayedReceiver {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderRecordService orderRecordService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private ISysCodeService sysCodeService;

    /**发布需求*/
    @Autowired
    private IPublishService publishService;

    @RabbitListener(queues = "delayed.home.order")
    public void process(Message message, Channel channel) throws IOException  {
        String msg = new String(message.getBody());
        log.info("延迟消息内容：" + msg);
        try {
            if (msg.startsWith(PREFIX_NO_PAY_ORDER)) {
                // 待支付订单
                log.info("取消超时未支付订单：执行");
                dealUnPayOrder(msg.replace(PREFIX_NO_PAY_ORDER, ""));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    /**
     * 待支付订单
     */
    private void dealUnPayOrder(String orderId) {
        Order order = orderService.selectOrderByOrderId(Long.valueOf(orderId));
        log.info("取消超时未支付订单：订单状态：" + order.getOrderState());
        if ("000".equals(order.getOrderState())) {
            if(!publishService.cancelPublishOrder(Long.valueOf(orderId))){
                log.error("未支付订单(" + orderId + ")更改服务状态失败！");
                throw new ArithmeticException("更改服务状态失败");
            }

            log.info("取消超时未支付订单：订单：" + orderId);
            order.setOrderState("099");
            if (orderService.updateOrder(order) > 0) {
                log.info("未支付订单(" + orderId + ")取消成功！");
                OrderRecord orderRecord = new OrderRecord();
                orderRecord.setPreState("000");
                orderRecord.setOrderId(Long.valueOf(orderId));
                orderRecord.setNowState("099");
                orderRecord.setOperateInfo(sysCodeService.getDecodeValue("003", "099"));
                orderRecordService.insertOrderRecord(orderRecord);
                Member member = memberService.selectMemberByMemberId(order.getMemberId());
                // 退优金豆
                FamilyParam familyParam = new FamilyParam();
                familyParam.setTargetId(order.getOrderId().toString());    // 设置 关联id
                familyParam.setCode("002");            // 设置 积分变动类型（001-消费 002-退款 003-抵扣 004-评价订单新增）
                familyParam.setPhone(member.getPhone());
                familyParam.setOperation(order.getMerchantName());  // 设置 备注（商家名称）
                familyParam.setNum(new BigDecimal(order.getBeanAmount()));    // 设置 扣除的积分数量

                String integralId = coinService.increasePoints(familyParam);
                if (StringUtils.isBlank(integralId)) {
                    log.error("未支付订单(" + orderId + ")退回优金豆失败！");
                    throw new GlobalException("退回优金豆失败");
                }
                //订单非团购状态下
                if(!"003".equals(order.getOrderType())) {
                    // 取消订单预定记录
                    orderService.cancelBook(order);
                }
            } else {
                log.error("未支付订单(" + orderId + ")取消失败！");
            }
        }
    }
}
