package com.iformall.schedule;

import com.iformall.common.ResultData;
import com.iformall.domain.po.WxProfitSharingOrder;
import com.iformall.enums.EnumProfitSharingOrderStatus;
import com.iformall.mapper.*;
import com.iformall.service.WxProfitSharingOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SharingOrderResultSchedule {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxProfitSharingOrderService wxProfitSharingOrderService;

    @Autowired
    private WxProfitSharingOrderMapper wxProfitSharingOrderMapper;

    @Scheduled(cron = "0 15 0 * * ?") // 每天凌晨00:15更新分账结果
    //@Scheduled(cron = "*/10 * * * * ?") // 测试10秒中一次
    public void sharingOrderResultSchedule() {

        WxProfitSharingOrder wxProfitSharingOrder = new WxProfitSharingOrder();
        wxProfitSharingOrder.setSharingStatus(EnumProfitSharingOrderStatus.PROFIT_SHARING_ACCEPTED.getCode());
        List<WxProfitSharingOrder> list = wxProfitSharingOrderMapper.findList(wxProfitSharingOrder);
        for(WxProfitSharingOrder sharingOrder : list) {
            try {
                ResultData result = wxProfitSharingOrderService.querySharingOrder(sharingOrder);
                logger.info("状态更新结果:" + EnumProfitSharingOrderStatus.PROFIT_SHARING_ACCEPTED.getMessage()
                        + " ID:" +sharingOrder.getId()
                        + " MSG:" + result.message);
            } catch (Exception e){
                logger.error("状态更新失败:" + EnumProfitSharingOrderStatus.PROFIT_SHARING_ACCEPTED.getMessage()
                        + " ID:" +sharingOrder.getId()
                        + " MSG:" + e.getMessage());
            }
        }

        wxProfitSharingOrder.setSharingStatus(EnumProfitSharingOrderStatus.PROFIT_SHARING_PROCESSING.getCode());
        list = wxProfitSharingOrderMapper.findList(wxProfitSharingOrder);
        for(WxProfitSharingOrder sharingOrder : list) {
            try {
                ResultData result = wxProfitSharingOrderService.querySharingOrder(sharingOrder);
                logger.info("状态更新结果:" + EnumProfitSharingOrderStatus.PROFIT_SHARING_PROCESSING.getMessage()
                        + " ID:" + sharingOrder.getId()
                        + " MSG:" + result.message);
            } catch (Exception e){
                logger.error("状态更新失败:" + EnumProfitSharingOrderStatus.PROFIT_SHARING_PROCESSING.getMessage()
                        + " ID:" +sharingOrder.getId()
                        + " MSG:" + e.getMessage());
            }
        }

    }

}