<?php

namespace App\Http\Controllers\Api;

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 PartyController extends Controller
{

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

    }


    /**
     * 第三方账号登陆、注册
     *
     * @access public
     * @param mixed $req 数据传输
     * @return array JsonString
     */
    public function login(Request $req)
    {
        $code = -200;
        $msg = '操作失败';
        try {
            $check = $this->checkLoginArg($req);
            if($check['code'] != 1){
                return toJson($check['code'], $check['msg'], []);
            }

            $partyModel = new Models\Party;
            $key = $req->input('key');
            $appid = $req->input('appid');
            $partyUserName = $req->input('username');
            //$partyInfo = \App\Models\Party::where('key', $key)->first();
            $partyInfo = $partyModel->where('key', $key)->first();

            $money = $req->input('money');
            if($partyInfo['balance'] < $money){
                return toJson(-100, '您的余额不足', []);
            }

            $appModel = new Models\App;
            $appInfo = $appModel->where('id', $appid)->first();
            if($appInfo['balance'] < $money){
                return toJson(-101, '系统繁忙，请稍后重试', []); //我的余额不足
            }

            //查询该用户是否已在系统
            $partyUserModel = new Models\PartyUser();
            $partyUserInfo = $partyUserModel->where([
                ['party_id', '=', $partyInfo['id']],
                ['party_username', '=', $partyUserName],
            ])->first();
            if(empty($partyUserInfo)){
                $partyUserModel->insert([
                    'party_id' => $partyInfo['id'],
                    'party_username' => $partyUserName,
                    'password' => $req->input('password'),
                    'login_time' => now(),
                    'login_ip' => $this->get_real_ip(),
                    //'ctime' =>now()
                ]);
            }else{
                $partyUserModel->where('id', $partyUserInfo['id'])->update([
                    'login_time' => now(),
                    'login_ip' => $this->get_real_ip(),
                ]);
            }

            $adapter = new Adapter();
            //查询是否已创建对于应用的用户
            $appUserModel = new Models\AppUser();
            $appUsername = $this->buildAppUsername($partyInfo['id'], $partyUserName, $appid);
            $appUserInfo = $appUserModel->where('app_username',$appUsername)->first();
            if(empty($appUserInfo)){
                $result = $adapter->syncUser($appid, $appUsername, $req->input('password')); //检测用户并创建用户
                if($result['code'] != 1){
                    return toJson(-2, $result['msg'], []);
                }

                $appUserModel->insert([
                    'app_id' => $appInfo['id'],
                    'party_username' => $partyUserName,
                    'app_username' => $appUsername,
                    'password' => $req->input('password'),
                    'login_time' => now(),
                    'login_ip' => $this->get_real_ip(),
                    //'ctime' =>now()
                ]);
            }else{
                $appUserModel->where('id', $appUserInfo['id'])->update([
                    'login_time' => now(),
                    'login_ip' => $this->get_real_ip(),
                ]);
            }

            //调用内容方的登陆接口
            $result = $adapter->login($appid, $appUsername, $req->input('password'), $money);
            if($result['code'] != 1){
                return toJson(-3, $result['msg'], []);
            }

            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', $appInfo['id'])->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' =>$partyInfo['id'],
                'party_username' => $partyUserName,
                //'ctime' =>now()
            ]);
            if($result === false){
                $appUserModel->rollBack();
                return toJson(-4, '系统繁忙', []);
            }

            DB::commit();

            $msg = '成功';
            $code = 1;

            return toJson($code, $msg, []);
        } catch (Exception $e) {
            var_dump($e);die;
            return toJson($code, $msg, []);
        }

    }//end login()

    /**
     * 组装内容用户名称
     * @param $partyId
     * @param $partyUsername
     * @param $appid
     * @return string
     */
    public function buildAppUsername($partyId, $partyUsername, $appid){
        return 't'.$partyId.'_'.$partyUsername.'_a'.$appid;
    }

    private function checkLoginArg($req){
        $arr = array('code'=>-100, 'msg'=>'');
        if(empty($req->input('username'))){
            $arr['msg'] = '请输入用户名';
            return $arr;
        }
        if(empty($req->input('password'))){
            $arr['msg'] = '请输入密码';
            return $arr;
        }
        if(empty($req->input('appid'))){
            $arr['msg'] = '请输如appid';
            return $arr;
        }
        if(!preg_match('/^[0-9]{1,8}(.[0-9]{1,2})?$/', $req->input('money'))){
            $arr['msg'] = '请输入正确的金额';
            return $arr;
        }

        $arr['code'] = 1;
        return $arr;
    }


}
