<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\wendasns\controller;

use app\wendasns\WenBaseController;
use app\wendasns\service\PwOrder;
use app\wendasns\service\PwWallet;

class Reward extends WenBaseController
{
    //打赏
    public function index()
    {
    	//event('Payment');
    	$id = input('post.id',0,'intval');
    	$type = input('post.type','answer','ucfirst');
    	$paymode = input('post.paymode','');
    	$amount = input('post.amount',0,'intval');
    	$message = input('post.message','');

        try {
            validate(\app\wendasns\validate\Payment::class)->check([
                'paymode'  => $paymode,
                'amount' => $amount,
            ]);
        } catch (\think\exception\ValidateException $e) {
            error($e->getError());
        }
        
        
        if($paymode=='wallet' && !$this->loginUser->isLogin){
        	//error('请先登录账号');
        }
        
    	$className = '\\app\\wendasns\\model\\'.$type;
    	$dm = $className::find($id);
    	if(!$dm || !isset($dm->users->id)){
    		error('帖子不存在或用户不存在');
    	}
    	
    	try {
    		$order = new PwOrder();
    		$order->user_id = 107;//$this->loginUser->uid;
    		$order->other_id = $dm->user_id;
    		$order->title = '打赏';
    		$order->type = 'reward';
    		$order->paymode = $paymode;
    		$order->amount = $amount * -1;
    		$result = $order->save();
    		
    		$paymethod = config('paymode');
    		
    		$onlypay = new $paymethod[$paymode];
    		$onlypay->trade($result);
    		
    	} catch (\think\Exception $e) {
    		error($e->getMessage());
    	}
    	//event('Payment', $onlypay->toArray());
        return redirect($onlypay->getUrl());
    }
    
    public function success()
    {
    	return '打赏成功';
    }
}