package org.dromara.payment.operator.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.payment.bill.service.IMerBillService;
import org.dromara.payment.channel.domain.BusChannel;
import org.dromara.payment.channel.domain.BusChannelAccount;
import org.dromara.payment.channel.domain.BusChannelCashout;
import org.dromara.payment.channel.domain.vo.BusChannelAccountVo;
import org.dromara.payment.channel.domain.vo.BusChannelCashoutVo;
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.operator.domain.BusOperator;
import org.dromara.payment.operator.domain.BusOperatorAccount;
import org.dromara.payment.operator.domain.BusOperatorFlows;
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.BusOperatorFlowsMapper;
import org.dromara.payment.operator.mapper.BusOperatorMapper;
import org.dromara.payment.operator.service.IBusOperatorAccountService;
import org.dromara.payment.sys.domain.SysSydCashout;
import org.dromara.payment.sys.domain.SysSydFlows;
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.operator.domain.bo.BusOperatorCashoutBo;
import org.dromara.payment.operator.domain.vo.BusOperatorCashoutVo;
import org.dromara.payment.operator.domain.BusOperatorCashout;
import org.dromara.payment.operator.mapper.BusOperatorCashoutMapper;
import org.dromara.payment.operator.service.IBusOperatorCashoutService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 运营商提现记录Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-28
 */
@RequiredArgsConstructor
@Service
public class BusOperatorCashoutServiceImpl implements IBusOperatorCashoutService {

    private final BusOperatorCashoutMapper baseMapper;

    private final IBusOperatorAccountService operatorAccountService;

    private final BusOperatorAccountMapper operatorAccountMapper;

    private final BusOperatorMapper operatorMapper;

    private final BusOperatorFlowsMapper operatorFlowsMapper;

    private final IMerBillService billService;

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

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

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

