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

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.exception.ServiceException;
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.payment.bill.service.IMerBillService;
import org.dromara.payment.common.domain.TranLog;
import org.dromara.payment.common.domain.vo.TranLogVo;
import org.dromara.payment.common.mapper.TranLogMapper;
import org.dromara.payment.merchant.domain.BusMerchant;
import org.dromara.payment.merchant.domain.BusMerchantFlows;
import org.dromara.payment.merchant.domain.vo.BusMerchantAccountVo;
import org.dromara.payment.merchant.domain.vo.BusMerchantVo;
import org.dromara.payment.merchant.mapper.BusMerchantFlowsMapper;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.merchant.service.IBusMerchantAccountService;
import org.dromara.payment.sys.domain.SysSydCashout;
import org.dromara.payment.sys.domain.SysSydFlows;
import org.dromara.payment.sys.domain.vo.SysSydAccountVo;
import org.dromara.payment.sys.domain.vo.SysSydCashoutVo;
import org.dromara.payment.sys.domain.vo.SysSydVo;
import org.dromara.settlement.api.RemoteAccountService;
import org.dromara.settlement.api.domain.Account;
import org.dromara.settlement.api.domain.Result;
import org.dromara.settlement.api.domain.TransactionLog;
import org.springframework.stereotype.Service;
import org.dromara.payment.merchant.domain.bo.BusMerchantCashoutBo;
import org.dromara.payment.merchant.domain.vo.BusMerchantCashoutVo;
import org.dromara.payment.merchant.domain.BusMerchantCashout;
import org.dromara.payment.merchant.mapper.BusMerchantCashoutMapper;
import org.dromara.payment.merchant.service.IBusMerchantCashoutService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商户提现记录Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class BusMerchantCashoutServiceImpl implements IBusMerchantCashoutService {

    private final BusMerchantCashoutMapper baseMapper;

    private final BusMerchantMapper merchantMapper;

    private final IBusMerchantAccountService busMerchantAccountService;

    private final IMerBillService billService;

    private final TranLogMapper tranLogDao;//交易日志dao

    private final BusMerchantFlowsMapper merchantFlowsMapper;

    private final IBusMerchantAccountService merchantAccountService;

    @DubboReference
    private RemoteAccountService accountService;//银行账户业务

    /**
     * 查询商户提现记录
     */
    @Override
    public BusMerchantCashoutVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商户提现记录列表
     */
    @Override
    public TableDataInfo<BusMerchantCashoutVo> queryPageList(BusMerchantCashoutBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusMerchantCashout> lqw = buildQueryWrapper(bo);
        Page<BusMerchantCashoutVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商户提现记录列表
     */
    @Override
    public List<BusMerchantCashoutVo> queryList(BusMerchantCashoutBo bo) {
        LambdaQueryWrapper<BusMerchantCashout> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BusMerchantCashout> buildQueryWrapper(BusMerchantCashoutBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusMerchantCashout> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSydId() != null, BusMerchantCashout::getSydId, bo.getSydId());
        lqw.eq(bo.getMerId() != null, BusMerchantCashout::getMerId, bo.getMerId());
        lqw.eq(bo.getAccId() != null, BusMerchantCashout::getAccId, bo.getAccId());
        lqw.eq(StringUtils.isNotBlank(bo.getBusNo()), BusMerchantCashout::getBusNo, bo.getBusNo());
        lqw.eq(bo.getAmount() != null, BusMerchantCashout::getAmount, bo.getAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getKhh()), BusMerchantCashout::getKhh, bo.getKhh());
        lqw.eq(StringUtils.isNotBlank(bo.getKhhNo()), BusMerchantCashout::getKhhNo, bo.getKhhNo());
        lqw.eq(StringUtils.isNotBlank(bo.getFr()), BusMerchantCashout::getFr, bo.getFr());
        lqw.eq(StringUtils.isNotBlank(bo.getKhd()), BusMerchantCashout::getKhd, bo.getKhd());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCard()), BusMerchantCashout::getBankCard, bo.getBankCard());
        lqw.eq(bo.getPayStatus() != null, BusMerchantCashout::getPayStatus, bo.getPayStatus());
        lqw.eq(bo.getPayTime() != null, BusMerchantCashout::getPayTime, bo.getPayTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPayRemark()), BusMerchantCashout::getPayRemark, bo.getPayRemark());
        lqw.eq(bo.getAddTime() != null, BusMerchantCashout::getAddTime, bo.getAddTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddBy()), BusMerchantCashout::getAddBy, bo.getAddBy());
        lqw.eq(StringUtils.isNotBlank(bo.getPassage()), BusMerchantCashout::getPassage, bo.getPassage());
        lqw.eq(StringUtils.isNotBlank(bo.getPayReceipt()), BusMerchantCashout::getPayReceipt, bo.getPayReceipt());
        return lqw;
    }

    /**
     * 新增商户提现记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BusMerchantCashoutBo bo) {
        BusMerchantCashout add = MapstructUtils.convert(bo, BusMerchantCashout.class);
        validEntityBeforeSave(add);
        BusMerchantAccountVo vo = busMerchantAccountService.getCashoutAccount(bo.getAccId());
        if(vo == null){
            throw new ServiceException("资金账户不存在，提现失败");
        }
        if(vo.getBalance() - vo.getFrozen() < bo.getAmount()){
            throw new ServiceException("资金账户可用余额不足，提现失败");
        }
        billService.checkPayPassword(BusRole.MERCHANT, vo.getMerId(), () -> {
            BusMerchant merchant = merchantMapper.selectOne(new LambdaQueryWrapper<BusMerchant>().eq(BusMerchant::getId,vo.getMerId()));
            if(StringUtils.isBlank(merchant.getPayPassword())){
                throw new ServiceException("请前往系统管理进行支付密码重置！");
            }
            return !bo.getPassword().equals(merchant.getPayPassword());
        });
        String busDesc = "商户提现";
        if(merchantAccountService.updateFrozenByAccId(vo.getAccId().intValue(),bo.getAmount()) == 0){
            throw new ServiceException(busDesc+"时，"+vo.getBankType()+"账户可用余额不足");
        }
        add.setSydId(vo.getSydId());
        add.setMerId(vo.getMerId());
        add.setKhd(vo.getKfd());
        add.setKhh(vo.getKfh());
        add.setKhhNo(vo.getKhhNo());
        add.setFr(vo.getAccName());
        add.setBankCard(vo.getBankVirtualCard());
        add.setPassage(vo.getBankType());
        add.setBusNo("PW"+IdUtil.getSnowflakeNextIdStr());
        add.setAddTime(new Date());
        add.setPayStatus(2l);//支付中
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            Account bankAcc = new Account();
//            bankAcc.setBankType(add.getPassage());
            bankAcc.setBankType(add.getKhh());
            bankAcc.setBankCard(add.getBankCard());
            bankAcc.setUnitId(0l);
            bankAcc.setName(add.getFr());
            bankAcc.setType((short)3);//3:真实企业账户
            Result<Account> addRtn = accountService.addAccount(bankAcc);
            String msg = "创建交易账号失败";

            if (addRtn.hasError()) {
                throw new ServiceException(msg).setDetailMessage(busDesc+"，"+msg+"："+addRtn.getResult());
            }else if (addRtn.hasTip()) {
                throw new ServiceException(msg).setDetailMessage(busDesc+"，"+msg+"："+addRtn.getResult());
            }else if (addRtn.getRtnData() == null) {
                throw new ServiceException(msg);
            }
            //商户提现
            TranLog backLog = new TranLog();
            backLog.setBusType(6l);
            backLog.setBusItem(5l);
            backLog.setTranNo("WI"+IdUtil.getSnowflakeNextIdStr());
            backLog.setBuisId(add.getId());
            Result<TransactionLog> backRtn = accountService.applyTransfer(vo.getAccId().intValue(), addRtn.getRtnData().getId(),bo.getAmount(), add.getBusNo(), "提现");
            if (backRtn.hasError()) {
                throw new ServiceException(busDesc + "，发送交易申请失败："+backRtn.getResult());
            }else if (backRtn.hasTip()) {
                throw new ServiceException(busDesc + "，发送交易申请失败："+backRtn.getResult());
            }else if (backRtn.getRtnData() == null) {
                throw new ServiceException(busDesc + "，发送交易申请失败");
            }
            backLog.setTranId(backRtn.getRtnData().getId());
            backLog.setAddTime(new Date());
            backLog.setTranResult(backRtn.getRtnData().getResult().intValue());
            backLog.setSourceAccId(backRtn.getRtnData().getSourceAccId().longValue());
            backLog.setSourceAccType(BusRole.MERCHANT.getId());
            backLog.setTargetAccId(backRtn.getRtnData().getTargetAccId().longValue());
            backLog.setTargetAccType(BusRole.MERCHANT.getId());
            backLog.setIsCallback(0);
            tranLogDao.insert(backLog);
        }
        return flag;
    }

    /**
     * 修改商户提现记录
     */
    @Override
    public Boolean updateByBo(BusMerchantCashoutBo bo) {
        BusMerchantCashout update = MapstructUtils.convert(bo, BusMerchantCashout.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMerchantCashout 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 TranLog cashoutResult(TranLogVo tlog, TransactionLog tran) {
        TranLog save = null;
        if (tran.getResult().intValue() == 2 || tran.getResult().intValue() == 3){
            String busDesc = "商户提现";
            BusMerchantCashoutVo vo = baseMapper.selectVoById(tlog.getBuisId());
            if (vo == null) {
                throw new ServiceException(busDesc+"时，提现记录不存在（"+tlog.getBuisId()+"）");
            }
            if(vo.getPayStatus() != 2){
                //非支付中，直接返回
                return null;
            }
            if(merchantAccountService.updateFrozenByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户冻结金额不足（"+tlog.getBuisId()+"）");
            }
            if (tran.getResult().intValue() == 2) {//支付成功
                if(merchantAccountService.updateBalanceByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                    throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户余额不足（"+tlog.getBuisId()+"）");
                }
                if(baseMapper.update(new LambdaUpdateWrapper<BusMerchantCashout>().eq(BusMerchantCashout::getId,vo.getId())
                    .eq(BusMerchantCashout::getPayStatus,2)
                    .set(BusMerchantCashout::getPayStatus,3)
                    .set(BusMerchantCashout::getPayTime,new Date())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                BusMerchantVo merchant = merchantMapper.selectVoById(vo.getMerId());
                BusMerchantFlows merchantFlow = new BusMerchantFlows(2,vo.getMerId(),vo.getSydId(),14, vo.getPassage(), null,tran.getTargetBankNo(), -tran.getAmount(), new Date(),vo.getAddBy(),"提现", null, vo.getId(), null, tlog.getTranNo(), 3, tran.getResult().intValue(), tlog.getSourceAccType(), vo.getMerId(), merchant.getName(), tran.getSourceCard(), tran.getSourceAccId().longValue(), tlog.getTargetAccType(), 0l, merchant.getName(), tran.getTargetCard(), tran.getTargetAccId().longValue(), "", 1, "");
                merchantFlowsMapper.insertAll(Arrays.asList(merchantFlow));
            }else if (tran.getResult().intValue() == 3) {//支付失败
                if(baseMapper.update(new LambdaUpdateWrapper<BusMerchantCashout>().eq(BusMerchantCashout::getId,vo.getId())
                    .eq(BusMerchantCashout::getPayStatus,2)
                    .set(BusMerchantCashout::getPayStatus,4)
                    .set(BusMerchantCashout::getPayTime,new Date())
                    .set(BusMerchantCashout::getPayRemark,tran.getReason())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                save = new TranLog(tlog.getId(),tran.getResult().intValue(),new Date());
            }
        }
        return save;
    }
}
