package org.dromara.payment.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.bill.domain.MerBillDetail;
import org.dromara.payment.bill.service.IMerBillDetailService;
import org.dromara.payment.merchant.domain.BusMerchantAccount;
import org.dromara.payment.merchant.domain.BusMerchantAccountSyn;
import org.dromara.payment.merchant.domain.vo.BusMerchantAccountVo;
import org.dromara.payment.merchant.mapper.BusMerchantAccountMapper;
import org.dromara.payment.merchant.mapper.BusMerchantAccountSynMapper;
import org.dromara.payment.merchant.service.IBusMerchantAccountService;
import org.dromara.settlement.api.domain.AccountLog;
import org.dromara.settlement.api.domain.AccountSyn;
import org.springframework.stereotype.Service;
import org.dromara.payment.merchant.domain.bo.BusMerchantFlowsBo;
import org.dromara.payment.merchant.domain.vo.BusMerchantFlowsVo;
import org.dromara.payment.merchant.domain.BusMerchantFlows;
import org.dromara.payment.merchant.mapper.BusMerchantFlowsMapper;
import org.dromara.payment.merchant.service.IBusMerchantFlowsService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商户流水Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class BusMerchantFlowsServiceImpl implements IBusMerchantFlowsService {

    private final BusMerchantFlowsMapper baseMapper;

    private final BusMerchantAccountMapper merchantAccountMapper;

    private final IBusMerchantAccountService merchantAccountService;

    private final BusMerchantAccountSynMapper merchantAccountSynMapper;

    private final IMerBillDetailService billDetailService;

    /**
     * 查询商户流水
     */
    @Override
    public BusMerchantFlowsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商户流水列表
     */
    @Override
    public TableDataInfo<BusMerchantFlowsVo> queryPageList(BusMerchantFlowsBo bo, PageQuery pageQuery) {
        bo.setMerId(LoginHelper.getBusId());
        LambdaQueryWrapper<BusMerchantFlows> lqw = buildQueryWrapper(bo);
        Page<BusMerchantFlowsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商户流水列表
     */
    @Override
    public List<BusMerchantFlowsVo> queryList(BusMerchantFlowsBo bo) {

        LambdaQueryWrapper<BusMerchantFlows> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BusMerchantFlows> buildQueryWrapper(BusMerchantFlowsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusMerchantFlows> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMerId() != null, BusMerchantFlows::getMerId, bo.getMerId());
        lqw.eq(bo.getSydId() != null, BusMerchantFlows::getSydId, bo.getSydId());
        lqw.eq(bo.getBusType() != null, BusMerchantFlows::getBusType, bo.getBusType());
        lqw.eq(StringUtils.isNotBlank(bo.getChannel()), BusMerchantFlows::getChannel, bo.getChannel());
        lqw.eq(StringUtils.isNotBlank(bo.getBusNo()), BusMerchantFlows::getBusNo, bo.getBusNo());
        lqw.eq(StringUtils.isNotBlank(bo.getBankNo()), BusMerchantFlows::getBankNo, bo.getBankNo());
        lqw.eq(bo.getMoney() != null, BusMerchantFlows::getMoney, bo.getMoney());
        lqw.eq(bo.getBalance() != null, BusMerchantFlows::getBalance, bo.getBalance());
        lqw.eq(bo.getAddTime() != null, BusMerchantFlows::getAddTime, bo.getAddTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddBy()), BusMerchantFlows::getAddBy, bo.getAddBy());
        lqw.eq(StringUtils.isNotBlank(bo.getBusDesc()), BusMerchantFlows::getBusDesc, bo.getBusDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getBillNo()), BusMerchantFlows::getBillNo, bo.getBillNo());
        lqw.eq(bo.getBillId() != null, BusMerchantFlows::getBillId, bo.getBillId());
        lqw.eq(bo.getBillDetailId() != null, BusMerchantFlows::getBillDetailId, bo.getBillDetailId());
        lqw.eq(StringUtils.isNotBlank(bo.getTranNo()), BusMerchantFlows::getTranNo, bo.getTranNo());
        lqw.eq(bo.getTranType() != null, BusMerchantFlows::getTranType, bo.getTranType());
        lqw.eq(bo.getTranStatus() != null, BusMerchantFlows::getTranStatus, bo.getTranStatus());
        lqw.eq(bo.getPayerType() != null, BusMerchantFlows::getPayerType, bo.getPayerType());
        lqw.eq(bo.getPayerId() != null, BusMerchantFlows::getPayerId, bo.getPayerId());
        lqw.like(StringUtils.isNotBlank(bo.getPayerName()), BusMerchantFlows::getPayerName, bo.getPayerName());
        lqw.eq(StringUtils.isNotBlank(bo.getPayerAcc()), BusMerchantFlows::getPayerAcc, bo.getPayerAcc());
        lqw.eq(bo.getPayerAccId() != null, BusMerchantFlows::getPayerAccId, bo.getPayerAccId());
        lqw.eq(bo.getPayeeType() != null, BusMerchantFlows::getPayeeType, bo.getPayeeType());
        lqw.eq(bo.getPayeeId() != null, BusMerchantFlows::getPayeeId, bo.getPayeeId());
        lqw.like(StringUtils.isNotBlank(bo.getPayeeName()), BusMerchantFlows::getPayeeName, bo.getPayeeName());
        lqw.eq(StringUtils.isNotBlank(bo.getPayeeAcc()), BusMerchantFlows::getPayeeAcc, bo.getPayeeAcc());
        lqw.eq(bo.getPayeeAccId() != null, BusMerchantFlows::getPayeeAccId, bo.getPayeeAccId());
        lqw.eq(StringUtils.isNotBlank(bo.getPayReceipt()), BusMerchantFlows::getPayReceipt, bo.getPayReceipt());
        lqw.eq(bo.getPayReceiptType() != null, BusMerchantFlows::getPayReceiptType, bo.getPayReceiptType());
        lqw.eq(StringUtils.isNotBlank(bo.getIllustrate()), BusMerchantFlows::getIllustrate, bo.getIllustrate());
        if(StringUtils.isNotBlank(bo.getParams().get("begin_time")) && StringUtils.isNotBlank(bo.getParams().get("end_time"))){
            lqw.between(BusMerchantFlows::getAddTime,bo.getParams().get("begin_time")+" 00:00:00",bo.getParams().get("end_time")+" 23:59:59");
        }
        if(StringUtils.isNotBlank(bo.getParams().get("acc_id"))){
            BusMerchantAccountVo acc = merchantAccountMapper.selectVoById(Long.parseLong(bo.getParams().get("acc_id").toString()));
            lqw.and(i -> i.eq(BusMerchantFlows::getPayeeAccId,acc.getAccId()).or().eq(BusMerchantFlows::getPayerAccId,acc.getAccId()));
        }

        lqw.orderByDesc(BusMerchantFlows::getId);
        return lqw;
    }

    /**
     * 新增商户流水
     */
    @Override
    public Boolean insertByBo(BusMerchantFlowsBo bo) {
        BusMerchantFlows add = MapstructUtils.convert(bo, BusMerchantFlows.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商户流水
     */
    @Override
    public Boolean updateByBo(BusMerchantFlowsBo bo) {
        BusMerchantFlows update = MapstructUtils.convert(bo, BusMerchantFlows.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMerchantFlows entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商户流水
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveFlows(BusMerchantAccountVo acc, AccountSyn syn) {
        Long addAmount = 0l;
        List<BusMerchantFlows> flows = new ArrayList<BusMerchantFlows>();
        Long preMoney = 0l;
        for (AccountLog log : syn.getLogs()) {
            if(log.getTrxdir().intValue() == 1) {
                boolean isRecharge = true;//是否充值
                //订单退票,过滤账单明细和提现业务
                if (StringUtils.isNotBlank(log.getNarinn()) && log.getNarinn().startsWith("bus")) {
                    //账单代发退回
                    isRecharge = !billDetailService.refundBillDetail(log.getNarinn(),log.getTrxamt(),log.getTrxtxt());
                }
                if(isRecharge) {
                    BusMerchantFlows flow = new BusMerchantFlows();
                    flow.setDirection(1);//流水方向（1:收入 2:支出）
                    flow.setAddBy("系统");
                    flow.setAddTime(new Date());
                    flow.setBankNo(log.getTrxnbr());
                    flow.setBusType(2);//商户充值
                    flow.setChannel(syn.getBankType());
                    flow.setMerId(acc.getMerId());
                    flow.setMoney(log.getTrxamt());
                    flow.setPreMoney(preMoney);
                    flow.setSydId(acc.getSydId());
                    flow.setBusDesc("充值");
                    flow.setTranStatus(2);
                    flow.setPayerName(log.getRpynam());
                    flow.setPayerAcc(log.getRpyacc());
                    flow.setTranType(7);//充值交易
                    flow.setPayeeType(BusRole.MERCHANT.getId());
                    flow.setPayeeId(acc.getMerId());
                    flow.setPayeeName(acc.getMerName());
                    flow.setPayeeAcc(acc.getBankVirtualCard());
                    flow.setPayeeAccId(acc.getAccId());
                    flows.add(flow);
                    preMoney += flow.getMoney();
                    addAmount += flow.getMoney();
                }
            }
        }
        baseMapper.insertAll(flows);
        merchantAccountService.updateBalance(acc.getSydId(),acc.getMerId(), addAmount,acc.getBankType());
        merchantAccountSynMapper.update(new LambdaUpdateWrapper<BusMerchantAccountSyn>().eq(BusMerchantAccountSyn::getId,acc.getAccId())
            .set(BusMerchantAccountSyn::getSynPosition,syn.getLogs().get(syn.getLogs().size()-1).getId()));
        return addAmount;
    }
}
