package com.sqx.modules.job.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.pay.dao.CashOutDao;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.service.WuyouCallbackService;
import com.sqx.modules.pay.wuyou.BaseResp;
import com.sqx.modules.pay.wuyou.WuyouPay;
import com.sqx.modules.sys.dao.SysUserMoneyDao;
import com.sqx.modules.sys.entity.SysUserMoney;
import com.sqx.modules.sys.entity.SysUserMoneyDetails;
import com.sqx.modules.sys.service.SysUserMoneyDetailsService;
import com.sqx.modules.sys.service.SysUserMoneyService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
@Profile({"prod"})
public class TempCashOutTask {

    @Resource
    private CashOutDao cashOutDao;
    @Resource
    private WuyouPay wuyouPay;
    @Resource
    private WuyouCallbackService wuyouCallbackService;

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


    @Scheduled(cron = "0 0/8 * * * ? ")
    public void run() {
        List<CashOut> cashOuts = cashOutDao.selectTemp(DateUtil.offsetMinute(DateUtil.date(), 15));
        logger.info("定时查询提现订单 待处理订单: {}", cashOuts.size());

        List<String> sucOrderList = new ArrayList<>();
        List<String> failOrderList = new ArrayList<>();
        for (CashOut cashOut : cashOuts) {
            try {
                BaseResp baseResp = wuyouPay.queryExtractOrder(cashOut.getOrderNumber(), cashOut.getUserId(), cashOut.getUserType() != 2, cashOut.getMoney());
                int i = wuyouCallbackService.executeExtractCallback(cashOut, baseResp);
                if (i == 1) {
                    sucOrderList.add(cashOut.getOrderNumber());
                } else {
                    failOrderList.add(cashOut.getOrderNumber());
                }
            } catch (Exception e) {
                logger.error("体现定时任务查询出错", e);
            }
        }

        logger.info("定时查询提现订单  提现结束, 成功：{}条, 失败：{}条", sucOrderList.size(), failOrderList.size());
        logger.info("定时查询提现订单  提现结束, 成功：{}, 失败：{}", JSONUtil.toJsonStr(sucOrderList), JSONUtil.toJsonStr(failOrderList));
    }
}
