package com.jeequan.jeepay.pay.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.model.applyment.MchModifyApplymentModel;
import com.jeequan.jeepay.core.utils.HolidayUtil;
import com.jeequan.jeepay.db.entity.MchModifyApplymentEntity;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchModifyApplymentService;
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 org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.Date;

@Component
@Slf4j
public class SyncMchSettlementTypeTask {

    @Autowired private MchModifyApplymentService modifyApplymentService;

    @Autowired private MchApplymentService mchApplymentService;

    @Autowired private TransactionDefinition transactionDefinition;

    @Autowired private PlatformTransactionManager platformTransactionManager;

    @XxlJob("syncMchSettlementTypeTaskHandler")
    public void start() {
        log.info("【同步部分通道变更结算方式(D0、D1)】定时任务开始");

        int pageSize = 100; // 根据需要调整页面大小
        int currentPage = 1;

        boolean isWorkDay = HolidayUtil.isWorkDay(new Date());

        while (true) {
            Page<MchModifyApplymentEntity> page = new Page<>(currentPage, pageSize);

            modifyApplymentService.lambdaQuery()
//                    .eq(MchModifyApplymentEntity::getState, MchApplyment.STATE_AUDITING)
//                    .eq(MchModifyApplymentEntity::getIfCode, CS.IfCode.YSPAY.getValue())
                    .eq(MchModifyApplymentEntity::getState, MchApplyment.STATE_SUCCESS_INEFFECTIVE)
                    // 银盛开通D1，从第二个工作日开始计算
                    .or(wrapper -> {
                        wrapper.eq(MchModifyApplymentEntity::getState, MchApplyment.STATE_AUDITING)
                                .eq(MchModifyApplymentEntity::getIfCode, CS.IfCode.YSPAY.getValue());
                    })
                    .page(page);

            page.getRecords().forEach(item -> {
                String applyId = item.getApplyId();

                try {
                    MchModifyApplymentModel applymentModel = JSON.parseObject(item.getApplyDetailInfo(), MchModifyApplymentModel.class);

                    // 拉卡拉汇拓客次日完成结算方式变更
                    if (item.getIfCode().equalsIgnoreCase(CS.IfCode.LKLSB2BPAY.getValue())
                        || item.getIfCode().equalsIgnoreCase(CS.IfCode.LKLSPAY.getValue())) {

                        MchModifyApplymentEntity resultModifyApply = new MchModifyApplymentEntity();
                        resultModifyApply.setModifyApplyId(item.getModifyApplyId())
                                .setState(MchApplyment.STATE_SUCCESS);

                        com.jeequan.jeepay.db.entity.MchApplyment resultMchApplyment = new com.jeequan.jeepay.db.entity.MchApplyment();
                        resultMchApplyment.setSettlementType(applymentModel.getSettlementType())
                                .setApplyId(applyId);

                        // 更新状态，此处使用编程式事务
                        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
                        try {
                            modifyApplymentService.updateById(resultModifyApply);
                            mchApplymentService.updateById(resultMchApplyment);
                            platformTransactionManager.commit(transaction);
                        } catch (Exception e) {
                            log.error("更新 applyId 为 {} 的实体时出错", applyId, e);
                            // Rollback the transaction
                            platformTransactionManager.rollback(transaction);
                        }
                    }


                    if (CS.IfCode.YSPAY.getValue().equalsIgnoreCase(item.getIfCode()) &&
                            isWorkDay) {

                        MchModifyApplymentEntity resultModifyApply = new MchModifyApplymentEntity();
                        resultModifyApply.setModifyApplyId(item.getModifyApplyId())
                                .setState(MchApplyment.STATE_SUCCESS);

                        com.jeequan.jeepay.db.entity.MchApplyment resultMchApplyment = new com.jeequan.jeepay.db.entity.MchApplyment();
                        resultMchApplyment.setSettlementType(applymentModel.getSettlementType())
                                .setApplyId(applyId);

                        com.jeequan.jeepay.db.entity.MchApplyment mchApplyment = mchApplymentService.getById(applyId);

                        // 更新状态，此处使用编程式事务
                        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
                        try {
                            modifyApplymentService.updateById(resultModifyApply);
                            // T1转D1
                            if (applymentModel.getSettlementType().equalsIgnoreCase(CS.SETTLEMENT_TYPE.D1)
                                    && mchApplyment.getSettlementType().equalsIgnoreCase(CS.SETTLEMENT_TYPE.T1)) {
                                mchApplymentService.updateById(resultMchApplyment);
                            }

                            platformTransactionManager.commit(transaction);
                        } catch (Exception e) {
                            log.error("更新 applyId 为 {} 的实体时出错", applyId, e);
                            // Rollback the transaction
                            platformTransactionManager.rollback(transaction);
                        }
                    }

                } catch (Exception e) {
                    log.error("操作异常，applyId: {}", applyId, e);
                }

            });

            currentPage++;

            if (currentPage > page.getPages()) {
                break; // 没有更多数据，退出循环
            }
        }


        log.info("【同步部分通道变更结算方式(D0、D1)】定时任务结束");
    }
}
