package com.hfkj.schedule;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.entity.BsOrderSettle;
import com.hfkj.entity.BsOrderSettleLedger;
import com.hfkj.pay.HuiPayService;
import com.hfkj.service.order.BsOrderSettleLedgerService;
import com.hfkj.service.order.BsOrderSettleService;
import com.hfkj.sysenum.order.OrderSettleLedgerStatusEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单结算业务
 * @className: OrderSettleService
 * @author: HuRui
 * @date: 2024/6/25
 **/
@Component
public class OrderSettleSchedule {
    @Resource
    private BsOrderSettleService orderSettleService;
    @Resource
    private BsOrderSettleLedgerService orderSettleLedgerService;

    @Scheduled(cron="0 0/3 * * * ?")   //每3分钟执行一次
    public void getBlxCoupon() {
        Map<String,Object> param = new HashMap<>();
        param.put("ledgerStatus", OrderSettleLedgerStatusEnum.status2.getCode());
        List<BsOrderSettle> orderSettleList = orderSettleService.getList(param);
        for (BsOrderSettle orderSettle : orderSettleList) {
            // 查询分账处理结果
            JSONObject obj = HuiPayService.profitSharingQuery(orderSettle);
            if (obj.getString("return_code").equals("000000")) {
                // 1：已完成 2：处理中 3：已受理 4：失败
                if (obj.getInteger("status") == 1) {
                    orderSettle.setLedgerStatus(OrderSettleLedgerStatusEnum.status1.getCode());
                    orderSettleService.editData(orderSettle);
                    // 分账接收方
                    List<BsOrderSettleLedger> ledgerList = orderSettleLedgerService.getListBySettleId(orderSettle.getId());
                    for (BsOrderSettleLedger ledger : ledgerList) {
                        ledger.setStatus(1);
                        orderSettleLedgerService.editData(ledger);
                    }

                } else if (obj.getInteger("status") == 4) {
                    orderSettle.setLedgerStatus(OrderSettleLedgerStatusEnum.status4.getCode());
                    orderSettleService.editData(orderSettle);
                }
            }
        }
    }
}
