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

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.satoken.utils.LoginHelper;
import org.dromara.payment.bill.service.IMerBillService;
import org.dromara.payment.channel.domain.BusChannel;
import org.dromara.payment.channel.domain.BusChannelFlows;
import org.dromara.payment.channel.domain.vo.BusChannelAccountVo;
import org.dromara.payment.channel.domain.vo.BusChannelVo;
import org.dromara.payment.channel.mapper.BusChannelAccountMapper;
import org.dromara.payment.channel.mapper.BusChannelFlowsMapper;
import org.dromara.payment.channel.mapper.BusChannelMapper;
import org.dromara.payment.channel.service.IBusChannelAccountService;
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.BusMerchantCashout;
import org.dromara.payment.merchant.domain.BusMerchantFlows;
import org.dromara.payment.merchant.domain.vo.BusMerchantAccountVo;
import org.dromara.payment.merchant.domain.vo.BusMerchantCashoutVo;
import org.dromara.payment.merchant.domain.vo.BusMerchantVo;
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.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.channel.domain.bo.BusChannelCashoutBo;
import org.dromara.payment.channel.domain.vo.BusChannelCashoutVo;
import org.dromara.payment.channel.domain.BusChannelCashout;
import org.dromara.payment.channel.mapper.BusChannelCashoutMapper;
import org.dromara.payment.channel.service.IBusChannelCashoutService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 代理商提现记录Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-10
 */
@RequiredArgsConstructor
@Service
public class BusChannelCashoutServiceImpl implements IBusChannelCashoutService {

    private final BusChannelCashoutMapper baseMapper;

    private final IBusChannelAccountService channelAccountService;

    private final BusChannelAccountMapper channelAccountMapper;

    private final BusChannelMapper channelMapper;

    private final IMerBillService billService;

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

    private final BusOperatorMapper operatorMapper;

    private final BusChannelFlowsMapper channelFlowsMapper;

    private final BusOperatorAccountMapper operatorAccountMapper;

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

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

