<?php

namespace App\Http\Controllers\Sys;

use App\Http\Appadapter\Adapter;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use \App\Http\Models;
use Illuminate\Support\Facades\DB;
use \Exception;

/**
 * 第三方管理类
 */
class AppController extends Controller
{

    /**
     * 构造函数
     *
     * @access public
     * @param mixed $req 数据传输
     * @return array JsonString
     */
    public function __construct() {

    }

    /**
     * 接收app发来的下线通知
     */
    public function loginOut(Request $req){
        $input =  $req->input();

        if(!isset($input['money']) || !preg_match('/^[0-9]{1,8}(.[0-9]{1,2})?$/', $input['money'])){
            $arr['msg'] = '请传入正确的金额';
            return $arr;
        }

        $money = $req->input('money');
        $appUsername = $req->input('username');

        $appUserModel = new Models\AppUser();
        $appUserInfo = $appUserModel->where('app_username',$appUsername)->first();

        $mathches = array();
        preg_match('/^t(\d+)_(\w+\W+)_a(\d+)$/', $appUsername, $mathches);
        $partyId = $mathches[1];
        $appId = $mathches[3];
        $partyUserName = $mathches[2];

        $appModel = new Models\App;
        $appInfo = $appModel->where('id', $appId)->first();

        DB::beginTransaction();
        //更新额度
        /*$result = $partyModel->where('id', $partyInfo['id'])->update(array(
            'balance' => $partyInfo['balance'] - $money
        ));
        if($result === false){
            $appUserModel->rollBack();
            return toJson(-4, '系统繁忙', []);
        }*/


        //更新额度

        $result = $appModel->where('id', $appId)->update(array(
            'balance' => $appInfo['balance'] - $money
        ));
        if($result === false){
            DB::rollBack();
            return toJson(-4, '系统繁忙', []);
        }

        //记录日志
        $result = $balanceLogModel = new Models\BalanceLog();
        $balanceLogModel->insert([
            'type' => 2,
            'money' => $money,
            'app_id' => $appInfo['id'],
            'app_username' => $appUsername,
            'party_id' =>$partyId,
            'party_username' => $partyUserName,
            //'ctime' =>now()
        ]);
        if($result === false){
            $appUserModel->rollBack();
            return toJson(-4, '系统繁忙', []);
        }

        DB::commit();

        //TODO 调用第三方平台推出接口，更新第三方额度

    }


}
