package cn.pluss.platform.job;

import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.entity.MerchantRefundOrder;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.refundOrder.MerchantRefundOrderService;
import cn.pluss.platform.sxf.pay.SxfPayService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.util.SxfConfg;
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.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

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

/**
 * 检查退管订单状态定时任务
 *
 * @Author admin
 *
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class CheckMerchantRefundOrderStatusJob {

    @Autowired
    private MerchantRefundOrderService merchantRefundOrderService;

    @Autowired
    private SxfPayService sxfPayService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysPayService")})
    private PayService ysPayService;

    /**
     * 检查退款订单的状态TASK
     * 每30分钟执行一次
     */
    @Scheduled(fixedDelay = 30 * 60 * 1000)
    public void checkMercRefundOrderStatusTask(){
        log.info("===============>检查退款订单状态定时任务开始<==================");
        Date startDate = DateUtils.getDayBegin();
        Date endDate =  DateUtils.getDayEnd();
        QueryWrapper<MerchantRefundOrder> queryWrapper = new QueryWrapper<MerchantRefundOrder>()
                .eq("status","2").between("createTime",startDate,endDate);
        List<MerchantRefundOrder> refundOrderList = merchantRefundOrderService.list(queryWrapper);
        if(refundOrderList.isEmpty()){
            log.info("===============>当前退款中的订单数据为空，定时任务结束!<==================");
            return;
        }
        log.info("===============>待更新退款订单的数据条数为:{}<==================",refundOrderList.size());
        refundOrderList.forEach(refundOrder ->{
            if(refundOrder.getOrderNumber().contains("SXF")){
                JSONObject qData = sxfPayService.refundQuery(refundOrder);
                log.info("===========>退款订单上送，返回参数:{}<===============",qData.toJSONString());
                if("1".equals(qData.get("code").toString())){
                    Map<String,String> respData = (Map<String,String>)qData.get("data");
                    String tranSts = respData.get("tranSts");
                    refundOrder.setFailMsg(respData.get("bizMsg"));
                    //退款成功
                    if(SxfConfg.SXF_REFUND_SUCCESS_STATUS_CODE.equalsIgnoreCase(tranSts)){
                        refundOrder.setStatus("1");
                        Date payTime = DateUtils.parse(respData.get("payTime"));
                        refundOrder.setRefundTime(payTime);
                    }else if(SxfConfg.SXF_REFUND_FAIL_STATUS_CODE.equalsIgnoreCase(tranSts)){
                        refundOrder.setStatus("3");
                    }else if(SxfConfg.SXF_REFUND_ING_STATUS_CODE.equalsIgnoreCase(tranSts)){
                        return;
                    }
                    merchantRefundOrderService.updateById(refundOrder);
                }
            }else if(refundOrder.getOrderNumber().contains("YS")){
                JSONObject object = ysPayService.refundQuery(refundOrder);
                if(ResultCode.SUCCESS.code() == object.getIntValue("code")){
                    refundOrder.setStatus(object.getString("status"));
                    if(StringUtil.isNotEmpty(object.getString("refundTime"))){
                        Date refundTime = DateUtils.parse(object.getString("refundTime"), "yyyyMMddHHmmss");
                        refundOrder.setRefundTime(refundTime);
                    }
                    merchantRefundOrderService.updateById(refundOrder);
                }else{
                    log.info("===============>定时任务查询退款订单状态,订单号为:{}的退款订单,查询异常,异常信息:{}<============",refundOrder.getRefundNo(),object.getString("msg"));
                }
            }
        });
        log.info("===============>退款检查退款订单状态定时任务执行结束<==================");
    }
}
