package com.heyu.api.listener.delay.handler;

import com.alibaba.fastjson.JSONObject;
import com.heyu.api.data.enums.OrderStatusEnums;
import com.heyu.api.data.dao.vv.VvTradeOrderLineDao;
import com.heyu.api.data.dto.WeiXinPayDelayDTO;
import com.heyu.api.data.entity.vv.VvTradeOrderLineEntity;
import com.heyu.api.data.utils.R;
import com.heyu.api.listener.BaseDelayedHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Slf4j
@Component("weiXinPayCloseHandler")
public class WeiXinPayCloseHandler extends BaseDelayedHandler {

    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;


    @Override
    public R handler(String message) {
        log.info("weiXinPayCloseHandler receive message:{}", message);
        WeiXinPayDelayDTO weiXinPayDelayDTO = JSONObject.parseObject(message, WeiXinPayDelayDTO.class);

        List<VvTradeOrderLineEntity> vvTradeOrderLineEntities = vvTradeOrderLineDao.selectVvTradeOrderLineByTradeOrderId(weiXinPayDelayDTO.getTradeOrderId());

        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntities) {
            if(OrderStatusEnums.wait_pay.getStatus().equals(vvTradeOrderLineEntity.getStatus())){
                vvTradeOrderLineEntity.setStatus(OrderStatusEnums.close.getStatus());
                vvTradeOrderLineEntity.setGmtClose(new Date());
                vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);
            }else{
                log.info("weiXinPayCloseHandler not to close tradeOrderLineId:{} status:{}", vvTradeOrderLineEntity.getId(),vvTradeOrderLineEntity.getStatus());
            }
        }
        return R.ok();
    }
}
