<?php
namespace app\wendasns\service;


use app\wendasns\service\PwCredit;
use app\wendasns\model\Order;

use wendasns\Wend;
use think\Exception;
use think\helper\Str;

class PwOrder
{
	private $order;
	
    public function __construct()
    {

    }

	public function save()
	{
    	$data = [
    		'user_id' => $this->user_id,
    		'other_id' => $this->other_id,
    		'order_no' => $this->orderNo(),
    		'subject' => $this->title,
    		'type' => $this->type,
    		'paymode' => $this->paymode,
    		'total_amount' => $this->amount,
    		'create_time' => Wend::getTime()
    	];
    	$dm = Order::create($data);
    	if(!isset($dm->id)){
    		throw new Exception('订单创建失败');
    	}
    	return $dm;
	}
	
	//获取积分值
	public function getOrderType($type)
	{
        $this->order = Order::find($this->id);
        if(!$this->order){
			throw new Exception('订单不存在');
		}
		switch ($type){
			case 'recharge':
				return $this->recharge();
				break;
			case 'reward':
				return $this->reward();
				break;
			default:
				
		}
	}
	
	//充值
	public function recharge()
	{
		$credit = new PwCredit();
		
		$credit->uid = $this->order->user_id;
		$credit->setInc($this->order->total_amount);
		
		$this->order->pay_time = Wend::getTime();
		$this->order->status = 1;
		$this->order->save();
		return true;
	}
	
	//打赏
	public function reward()
	{
		$total_amount = abs($this->order->total_amount);
		$credit = new PwCredit();
		$credit->uid = $this->order->other_id;//收款人
		$credit->setInc($total_amount);
		$time = Wend::getTime();
		$data = [
			'user_id' => $this->order->other_id,
			'other_id' => $this->order->user_id,
    		'order_no' => $this->orderNo(),
    		'subject' => '被打赏',
    		'type' => 'reward',
    		'paymode' => $this->order->paymode,
    		'total_amount' => $total_amount,
    		'create_time' => $time,
    		'pay_time' => $time,
    		'status' => 1
    	];
    	$dm = Order::create($data);
    	
    	$this->order->pay_time = $time;
    	$this->order->status = 1;
    	$this->order->save();
    	return $dm;
	}
	
    private function orderNo()
    {
    	$ms = sprintf("%03d", rand(0,99));
    	$order_no = date('YmdHis',Wend::getTime()).$ms.Str::random(8);
    	return $order_no;
    }
}