package com.iamberry.wechat.service.coupon;

import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.welfare.UserAmountLogs;
import com.iamberry.wechat.face.coupon.WelfareService;
import com.iamberry.wechat.service.mapper.OrderMapper;
import com.iamberry.wechat.service.mapper.UserAmountLogsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

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

/**
 * @author root
 */
@Lazy(value = false)
@Service
public class WelfareTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(WelfareTask.class);

    @Autowired
    private UserAmountLogsMapper amountLogsMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WelfareService welfareService;

    @Scheduled(cron = "59 59 23 * * ?")
    public void amount() {
        LOGGER.info("启动返利任务");
        UserAmountLogs select = new UserAmountLogs();
        select.setLogsDate(new Date());
        select.setLogsType(1);
        select.setLogsState(1);
        List<UserAmountLogs> list = amountLogsMapper.list(select);
        if (list == null || list.isEmpty()) {
            return;
        }
        for (UserAmountLogs logs : list) {
            // 校验订单状态
            Order order = new Order();
            order.setSalesOrderid(logs.getOrderId());
            order = orderMapper.selectOrderInfoById(order);
            if (order == null || order.getSalesStatus() != 5 || order.getSalesStatus() != 2) {
                LOGGER.error("{}的返利入账失败，订单号:{} ", logs.getUserOpenid(), logs.getOrderId());
                logs.setLogsState(2);
                logs.setLogsRemark("返利金额入账失败,原因:订单(" + logs.getOrderId() + ")状态非发货或已支付状态");
                amountLogsMapper.edit(logs);
                continue;
            }
            welfareService.enter(logs);
        }
    }

}
