<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2019/3/6
 * Time: 10:17
 */

namespace App\Http\Controllers\Web;

use App\Models\AlbumAgentModel;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumUserModel;
use Illuminate\Http\Request;
use EasyWeChat\Factory;

class AuthController extends Controller
{
    public function bind(Request $request)
    {
        if ($request->isMethod('post')) {
            $store_id = $request->input('store_id');
            $phone = $request->input('phone');
            $name = $request->input('name');
            if (!$phone || !$name) {
                $message = '请输入电话号码';
                return view('web.auth.error', compact('message'));
            } else {
                $check = AlbumUserModel::where([['phone', $phone],['g_open_id', null],['is_dealer', 1]])->first();
                if (!$check) {
                    $message = '该经销商号码不存在或是已绑定';
                    return view('web.auth.error', compact('message'));
                }

            }
            $weChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();
            $config = [
                'app_id' => $weChatApp->G_app_id,
                'secret' => $weChatApp->G_app_secret,
                'response_type' => 'array',
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => '/web/notify?store_id=' . $store_id . "&name=$name&phone=$phone",
                ]

            ];
            $app = Factory::officialAccount($config);
            $response = $app->oauth
                ->redirect();
            return $response;
        } else {
            return view('web.auth.bind');
        }
    }
    public function notify(Request $request)
    {
        $store_id = $request->input('store_id');
        $phone = $request->input('phone');
        $name = $request->input('name');
        $weChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $config = [
            'app_id' => $weChatApp->G_app_id,
            'secret' => $weChatApp->G_app_secret,
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/web/notify',
            ]
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user()->toArray();
        $check_user = AlbumUserModel::where([['store_id',$store_id],['wechat_union_id',$user['original']['unionid']]])->first();
        $agent = AlbumAgentModel::where([['store_id', $store_id],['user_id', $check_user->id]])->first();
        $agent->name = $name;
        $agent->save();
        $check_user->g_open_id = $user['id'];
        $check_user->phone = $phone;
        $check_user->save();

        return view('web.auth.success');
    }

    public function notifyAccount(Request $request)
    {
        $store_id = $request->input('store_id');
        $config = [
            'app_id' => 'wxbce144ca3da7aa23',
            'secret' => '4d97eba675deeea187e1ebc32c1399da',
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);
        if (isset($_GET["echostr"])) {
            $echoStr = $_GET["echostr"];
            //对接规则
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $token = 'bshbdajdbjadwedwqer';
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                echo $echoStr;
            } else {
                echo "";
                exit;
            }
        } else {
            $postStr = file_get_contents("php://input");
            if (!empty($postStr)) {
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $MsgT = $postObj->MsgType;
                $time = time();
                //如果用户发的text类型
                if ($MsgT == "text") {
                    $key = trim($postObj->Content);
                    $fromUsername = $postObj->FromUserName;
                    $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                    $msgType = "text";
                    if ($key == '绑定') {
                        $user = $app->user->get($fromUsername);
                        $check_user = AlbumUserModel::where([['store_id',$store_id],['wechat_union_id',$user['unionid']]])->first();
                        if ($check_user) {
                            $check_user->g_open_id = $user['id'];
                            $res = $check_user->save();
                        } else {
                            $data['username'] = $user['nickname'];
                            $data['wechat_union_id'] = $user['unionid'];
                            $data['avatar'] = $user['headimgurl'];
                            $data['g_open_id'] = $fromUsername;
                            $data['store_id'] = $store_id;
                            $data['is_dealer'] = 0;
                            $data['role'] = 0;
                            $data['model'] = 0;
                            $data['up_agent_id'] = 0;
                            $res = AlbumUserModel::create($data);
                        }
                        if ($res) {
                            $contentStr = "绑定成功";
                        } else {
                            $contentStr = "绑定失败";
                        }
                    } else {
                        $contentStr = "回复 绑定 即可绑定用户";
                    }

                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    exit;
                }

                //如果用户发的event（事件）类型
                if ($MsgT == "event") {
                    $Event = $postObj->Event;
                    if ($Event == 'subscribe') {
                        $contentStr = "欢迎关注，回复 绑定 即可绑定用户";
                    } else {
                        $contentStr = "希望您下次关注，但您收不到此条消息了";
                    }

                    $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                    $Title = $postObj->Title;
                    $Description = $postObj->Description;
                    $Url = $postObj->Url;
                    $msgType = 'text';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    exit;
                }
            } else {
                echo "";
                exit;
            }
        }
    }

    public function welcome()
    {
        return view('welcome');
    }
}