<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\AppInfoModel;
use App\Models\Merchant;
use App\Models\MemberMerchant;
use App\Models\UserBanks;
use App\Models\Setting;

use App\Models\WxUserInfoModel;
use Illuminate\Http\Request;
//use App\Http\HelperTraits\AttachmentHelper;
use App\Services\Base\ErrorCode;
use App\User;
use Illuminate\Support\Facades\Hash;
use Validator, Auth, Cache;

class AuthController extends Controller
{

    private $expireTime     = 1;
    private $keySmsCode     = 'auth:sms:';
    private $keySmsCodeExist     = 'auth:sms:exist';
    private $expireTimeExist     = 24*60;

    public function test(){
//        return $this->error(ErrorCode::SAVE_USER_FAILED);
        return $this->api(['test' => 'test']);
    }
    public function shop2(){

        return '{"code":0,"msg":"success","data":{"store_name":"商城最新版","contact_tel":"18268343615","show_customer_service":1,"share_setting":{"id":"1","first":"10.00","second":"5.00","third":"0.00","store_id":"1","level":"2","condition":"0","share_condition":"1","content":"成为分销商，推广平台任意商品都有高额提成！","pay_type":"1","min_money":"1.00","agree":"申请成为分销商，务必要填写真实的姓名和电话，否则一律不通过！","first_name":"白金","second_name":"白银","third_name":"","pic_url_1":"http:\/\/www.xkedou.cn\/addons\/hjmall\/core\/web\/uploads\/image\/82\/8285e1e45c4ce7bf4e4433326c9e16ee.png","pic_url_2":"http:\/\/www.xkedou.cn\/addons\/hjmall\/core\/web\/uploads\/image\/72\/727a6d8c05ca1feb26ab179fd34bf512.png","qrcode_bg":"http:\/\/www.xkedou.cn\/addons\/hjmall\/core\/web\/statics\/images\/2.png"},"store":{"id":1,"name":"商城最新版","copyright":"提供技术支持","copyright_pic_url":"http:\/\/www.xkedou.cn\/addons\/hjmall\/core\/web\/uploads\/image\/af\/af3d4d7641bafd696d28adef6a635e2d.png","copyright_url":"\/pages\/article-detail\/article-detail?id=about_us","contact_tel":"18268343615","show_customer_service":1,"cat_style":4,"address":"","is_offline":1,"is_coupon":1}}}';
    }
    /**
     * @api {post} /api/auth/login 微信登陆入口（login）
     * @apiDescription 微信登陆入口(login)
     * @apiGroup Auth
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  code   登录凭证
     * @apiParam {string}  nickname   微信昵称
     * @apiParam {string}  avatar   微信头像
     * @apiParam {string}  appid   appid
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "state": true,
     *     "code": 0,
     *     "message": "",
     *     "data": {
     *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
     *         "user": {
     *             "id": 1,
     *             "name": "15888888888",
     *             "email": "abcdefg@gmail.com",
     *             "phone": "15888888888",
     *             "avatar": null,
     *             "last_ip": null,
     *             "created_at": "2016-09-30 00:45:13",
     *             "updated_at": "2016-09-29 16:43:36"
     *         }
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     *    1102    INCORRECT_USER_OR_PASS          用户名或密码不正确
     */
    public function login(Request $request) {

        $validator = Validator::make($request->all(),
            [
                'code'         => 'required',
                'nickname'         => 'required',
                'avatar'         => 'required',
                'appid'         => 'required',
            ],
            [
                'code.required'        => '登录凭证不存在',
                'nickname.required'        => '微信昵称不存在',
                'avatar.required'        => '微信头像不存在',
                'appid.required'        => 'appid不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $js_code = $request->input('code');
        $nickname = $request->input('nickname');
        $avatar = $request->input('avatar');
        $appid = $request->input('appid');
        \Log::info('js_code:'.$js_code.' avatar:'.$avatar.' nickname:'.$nickname);
        $info =AppInfoModel::where('appid',$appid)->first();
        if(empty($info)) return $this->error(ErrorCode::APPID_NOT_EXIST);
        $secret = $info->appsecret;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$js_code."&grant_type=authorization_code";
        $weixin = file_get_contents($url);     //file_get_contents获取指定路由返回的数据
        $array = json_decode($weixin,true); //对JSON格式的字符串进行编码
//        $array = get_object_vars($jsondecode);//转换成数组
        if (!isset($array['openid'])) {
            \Log::info($url);
            \Log::info($array);
            return $this->error(102, '服务器错误');
        }
        $openid = $array['openid'];//输出openid

        $user = WxUserInfoModel::where('openid', $openid)->first();
        if (!$user) {
            //注册
            $data['appid'] = $appid;
            $data['openid'] = $openid;
            $data['nickname'] = $nickname;
            $data['avatar'] = $avatar;
            $res = WxUserInfoModel::create($data);
            if (!$res) return $this->error(1000, 'error');
            $user = $res;
        }
        \Log::info($user);
        $token = $user->createToken("user_".$user->id)->accessToken;
        return $this->api(compact('user', 'token'));
    }





}