    /**
     * 查询代理商提现记录列表
     */
    @Override
    public TableDataInfo<BusChannelCashoutVo> queryPageList(BusChannelCashoutBo bo, PageQuery pageQuery) {
        QueryWrapper<BusChannelCashout> lqw = buildQueryWrapper(bo);
        Page<BusChannelCashoutVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询代理商提现记录列表
     */
    @Override
    public List<BusChannelCashoutVo> queryList(BusChannelCashoutBo bo) {
        QueryWrapper<BusChannelCashout> lqw = buildQueryWrapper(bo);
        return baseMapper.queryList(lqw);
    }

    private QueryWrapper<BusChannelCashout> buildQueryWrapper(BusChannelCashoutBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<BusChannelCashout> lqw = new QueryWrapper<>();
        lqw.eq(bo.getSydId() != null, "t.syd_id", bo.getSydId());
        lqw.eq(bo.getChannelId() != null, "t.channel_id", bo.getChannelId());
        lqw.eq(bo.getAccId() != null, "t.acc_id", bo.getAccId());
        lqw.eq(StringUtils.isNotBlank(bo.getBusNo()), "t.bus_no", bo.getBusNo());
        lqw.eq(bo.getAmount() != null, "t.amount", bo.getAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getKhh()), "t.khh", bo.getKhh());
        lqw.eq(StringUtils.isNotBlank(bo.getKhhNo()), "t.khh_no", bo.getKhhNo());
        lqw.eq(StringUtils.isNotBlank(bo.getFr()), "t.fr", bo.getFr());
        lqw.eq(StringUtils.isNotBlank(bo.getKhd()), "t.khd", bo.getKhd());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCard()), "t.bank_card", bo.getBankCard());
        lqw.eq(bo.getVerifyStatus() != null, "t.verify_status", bo.getVerifyStatus());
        lqw.eq(bo.getVerifyTime() != null, "t.verify_time", bo.getVerifyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getVerifyBy()), "t.verify_by", bo.getVerifyBy());
        lqw.eq(StringUtils.isNotBlank(bo.getVerifyReason()), "t.verify_reason", bo.getVerifyReason());
        lqw.eq(StringUtils.isNotBlank(bo.getInvoicePic()), "t.invoice_pic", bo.getInvoicePic());
        lqw.eq(bo.getPayStatus() != null, "t.pay_status", bo.getPayStatus());
        lqw.eq(bo.getPayTime() != null, "t.pay_time", bo.getPayTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPayRemark()), "t.pay_remark", bo.getPayRemark());
        lqw.eq(bo.getAddTime() != null, "t.add_time", bo.getAddTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddBy()), "t.add_by", bo.getAddBy());
        lqw.eq(StringUtils.isNotBlank(bo.getPassage()), "t.passage", bo.getPassage());
        lqw.eq(StringUtils.isNotBlank(bo.getPayReceipt()), "t.pay_receipt", bo.getPayReceipt());
        if(StringUtils.isNotBlank(bo.getParams().get("begin_time")) && StringUtils.isNotBlank(bo.getParams().get("end_time"))){
            lqw.between("t.add_time",bo.getParams().get("begin_time")+" 00:00:00",bo.getParams().get("end_time")+" 23:59:59");
        }
        if(StringUtils.isNotBlank(params.get("channel_no"))){
            lqw.likeRight("t.channel_no",params.get("channel_no"));
        }
        if(StringUtils.isNotBlank(bo.getParams().get("channel_name"))){
            lqw.like("t1.name",bo.getParams().get("channel_name"));
        }

        lqw.orderByDesc("t.add_time");

        return lqw;
    }

    /**
     * 新增代理商提现记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BusChannelCashoutBo bo) {
        BusChannelCashout add = MapstructUtils.convert(bo, BusChannelCashout.class);
        validEntityBeforeSave(add);
        BusChannelAccountVo vo = channelAccountService.getCashoutAccount(bo.getAccId());
        if(vo == null){
            throw new ServiceException("资金账户不存在，提现失败");
        }
        if(vo.getBalance() - vo.getFrozen() < bo.getAmount()){
            throw new ServiceException("资金账户可用余额不足，提现失败");
        }
//        BusChannel channel = channelMapper.selectOne(new LambdaQueryWrapper<BusChannel>().eq(BusChannel::getId,vo.getChannelId()));
//        billService.checkPayPassword(BusRole.AGENT, vo.getChannelId(), () -> {
//            if(StringUtils.isBlank(channel.getPayPassword())){
//                throw new ServiceException("请前往系统管理进行支付密码重置！");
//            }
//            return bo.getPassword().equals(channel.getPayPassword());
//        });
        String busDesc = "代理商提现";
        if(channelAccountService.updateFrozen(vo.getChannelId(),bo.getAmount()) == 0){
            throw new ServiceException(busDesc+"时，"+vo.getBankType()+"账户可用余额不足");
        }
        add.setSydId(vo.getSydId());
        add.setChannelId(vo.getChannelId());
        add.setChannelNo(vo.getChannelNo());
        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());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean verifyCashout(BusChannelCashoutBo bo) {
        BusChannelCashoutVo vo = baseMapper.selectVoById(bo.getId());
        if(vo == null){
            throw new ServiceException("提现申请不存在，审核失败");
        }
        if(vo.getVerifyStatus() != 0){
            throw new ServiceException("提现申请已审核");
        }
        BusChannelCashout update = MapstructUtils.convert(bo, BusChannelCashout.class);
        update.setVerifyTime(new Date());
        String busDesc = "代理商提现";
        if(update.getVerifyStatus() == 1){//驳回
            if(baseMapper.update(update,new LambdaQueryWrapper<BusChannelCashout>().eq(BusChannelCashout::getId,bo.getId())
                .eq(BusChannelCashout::getVerifyStatus,0)) == 0){
                throw new ServiceException("提现申请已审核");
            }
            if(channelAccountService.updateFrozen(vo.getChannelId(),-bo.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户可用余额不足");
            }
        }else if(update.getVerifyStatus() == 2){//审批通过
//            update.setPayStatus(2l);//支付中
            if(baseMapper.update(update,new LambdaQueryWrapper<BusChannelCashout>().eq(BusChannelCashout::getId,bo.getId())
                .eq(BusChannelCashout::getVerifyStatus,0)) == 0){
                throw new ServiceException("提现申请已审核");
            }

            this.cashoutResultOffline(bo);

//            BusChannel channel = channelMapper.selectOne(new LambdaQueryWrapper<BusChannel>().eq(BusChannel::getId,vo.getChannelId()));
//            Account bankAcc = new Account();
//            bankAcc.setBankType(vo.getPassage());
//            bankAcc.setBankCard(vo.getBankCard());
//            bankAcc.setUnitId(0l);
//            bankAcc.setName(vo.getFr());
//            if(channel.getDwType() == 1) {
//                bankAcc.setType((short) 3);//3:真实企业账户
//            }else if(channel.getDwType() == 2){
//                bankAcc.setType((short) 2);//2:真实个人账户
//            }
//            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(3l);
//            backLog.setBusItem(5l);
//            backLog.setTranNo("WI"+IdUtil.getSnowflakeNextIdStr());
//            backLog.setBuisId(vo.getId());
//            BusOperator operator = operatorMapper.selectOne(new LambdaQueryWrapper<BusOperator>().eq(BusOperator::getNo,channel.getOperatorNo()));
//            if(operator == null){
//                throw new ServiceException("运营商不存在，提现失败");
//            }
//            BusOperatorAccountVo opAcc = operatorAccountMapper.selectVoOne(new LambdaQueryWrapper<BusOperatorAccount>()
//                .eq(BusOperatorAccount::getSydId,vo.getSydId())
//                .eq(BusOperatorAccount::getOpId,operator.getId())
//                .eq(BusOperatorAccount::getBankType,vo.getPassage())
//                .eq(BusOperatorAccount::getIsDefault,1));
//            if(opAcc == null){
//                throw new ServiceException("运营商未开通资金账户，提现失败");
//            }
//            Result<TransactionLog> backRtn = accountService.applyTransfer(opAcc.getAccId().intValue(), addRtn.getRtnData().getId(),bo.getAmount(), vo.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.OPERATOR.getId());
//            backLog.setTargetAccId(backRtn.getRtnData().getTargetAccId().longValue());
//            backLog.setTargetAccType(BusRole.AGENT.getId());
//            backLog.setIsCallback(0);
//            tranLogDao.insert(backLog);
        }
        return true;
    }



    @Transactional(rollbackFor = Exception.class)
    public void cashoutResultOffline(BusChannelCashoutBo bo) {
            String busDesc = "代理商提现";
            BusChannelCashoutVo vo = baseMapper.selectVoById(bo.getId());
            if (vo == null) {
                throw new ServiceException(busDesc+"时，提现记录不存在（"+bo.getId()+"）");
            }

            if(channelAccountService.updateFrozen(vo.getChannelId(),-vo.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户冻结金额不足（"+bo.getId()+"）");
            }
                if(channelAccountService.updateBalance(vo.getChannelId(),-vo.getAmount()) == 0){
                    throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户余额不足（"+bo.getId()+"）");
                }
                if(baseMapper.update(new LambdaUpdateWrapper<BusChannelCashout>().eq(BusChannelCashout::getId,vo.getId())
                    .eq(BusChannelCashout::getPayStatus,0)
                    .set(BusChannelCashout::getPayStatus,3)
                    .set(BusChannelCashout::getPayTime,new Date())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+bo.getId()+"）");
                }
                channelAccountMapper.updateCashout(vo.getChannelId(),vo.getAmount());
                BusChannelVo channel = channelMapper.selectVoById(vo.getChannelId());
                BusOperatorVo   operVo = operatorMapper.selectVoById(LoginHelper.getBusId());
                channelFlowsMapper.insertSelective(new BusChannelFlows(2,channel.getId(),15,vo.getBusNo(),-vo.getAmount(),new Date(),vo.getAddBy(),"提现",null,vo.getId(),null,3,BusRole.OPERATOR.getId(),operVo.getId(),operVo.getKhm(),operVo.getBankCard(),0l,BusRole.AGENT.getId(), channel.getId(),channel.getKhm(),vo.getBankCard(),null,""));
    }


    @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 = "代理商提现";
            BusChannelCashoutVo vo = baseMapper.selectVoById(tlog.getBuisId());
            if (vo == null) {
                throw new ServiceException(busDesc+"时，提现记录不存在（"+tlog.getBuisId()+"）");
            }
            if(vo.getPayStatus() != 2){
                //非支付中，直接返回
                return null;
            }
            if(channelAccountService.updateFrozen(vo.getChannelId(),-tran.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户冻结金额不足（"+tlog.getBuisId()+"）");
            }
            if (tran.getResult().intValue() == 2) {//支付成功
                if(channelAccountService.updateBalance(vo.getChannelId(),-tran.getAmount()) == 0){
                    throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户余额不足（"+tlog.getBuisId()+"）");
                }
                if(baseMapper.update(new LambdaUpdateWrapper<BusChannelCashout>().eq(BusChannelCashout::getId,vo.getId())
                    .eq(BusChannelCashout::getPayStatus,2)
                    .set(BusChannelCashout::getPayStatus,3)
                    .set(BusChannelCashout::getPayTime,new Date())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                channelAccountMapper.updateCashout(vo.getChannelId(),tran.getAmount());
                BusChannelVo channel = channelMapper.selectVoById(vo.getChannelId());
                channelFlowsMapper.insertSelective(new BusChannelFlows(2,channel.getId(),15,vo.getBusNo(),-tran.getAmount(),new Date(),vo.getAddBy(),"提现",null,vo.getId(),null,3,BusRole.AGENT.getId(),vo.getChannelId(),channel.getKhm(),tran.getTargetAccName(),0l,BusRole.AGENT.getId(), channel.getId(),channel.getKhm(),tran.getTargetCard(),tran.getTargetAccId().longValue(),""));
            }else if (tran.getResult().intValue() == 3) {//支付失败
                if(baseMapper.update(new LambdaUpdateWrapper<BusChannelCashout>().eq(BusChannelCashout::getId,vo.getId())
                    .eq(BusChannelCashout::getPayStatus,2)
                    .set(BusChannelCashout::getPayStatus,4)
                    .set(BusChannelCashout::getPayTime,new Date())
                    .set(BusChannelCashout::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(BusChannelCashoutBo bo) {
        BusChannelCashout update = MapstructUtils.convert(bo, BusChannelCashout.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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