package cn.pluss.platform.job;

import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.MerchantOrder;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.ryx.pay.RyxPayService;
import cn.pluss.platform.sxf.pay.SxfPayService;
import cn.pluss.platform.util.DateUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

/**
 * 定时任务检查待确认状态的订单数据
 * @author admin
 * 
 * @Description
 */
@Slf4j
// @Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class CheckTransOrderStatusJob {


    @Resource
    private MerchantOrderService merchantOrderService;
    @Resource
    private MerchantChannelStatusService merchantChannelStatusService;
    @Resource
    private RyxPayService ryxPayService;
    @Resource
    private SxfPayService sxfPayService;
    @Setter(onMethod_ = {@Autowired, @Qualifier("ysPayOldService")})
    private PayService ysPayOldService;

    /**
     * 检查待确认订单状态定时任务 5秒执行一次
     */
    @Scheduled(fixedDelay = 5  * 1000)
    public void checkOrderStatus() {
        log.info("================>检查待确认订单状态定时任务开始<=====================");
        Date now = new Date();
        Date endTime = DateUtils.add(Calendar.SECOND, now, -10);
        Date startTime = DateUtils.add(Calendar.MINUTE, endTime, -2);
        QueryWrapper<MerchantOrder> orderWrapper = new QueryWrapper<MerchantOrder>()
                .in("status","5","7").between("createDt",startTime,endTime)
                .select("id");
        List<Long> orderIdList = merchantOrderService.listObjs(orderWrapper, new Function<Object, Long>() {
            @Override
            public Long apply(Object o) {
                if (o instanceof Integer) {
                    return ((Integer) o).longValue();
                }

                if (o instanceof Long) {
                    return ((Long) o);
                }

                if (o instanceof String) {
                    return Long.parseLong((String) o);
                }

                return null;
            }
        });

        QueryWrapper<MerchantOrder> qWrapper2 = new QueryWrapper<MerchantOrder>().in("id", orderIdList);
        List<MerchantOrder> orderList = merchantOrderService.list(qWrapper2);

        if (orderList.isEmpty()) {
            log.info("=================>没有需要处理的待确认订单状态的数据，定时任务结束<=================");
            return;
        }
        for (MerchantOrder order:orderList) {
            MerchantChannelStatus channel = null;
            if (order.getOrderNumber().startsWith("SXF")) {
                channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(), 1);
            }

            if (order.getOrderNumber().startsWith("RYX")) {
                channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(), 3);
            }

            if (order.getOrderNumber().startsWith("YS")) {
                channel = merchantChannelStatusService.getByMerchantCode(order.getMerchantCode(), 4);
            }

            if(channel == null){
                log.info("=============>检查待确认订单状态定时任务商户编号为:{}，的进件数据为空，跳过当前订单状态确认<================",order.getMerchantCode());
                continue;
            }
            log.info("======>【订单查询接口】当前查询订单号：{},订单状态:{}<=======",order.getOrderNumber(),order.getStatus());
            //随行付
            JSONObject result = null;
            if(channel.getChannel() == 1){
                result = sxfPayService.tradeQuery(order, channel.getMerchantId());
                //乐刷
            }else if(channel.getChannel() == 2){
                continue;
            //瑞银信
            }else if(channel.getChannel() == 3){
                result = ryxPayService.tradeQuery(order, channel.getMerchantId());
            //银盛
            }else if(channel.getChannel() == 4){
                result = ysPayOldService.tradeQuery(order, channel.getMerchantId());
            }else{
                continue;
            }
            if(result != null){
                merchantOrderService.updateOrderStatus(result,order);
            }
        }
        log.info("=====检查待确认订单状态定时任务结束=====");
    }

    /**
     * 修改待确认订单状态
     * @param order
     * @param result
     */
//    private void updateOrderStatus(MerchantOrder order, JSONObject result) {
//        log.info("===============>待确认订单查询接口返回支付结果参数:{}<===============",result);
//        MerchantOrder update = new MerchantOrder();
//        int code = result.getIntValue("code");
//        if(ResultCode.SUCCESS.code() == code){
//            update.setId(order.getId());
//            String payStatus = (String)result.get("payStatus");
//            if("1".equals(payStatus)){
//                String channelOrderNo = result.getString("channelOrderNo");
//                String transNo = result.getString("transNo");
//                String fee = result.getString("fee");
//                update.setStatus("1");
//                update.setTransNo(transNo);
//                update.setTransDt(result.getDate("payTime"));
//                update.setThirdTransNo(channelOrderNo);
//                if(StringUtil.isNotEmpty(fee) && order.getOrderNumber().startsWith("YS")){
//                    BigDecimal tradeAmt = new BigDecimal(order.getConsumeFee().toString());
//                    BigDecimal cashRate = new BigDecimal("0.001");
//                    BigDecimal minFee = new BigDecimal("0.1");
//                    BigDecimal cashFee = tradeAmt.multiply(cashRate).compareTo(minFee) > 0 ? tradeAmt.multiply(cashRate) : minFee;
//                    update.setEnterFee(tradeAmt.subtract(new BigDecimal(fee)).subtract(cashFee).setScale(2,BigDecimal.ROUND_DOWN).doubleValue());
//                }
//                merchantOrderService.updateById(update);
//                //创建分润
//                merchantProfitService.createOrderProfit(order);
//                log.info("==================>待确认的订单号为：{}的订单，订单状态更新成功<========================",order.getOrderNumber());
//            }else if("0".equals(payStatus) || "6".equals(payStatus)){
//                update.setStatus(payStatus);
//                merchantOrderService.saveOrUpdate(update);
//            }
//        }
//    }
}