    /**
     * 查询运营商提现记录列表
     */
    @Override
    public TableDataInfo<BusOperatorCashoutVo> queryPageList(BusOperatorCashoutBo bo, PageQuery pageQuery) {
        QueryWrapper<BusOperatorCashout> lqw = buildQueryWrapper(bo);
        Page<BusOperatorCashoutVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询运营商提现记录列表
     */
    @Override
    public List<BusOperatorCashoutVo> queryList(BusOperatorCashoutBo bo) {
        QueryWrapper<BusOperatorCashout> lqw = buildQueryWrapper(bo);
        return baseMapper.queryList(lqw);
    }

    private QueryWrapper<BusOperatorCashout> buildQueryWrapper(BusOperatorCashoutBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<BusOperatorCashout> lqw = new QueryWrapper<>();
        lqw.eq(bo.getSydId() != null, "t.syd_id", bo.getSydId());
        lqw.eq(bo.getOpId() != null, "t.op_id", bo.getOpId());
        lqw.eq(bo.getAccId() != null, "t.acc_id", bo.getAccId());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCard()), "t.bank_card", bo.getBankCard());
        lqw.eq(bo.getVerifyStatus() != null, "t.verify_status", bo.getVerifyStatus());
        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(bo.getParams().get("op_name"))){
            lqw.like("t1.name",bo.getParams().get("op_name"));
        }

        lqw.orderByDesc("t.add_time");
        return lqw;
    }

    /**
     * 新增运营商提现记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BusOperatorCashoutBo bo) {
        BusOperatorCashout add = MapstructUtils.convert(bo, BusOperatorCashout.class);
        validEntityBeforeSave(add);
        BusOperatorAccountVo vo = operatorAccountService.getCashoutAccount(bo.getAccId());
        if(vo == null){
            throw new ServiceException("资金账户不存在，提现失败");
        }
        if(vo.getBalance() - vo.getFrozen() < bo.getAmount()){
            throw new ServiceException("资金账户可用余额不足，提现失败");
        }
        BusOperator operator = operatorMapper.selectOne(new LambdaQueryWrapper<BusOperator>().eq(BusOperator::getId,vo.getOpId()));
        billService.checkPayPassword(BusRole.OPERATOR, vo.getOpId(), () -> {
            if(StringUtils.isBlank(operator.getPayPassword())){
                throw new ServiceException("请前往系统管理进行支付密码重置！");
            }
            return !bo.getPassword().equals(operator.getPayPassword());
        });
        String busDesc = "运营商提现";
        if(operatorAccountService.updateFrozenByAccId(vo.getAccId().intValue(),bo.getAmount()) == 0){
            throw new ServiceException(busDesc+"时，"+vo.getBankType()+"账户可用余额不足");
        }
        add.setSydId(vo.getSydId());
        add.setOpId(vo.getOpId());
        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());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean verifyCashout(BusOperatorCashoutBo bo) {
        BusOperatorCashoutVo vo = baseMapper.selectVoById(bo.getId());
        BusOperatorAccountVo  boavo = this.operatorAccountService.getCashoutAccount(vo.getAccId());
        if(vo == null){
            throw new ServiceException("提现申请不存在，审核失败");
        }
        if(vo.getVerifyStatus() != 0){
            throw new ServiceException("提现申请已审核");
        }
        BusOperatorCashout update = MapstructUtils.convert(bo, BusOperatorCashout.class);
        update.setVerifyTime(new Date());
        String busDesc = "运营商提现";
        if(update.getVerifyStatus() == 1){//驳回
            if(baseMapper.update(update,new LambdaQueryWrapper<BusOperatorCashout>().eq(BusOperatorCashout::getId,bo.getId())
                .eq(BusOperatorCashout::getVerifyStatus,0)) == 0){
                throw new ServiceException("提现申请已审核");
            }
            if(operatorAccountService.updateFrozenByAccId(vo.getAccId().intValue(),-bo.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户可用余额不足");
            }
        }else if(update.getVerifyStatus() == 2){//审批通过
            update.setPayStatus(2l);//支付中
            if(baseMapper.update(update,new LambdaQueryWrapper<BusOperatorCashout>().eq(BusOperatorCashout::getId,bo.getId())
                .eq(BusOperatorCashout::getVerifyStatus,0)) == 0){
                throw new ServiceException("提现申请已审核");
            }

            Account bankAcc = new Account();
            bankAcc.setBankType(vo.getKhh());
            bankAcc.setBankCard(vo.getBankCard());
            bankAcc.setUnitId(0l);
            bankAcc.setName(vo.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(4l);
            backLog.setBusItem(5l);
            backLog.setTranNo("WI"+IdUtil.getSnowflakeNextIdStr());
            backLog.setBuisId(vo.getId());
            Result<TransactionLog> backRtn = accountService.applyTransfer(boavo.getAccId().intValue(), addRtn.getRtnData().getId(),vo.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.OPERATOR.getId());
            backLog.setIsCallback(0);
            tranLogDao.insert(backLog);
            operatorAccountMapper.updateCashoutingByAccId(backRtn.getRtnData().getSourceAccId(),backRtn.getRtnData().getAmount());
        }
        return true;
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusOperatorCashout 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 = "运营商提现";
            BusOperatorCashoutVo vo = baseMapper.selectVoById(tlog.getBuisId());
            if (vo == null) {
                throw new ServiceException(busDesc+"时，提现记录不存在（"+tlog.getBuisId()+"）");
            }
            if(vo.getPayStatus() != 2){
                //非支付中，直接返回
                return null;
            }
            if(operatorAccountService.updateFrozenByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户冻结金额不足（"+tlog.getBuisId()+"）");
            }
            if (tran.getResult().intValue() == 2) {//支付成功
                if(operatorAccountService.updateBalanceByAccId(tran.getSourceAccId(),-tran.getAmount()) == 0){
                    throw new ServiceException(busDesc+"时，"+vo.getPassage()+"账户余额不足（"+tlog.getBuisId()+"）");
                }
                if(baseMapper.update(new LambdaUpdateWrapper<BusOperatorCashout>().eq(BusOperatorCashout::getId,vo.getId())
                    .eq(BusOperatorCashout::getPayStatus,2)
                    .set(BusOperatorCashout::getPayStatus,3)
                    .set(BusOperatorCashout::getPayTime,new Date())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                operatorAccountMapper.updateCashoutByAccId(tran.getSourceAccId(),tran.getAmount());
                BusOperatorVo op = operatorMapper.selectVoById(vo.getOpId());
                BusOperatorFlows flow = new BusOperatorFlows(2,vo.getOpId(),16,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(),op.getName(),tran.getSourceCard(), tran.getSourceAccId().longValue(),tlog.getTargetAccType(), 0l, tran.getTargetAccName(), tran.getTargetCard(), tran.getTargetAccId().longValue(),"",1);
                operatorFlowsMapper.insertSelective(flow);
            }else if (tran.getResult().intValue() == 3) {//支付失败
                if(baseMapper.update(new LambdaUpdateWrapper<BusOperatorCashout>().eq(BusOperatorCashout::getId,vo.getId())
                    .eq(BusOperatorCashout::getPayStatus,2)
                    .set(BusOperatorCashout::getPayStatus,4)
                    .set(BusOperatorCashout::getPayTime,new Date())
                    .set(BusOperatorCashout::getPayRemark,tran.getReason())
                ) == 0){
                    throw new ServiceException(busDesc+"时，重复处理提现结果（"+tlog.getBuisId()+"）");
                }
                save = new TranLog(tlog.getId(),tran.getResult().intValue(),new Date());
            }
        }
        return save;
    }
}
