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

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
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.common.redis.utils.RedisUtils;
import org.dromara.payment.bill.domain.MerBillDetail;
import org.dromara.payment.bill.domain.vo.MerBillDetailVo;
import org.dromara.payment.bill.domain.vo.MerBillVo;
import org.dromara.payment.bill.service.IMerBillService;
import org.dromara.payment.channel.domain.BusChannel;
import org.dromara.payment.channel.domain.BusChannelAccount;
import org.dromara.payment.channel.domain.BusChannelFlows;
import org.dromara.payment.common.domain.BusOperLog;
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.enums.BusLogType;
import org.dromara.payment.merchant.domain.BusMerchant;
import org.dromara.payment.merchant.domain.BusMerchantAccount;
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.BusMerchantAccountMapper;
import org.dromara.payment.operator.domain.BusOperatorFlows;
import org.dromara.payment.operator.domain.vo.BusOperatorVo;
import org.dromara.payment.sys.domain.SysSydAccount;
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.payment.sys.mapper.SysSydAccountMapper;
import org.dromara.payment.sys.mapper.SysSydFlowsMapper;
import org.dromara.payment.sys.mapper.SysSydMapper;
import org.dromara.payment.sys.service.ISysSydAccountService;
import org.dromara.payment.task.domain.MerTaskEnroll;
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.sys.domain.bo.SysSydCashoutBo;
import org.dromara.payment.sys.domain.SysSydCashout;
import org.dromara.payment.sys.mapper.SysSydCashoutMapper;
import org.dromara.payment.sys.service.ISysSydCashoutService;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.*;
import java.util.function.Supplier;

/**
 * 服务商提现记录Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-26
 */
@RequiredArgsConstructor
@Service
public class SysSydCashoutServiceImpl implements ISysSydCashoutService {

    private final SysSydCashoutMapper baseMapper;

    private final SysSydAccountMapper sydAccountMapper;

    private final ISysSydAccountService sydAccountService;

    private final SysSydFlowsMapper sydFlowsMapper;

    private final SysSydMapper sydMapper;

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

    private final IMerBillService billService;

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

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

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

    /**
     * 查询服务商提现记录列表
     */
    @Override
    public List<SysSydCashoutVo> queryList(SysSydCashoutBo bo) {
        LambdaQueryWrapper<SysSydCashout> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增服务商提现记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysSydCashoutBo bo) {
        SysSydCashout add = MapstructUtils.convert(bo, SysSydCashout.class);
        validEntityBeforeSave(add);
        SysSydAccountVo vo = sydAccountService.getCashoutAccount(bo.getAccId());
        if(vo == null){
            throw new ServiceException("资金账户不存在，提现失败");
        }
        if(vo.getBalance() - vo.getFrozen() < bo.getAmount()){
            throw new ServiceException("资金账户可用余额不足，提现失败");
        }
        billService.checkPayPassword(BusRole.SERVICE, vo.getSydId(), () -> {
            SysSydVo syd = sydMapper.selectVoById(vo.getSydId());
            if(StringUtils.isBlank(syd.getPayPassword())){
                throw new ServiceException("请前往系统管理进行支付密码重置！");
            }
            return !bo.getPassword().equals(syd.getPayPassword());
        });
        String busDesc = "服务商提现";
        if(sydAccountService.updateFrozenByAccId(vo.getAccId().intValue(),bo.getAmount()) == 0){
            throw new ServiceException(busDesc+"时，"+vo.getBankType()+"账户可用余额不足");
        }
        add.setSydId(vo.getSydId());
        add.setKhd(vo.getKfd());
        add.setKhh(vo.getKfh());
        add.setKhhNo(vo.getKhhNo());
        add.setFr(vo.getAccName());
        add.setBankCard(vo.getBankCard());
        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.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(5l);
            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.SERVICE.getId());
            backLog.setTargetAccId(backRtn.getRtnData().getTargetAccId().longValue());
            backLog.setTargetAccType(BusRole.SERVICE.getId());
            backLog.setIsCallback(0);
            tranLogDao.insert(backLog);
        }
        return flag;
    }

    @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 = "服务商提现";
            SysSydCashoutVo vo = baseMapper.selectVoById(tlog.getBuisId());
            if (vo == null) {
                throw new ServiceException(busDesc+"时，提现记录不存在（"+tlog.getBuisId()+"）");
            }
            if(vo.getPayStatus() != 2){
                //非支付中，直接返回
                return null;
            }
            if(sydAccountService.updateFrozenByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户冻结金额不足（"+tlog.getBuisId()+"）");
            }
            if (tran.getResult().intValue() == 2) {//支付成功
                if(sydAccountService.updateBalanceByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                    throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户余额不足（"+tlog.getBuisId()+"）");
                }
                if(baseMapper.update(new LambdaUpdateWrapper<SysSydCashout>().eq(SysSydCashout::getId,vo.getId())
                        .eq(SysSydCashout::getPayStatus,2)
                        .set(SysSydCashout::getPayStatus,3)
                        .set(SysSydCashout::getPayTime,new Date())
                    ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                SysSydVo syd = sydMapper.selectVoById(vo.getSydId());
                SysSydFlows sydFlow = new SysSydFlows(2,vo.getSydId(),13, vo.getPassage(), null,tran.getTargetBankNo(), -tran.getAmount(), new Date(),vo.getAddBy(),"提现", null, vo.getId(), null, tlog.getTranNo(), 3, tran.getResult().intValue(), tlog.getSourceAccType(), vo.getSydId(), syd.getGsmc(), tran.getSourceCard(), tran.getSourceAccId().longValue(), tlog.getTargetAccType(), 0l, tran.getTargetAccName(), tran.getTargetCard(), tran.getTargetAccId().longValue(), "", 1);
                sydFlowsMapper.insertSelective(sydFlow);
            }else if (tran.getResult().intValue() == 3) {//支付失败
                if(baseMapper.update(new LambdaUpdateWrapper<SysSydCashout>().eq(SysSydCashout::getId,vo.getId())
                    .eq(SysSydCashout::getPayStatus,2)
                    .set(SysSydCashout::getPayStatus,4)
                    .set(SysSydCashout::getPayTime,new Date())
                    .set(SysSydCashout::getPayRemark,tran.getReason())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                save = new TranLog(tlog.getId(),tran.getResult().intValue(),new Date());
            }
        }
        return save;
    }

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

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

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