package com.jeequan.jeepay.pay.task;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.components.mq.model.PayOrderMarketMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.core.model.applyment.ApplymentBasicInfo;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.impl.*;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * TODO
 * 红包过期定时任务处理
 * @author crystal
 * @date 2024/1/26 11:09
 */
@Component
@Slf4j
public class RedPacketExpireTask {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private RedPacketInfoService redPacketInfoService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private MchApplymentService mchApplymentService;


    @Autowired
    private BankBranchAlipayService bankBranchAlipayService;

    @Autowired
    private TransferOrderService transferOrderService;

    @Autowired
    private IMQSender imqSender;

    /**
     * 红包过期定时任务处理
     */
    @XxlJob("redPacketExpireTaskHandler")
    public void start() {
        log.info("【红包过期】定时任务开始");
        try {
            Boolean isPlatOpen = sysConfigService.getDbMarketPlatRedPacket();
            if(!isPlatOpen){
                log.info("【红包过期】定时任务结算，平台未开启平台红包功能");
                return;
            }
            List<RedPacketInfo> list = redPacketInfoService.listRedPacketByExpire();
            if(list.isEmpty()){
                log.info("【红包过期】定时任务结算，未获取到即将过期的红包记录");
                return;
            }
            for (RedPacketInfo packetInfo:list) {
                boolean flag = redPacketInfoService.updateRedExpire(packetInfo.getFlowNo(),RedPacketInfo.EXPIRE,"红包使用期限超时，系统自动处理过期");
                if(flag && RedPacketInfo.NO_USE == packetInfo.getState() && packetInfo.getActualAmt() > 0){
                    //调用营销补贴
                    BigDecimal scale = packetInfo.getDiscountScale().compareTo(BigDecimal.TEN) >= 0 ? packetInfo.getDiscountScale().divide(BigDecimal.valueOf(100)) : packetInfo.getDiscountScale().divide(BigDecimal.TEN);
                    BigDecimal calcScale = BigDecimal.ONE.subtract(scale);
                    BigDecimal fkAmt = BigDecimal.valueOf(packetInfo.getActualAmt()).multiply(calcScale).setScale(0, RoundingMode.DOWN);
                    //如果大于0 则进行打款
                    if(fkAmt.compareTo(BigDecimal.ZERO) > 0){
                        PayOrder payOrder = payOrderService.getById(packetInfo.getFlowNo());
                        if(payOrder != null){
                            BigDecimal rate = new BigDecimal("0.001");
                            TransferOrderEntity transferOrder = new TransferOrderEntity();
                            transferOrder.setTransferId(SeqKit.genTransferId());
                            transferOrder.setMchNo(payOrder.getMchNo());
                            transferOrder.setIsvNo(payOrder.getIsvNo());
                            transferOrder.setAgentNo(payOrder.getAgentNo());
                            transferOrder.setAppId(payOrder.getAppId());
                            transferOrder.setMchName(payOrder.getMchName());
                            transferOrder.setMchType(payOrder.getMchType());
                            transferOrder.setMchOrderNo(SeqKit.genMhoOrderId());
                            transferOrder.setIfCode(CS.IF_CODE.SYBPAY);
                            transferOrder.setAmount(fkAmt.longValue());
                            transferOrder.setCurrency("cny");
                            transferOrder.setState(TransferOrderEntity.STATE_INIT);
                            transferOrder.setMchExtNo(payOrder.getMchExtNo());
                            //固定写死到银行卡
                            transferOrder.setEntryType(TransferOrder.ENTRY_BANK_CARD);
                            transferOrder.setMchFeeRate(rate.multiply(BigDecimal.valueOf(100)) + "%");
                            transferOrder.setMchOrderFeeAmount(fkAmt.multiply(rate).setScale(0,RoundingMode.HALF_EVEN).longValue());
                            transferOrder.setTransferDesc("营销红包过期，自动返现");
                            JSONObject channelExtra = new JSONObject(8);
                            channelExtra.put("settleType", MchApplyment.SETT_ACCOUNT_TYPE_PERSONAL);
                            //获取商户的信息
                            MchApplyment applyment = mchApplymentService.getById(payOrder.getMchExtNo());
                            if(applyment == null){
                                transferOrder.setState(TransferOrderEntity.STATE_FAIL);
                                transferOrder.setTransferDesc("商户信息未获取到");
                            }else{
                                ApplymentBasicInfo detailJson = JSONObject.parseObject(applyment.getApplyDetailInfo(),ApplymentBasicInfo.getImplInfoClass(payOrder.getIfCode()));
                                if(detailJson == null){
                                    transferOrder.setState(TransferOrderEntity.STATE_FAIL);
                                    transferOrder.setTransferDesc("商户信息未获取异常");
                                }else{
                                    String bankBranchNo = detailJson.bankBranchNo();
                                    //获取关联的支付宝支行联行号
                                    BankBranchAlipay branch = bankBranchAlipayService.getById(bankBranchNo);
                                    if(branch == null){
                                        transferOrder.setState(TransferOrderEntity.STATE_FAIL);
                                        transferOrder.setTransferDesc("商户绑定的结算卡支行信息异常");
                                    }else{
                                        // B:对公 C:对私
                                        String settAccountType = detailJson.getSettAccountType();
                                        if(StringUtils.isNotEmpty(settAccountType)){
                                            channelExtra.put("settleType",settAccountType);
                                        }
                                        String settAccountNo = detailJson.getSettAccountNo();
                                        String settAccountName = detailJson.bankAccountName();
                                        transferOrder.setAccountNo(settAccountNo);
                                        transferOrder.setAccountName(settAccountName);
                                        transferOrder.setBankName(branch.getBankName());
                                        channelExtra.put("branchName",branch.getBranchName());
                                        channelExtra.put("provinceName",branch.getProvinceName());
                                        channelExtra.put("cityName",branch.getCityName());
                                    }
                                }
                            }
                            transferOrder.setChannelExtra(channelExtra.toString());
                            transferOrderService.save(transferOrder);
                            imqSender.send(PayOrderMarketMQ.build(transferOrder.getTransferId(),PayOrderMarketMQ.RED_TYPE),10);
                        }
                    }
                }
            }
            log.info("【红包过期】定时任务结算，处理结束");
        }catch (Exception e){
            log.info("【红包过期】任务异常，异常信息:{}",e.getMessage());
        }
    }
}
