package org.dromara.payment.consumer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.payment.common.domain.BusAccounts;
import org.dromara.payment.merchant.domain.BusMerchantAccount;
import org.dromara.payment.merchant.domain.vo.BusMerchantAccountVo;
import org.dromara.payment.merchant.domain.vo.BusMerchantVo;
import org.dromara.payment.merchant.mapper.BusMerchantAccountMapper;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.operator.domain.BusOperator;
import org.dromara.payment.operator.domain.BusOperatorAccount;
import org.dromara.payment.operator.domain.vo.BusOperatorAccountVo;
import org.dromara.payment.operator.domain.vo.BusOperatorVo;
import org.dromara.payment.operator.mapper.BusOperatorAccountMapper;
import org.dromara.payment.operator.mapper.BusOperatorMapper;
import org.dromara.payment.operator.service.IBusOperatorAccountService;
import org.dromara.payment.sys.domain.SysSydAccount;
import org.dromara.payment.sys.service.ISysSydService;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
@Component
@RequiredArgsConstructor
public class BankAccountStreamConsumer {
    private final ISysSydService sydService;

    private final BusOperatorAccountMapper operatorAccountMapper;

    private final BusOperatorMapper operatorMapper;

    private final BusMerchantAccountMapper merchantAccountMapper;

    private final BusMerchantMapper merchantMapper;

    @Bean
    Consumer<JSONObject> account2() {
        log.info("订阅资金账户生成队列");
        return msg -> {
            log.info("通过stream消费到资金账户生成消息 => {}", msg);
            if (msg == null) {
                return;
            }
            try {
                Long unitId = null;
                String gsmc = null;
                Function<BusAccounts,Boolean> saveFun = null;
                Function<String,String> existsFun = null;
                if(msg.getInteger("accType") == BusRole.OPERATOR.getId()){
                    //运营商
                    BusOperatorVo vo = operatorMapper.selectVoById(msg.getInteger("accUnitId"));
                    if(vo != null){
                        unitId = vo.getId();
                        gsmc = vo.getName();
                    }
                    saveFun = add -> {
                        if(add != null) {
                            if(add.getId() > 0) {
                                Integer num = operatorAccountMapper.insertAccount(new BusOperatorAccount(add.getId(),add.getUnitId(), add.getAccId(), add.getBankType(), add.getBankCard(), add.getBalance(),0l, (long)1, add.getAddTime(),add.getName(),add.getKhh(),add.getLhh()));
                                return num > 0;
                            }
                            return true;
                        }
                        return false;
                    };
                    existsFun = bankType -> {
                        LambdaQueryWrapper<BusOperatorAccount> lqw = Wrappers.lambdaQuery();
                        lqw.eq(BusOperatorAccount::getOpId,vo.getId());
                        lqw.eq(BusOperatorAccount::getBankType,bankType);
                        List<BusOperatorAccountVo> accs = operatorAccountMapper.selectVoList(lqw);
                        return accs.size() > 0 ? accs.get(0).getBankVirtualCard() : null;
                    };
                }else if(msg.getInteger("accType") == BusRole.MERCHANT.getId()){
                    //商户
                    BusMerchantVo vo = merchantMapper.selectVoById(msg.getInteger("accUnitId"));
                    if(vo != null){
                        unitId = vo.getId();
                        gsmc = vo.getName();
                    }
                    saveFun = add -> {
                        if(add != null) {
                            if(add.getId() > 0) {
                                Integer num = merchantAccountMapper.insertAccount(new BusMerchantAccount(null,add.getId(),add.getUnitId(), add.getAccId(), add.getBankType(), add.getBankCard(), add.getBalance(),0l, (long)1, add.getAddTime(),add.getName(),add.getKhh(),add.getLhh()));
                                return num > 0;
                            }
                            return true;
                        }
                        return false;
                    };
                    existsFun = bankType -> {
                        LambdaQueryWrapper<BusMerchantAccount> lqw = Wrappers.lambdaQuery();
                        lqw.eq(BusMerchantAccount::getMerId,vo.getId());
                        lqw.eq(BusMerchantAccount::getBankType,bankType);
                        List<BusMerchantAccountVo> accs = merchantAccountMapper.selectVoList(lqw);
                        return accs.size() > 0 ? accs.get(0).getBankVirtualCard() : null;
                    };
                }
                String sydIds = msg.getString("sydIds");
                if(unitId == null || StringUtils.isBlank(gsmc) || StringUtils.isBlank(sydIds)){
                    throw new ServiceException("账户类型不支持");
                }
                String[] sydIdArr = sydIds.split(",");
                for (String sydId:sydIdArr
                     ) {
                    sydService.creatXNnum(Long.parseLong(sydId),unitId,gsmc,msg.getInteger("accType"),msg.getInteger("addAccType"), saveFun, existsFun);
                }
            } catch (Exception e) {
                log.error("资金账户生成出错：（"+msg+"）",e);
            }
        };
    }
}
