package org.dromara.payment.timer;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.payment.common.domain.vo.TranLogVo;
import org.dromara.payment.common.mapper.TranLogMapper;
import org.dromara.payment.common.service.ITranLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;
import tech.powerjob.worker.log.OmsLogger;

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

/**
 * 同步银行交易回置单任务
 * @author 张涛
 * @date 2021年9月3日
 */
@Component
public class BankTransactionCallBackJob {

    @Autowired
    private TranLogMapper synDao;

    @Autowired
    private ITranLogService tranLogService;

    @XxlJob("BankTransactionCallBackJob")
    public void process() throws Exception {
		long minId = 0;
		int limit = 10;
        XxlJobHelper.log("开始同步银行交易回置单");
        TranLogVo lockAccId = null;
		String synBatch = null;
		Integer row = 0;
		try {
			synBatch = DateUtils.parseDateToString("yyyyMMddHHmmssSSS", new Date());
			do {
				row = synDao.allotSyns(synBatch,2,(byte)0,minId,0,limit);
				if(row > 0) {
					List<TranLogVo> schools = synDao.selectTranLog(synBatch,2,(byte)0, null);
					for (TranLogVo accid : schools) {
                        try {
                            tranLogService.synTransferCallBack(accid);
                        } catch (Exception e) {
                            XxlJobHelper.log("同步银行交易回置单出错（" + minId + "," + limit + "," + JSONObject.toJSONString(accid) + "）：",e);
                        }
						synDao.cancelSyn(accid.getId());
						minId = accid.getId();
					}
				}
			} while (row == limit);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
            XxlJobHelper.log("同步银行交易回置单出错（" + minId + "," + limit + "）：",e);
		}finally {
			if(row > 0) {
				try {
					synDao.cancelSynByBatch(synBatch, 2);
				} catch (Exception e) {
                    XxlJobHelper.log("同步银行交易回置单时解锁出错（" + minId + "," + limit + "," + synBatch + "）：", e);
				}
			}
		}
        XxlJobHelper.log("结束同步银行交易回置单");
	}
}
