package com.jeequan.jeepay.member.task;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.db.entity.MemberRechargeRecord;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.service.impl.MemberRechargeRecordService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 会员充值定时
 *
 * @author xiaoyu
 * @date 2023/4/15 10:07
 */
@Slf4j
@Component
public class MemberRechargeTask {

    @Autowired private MemberRechargeRecordService rechargeRecordService;
    @Autowired private PayOrderService payOrderService;

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @XxlJob("memberRechargeOrderTaskHandler")
    public void start() {

        log.info("开始【处理会员充值任务】");

        //查询条件：充值中的记录
        LambdaQueryWrapper<MemberRechargeRecord> lambdaQueryWrapper = MemberRechargeRecord.gw()
                .eq(MemberRechargeRecord::getState, MemberRechargeRecord.STATE_ING)
                .select(MemberRechargeRecord::getPayOrderId, MemberRechargeRecord::getRechargeRecordId);
        int currentPageIndex = 1; //当前页码
        while(true){

            try {
                // 查询充值中的记录
                IPage<MemberRechargeRecord> resultPage = rechargeRecordService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);

                if(resultPage == null || resultPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询;
                    break;
                }
                // 缓存订单号
                ArrayList<String> orderList = new ArrayList<>();
                resultPage.getRecords().stream().forEach(record ->{
                    orderList.add(record.getPayOrderId());
                });

                // 订单号列表为空 跳出循环
                if (CollectionUtil.isEmpty(orderList)) {
                    break;
                }

                // 查询关联订单
                List<PayOrder> payOrderList = payOrderService.list(PayOrder.gw().in(PayOrder::getPayOrderId, orderList));
                // 缓存订单信息
                HashMap<String, PayOrder> orderMap = new HashMap<>();
                payOrderList.stream().forEach(order -> {
                    orderMap.put(order.getPayOrderId(), order);
                });

                for (MemberRechargeRecord record : resultPage.getRecords()) {

                    PayOrder payOrder = orderMap.get(record.getPayOrderId());
                    if (payOrder == null) {
                        log.info("【处理会员充值任务】订单{}不存在", record.getPayOrderId());
                        break;
                    }
                    // 支付成功处理充值
                    if (PayOrder.STATE_SUCCESS == payOrder.getState()) {

                        // 处理充值记录
                        boolean result = rechargeRecordService.updateIng2SuccessAndMbrAccount(record.getRechargeRecordId(), payOrder.getPayOrderId());
                        log.info("【处理会员充值任务】订单支付成功 rechargeId：{}, payOrderId：{}, 处理结果:{}", record.getRechargeRecordId(), payOrder.getPayOrderId(), result);

                        // 订单不为初始化、支付中、支付成功时。处理为充值失败
                    }else if (PayOrder.STATE_INIT != payOrder.getState() && PayOrder.STATE_ING != payOrder.getState() && PayOrder.STATE_SUCCESS != payOrder.getState()) {
                        // 处理充值记录
                        rechargeRecordService.updateIng2Fail(record.getRechargeRecordId(), payOrder.getErrCode(), payOrder.getErrMsg());
                        log.info("【处理会员充值任务】订单支付失败 rechargeId：{}, payOrderId：{}, errCode：{}, errMsg:{}, 订单状态：{}", record.getRechargeRecordId(), payOrder.getPayOrderId(), payOrder.getErrCode(), payOrder.getErrMsg(), payOrder.getState());

                    }else {
                        // 其他状态跳过
                        break;
                    }

                }

                //已经到达页码最大量，无需再次查询
                if(resultPage.getPages() <= currentPageIndex){
                    break;
                }
                currentPageIndex++;

            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        log.info("结束【处理会员充值任务】");
    }


}
