<?php

namespace App\Http\Controllers\Channel\User;

use Illuminate\Http\Request;
use App\Modules\User\Services\UserService;
use App\Http\Controllers\Channel\BaseController;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use GuzzleHttp\Client;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\Book\Services\BookConfigService;
use Log;
class UserController extends BaseController
{

    protected $secret_key = 'zhuishuyun#_2017';
    /**
     * @apiDefine User 用户
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取用户信息
     * @api {GET} user/userinfo 获取用户信息
     * @apiGroup User
     * @apiName index
     * @apiParam   {Number}  uid 用户ID.
     * @apiSuccess {Number}  id 用户ID.
     * @apiSuccess {String}  openid 微信openid.
     * @apiSuccess {String}  unionid 微信unionid.
     * @apiSuccess {Number}  distribution_channel_id 分销渠道ID.
     * @apiSuccess {String}  province 省份.
     * @apiSuccess {String}  city 城市.
     * @apiSuccess {String}  country 国家.
     * @apiSuccess {String}  headimgurl 头像地址.
     * @apiSuccess {Number}  send_order_id 派单ID.
     * @apiSuccess {Number=0,1}  sex 性别.
     * @apiSuccess {String}  balance 书币余额.
     * @apiSuccess {Int}     is_subscribed 是否关注 -1没关注 0 取关,1已关注.
     * @apiSuccess {String}  subscribed_time 关注时间
     * @apiSuccess {String}  subscribed_src 关注二维码
     * @apiSuccess {String}  subscribe_official 公众号名称
     * @apiSuccess {String}  is_subscribed_text 文本(取关|已关注)
     * @apiSuccess {String}  created_at 书币余额.
     * @apiSuccess {String}  balance 书币余额.
     * @apiSuccess {String}  total_charge 累计余额.
     * @apiSuccess {String}  total_consume 累计消耗.
     * @apiSuccess {String}  total_get 累计获取.
     * @apiSuccess {String}  label 标签
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *                "id": 9,
     *               "openid": "1212",
     *               "unionid": "12312322",
     *               "head_img": "http://www.cmread.com/u/cover_file/3528/413493528/20161228175952/cover180240.jpg",
     *               "distribution_channel_id": 13,
     *               "register_ip": "172.18.0.1",
     *               "send_order_id": 0,
     *               "balance": 88,
     *               "charge_balance": 88,
     *               "reward_balance": 0,
     *               "sex": 0,
     *               "country": "",
     *               "city": "asdf",
     *               "province": "广东",
     *               "created_at": "2017-11-24 20:50:05",
     *               "updated_at": "2017-12-18 22:09:01",
     *               "nickname": "赵六",
     *               "is_new": 0,
     *               "is_subscribed": 1,
     *               "subscribed_time": "2017-12-11 10:02:43",
     *               "subscribe_official": "嘉言小说",
     *               "subscribed_src": false,
     *               "is_subscribed_text": "已关注",
     *               "total_charge": 0,
     *               "total_consume": 123,
     *               "total_get": 456,
     *               "label": "都市爱情",
     *         }
     *     }
     */
    public function index(Request $request){
        $uid = $request->input('uid');
        if(empty($uid)){
            return response()->error('PARAM_EMPTY');
        }
        $channel_id = $this->getChannelId();

        if(empty($channel_id)){
            return response()->error('PARAM_EMPTY');
        }

        $data = UserService::getById($uid);
        if(!$data){
            return response()->error('USER_NOT_FOUND');
        }
        if($data->distribution_channel_id != $channel_id){
            return response()->error('USER_NOT_FOUND');
        }
        //关注
        $forceSubscribe = ForceSubscribeService::forceSubscribeUsersByUidIncludeCancel(['uid'=>$uid]);
        if($forceSubscribe){
            $data->is_subscribed = $forceSubscribe->is_subscribed;
            $data->subscribed_time = date('Y-m-d H:i:s',strtotime($forceSubscribe->created_at));
            $official_info = OfficialAccountService::officialAccountByAppid(['appid'=>$forceSubscribe->appid]);
            if($official_info){
                $data->subscribe_official = $official_info->nickname;
            }else{
                $data->subscribe_official = '';
            }
            $data->subscribed_src = $official_info->qrcode_url;
                //$this->getRcodeInfo(['appid'=>$forceSubscribe->appid],$forceSubscribe->bid,$uid);
            $data->label = '';
            if($forceSubscribe->bid){
                $book_info = BookConfigService::getBookById($forceSubscribe->bid);
                if($book_info) $data->label = $book_info->category_name;
            }
            if($forceSubscribe->is_subscribed == 1){
                $data->is_subscribed_text = '已关注';
            }else{
                $data->is_subscribed_text = '取关';
            }
        }else{
            $data->label = '';
            $data->is_subscribed = -1;
            $data->is_subscribed_text = '未关注';
            $data->subscribed_time = '';
            $data->subscribe_official = '';
            $data->subscribed_src = '';
        }
        $charge_lists = OrderService::totalChargeList($uid);
        $total_charge = 0;
        $total_money = 0;
        if($charge_lists){
            foreach ($charge_lists as $v){
                $total_charge += 100*$v->price+$v->given;
                $total_money += $v->price;
            }

        }
        $data->total_charge = number_format($total_charge);
        $data->balance = number_format($data->balance);
        $chapter_consume = ChapterOrderService::getChapterTotalConsume($uid);
        $book_consume = BookOrderService::getBookTotalConsume($uid);
        $data->total_consume = number_format($chapter_consume+$book_consume);
        $data->total_get = 0;
        $data->total_money = $total_money;

        return response()->success($data);
    }

    protected function getRcodeInfo($param,$bid,$uid){
        $param_need = [
            'gzh_app_id'=>$param['appid'],
            'scene_id' =>$uid,
            'timestamp'=>time(),
        ];
        $param_need['sign'] = $this->getSign($param_need);
        $client = new Client(['timeout'  => 3.0,]);
        try{
            $qrcode_url_res = $client->request('get','http://zsyauth.aizhuishu.com/api/get_qrcode_url?'.http_build_query($param_need))->getBody()->getContents();
            if($qrcode_url_res){
                $qrcode_url = json_decode($qrcode_url_res,true);
                if($qrcode_url['code'] == 1){
                    //保存强关时的bid
                    Redis::hset('force_subscribe_from_bid',$param['appid'].'_'.$this->uid,$bid);
                    return $qrcode_url['data'];
                }
            }
        }catch (\Exception $e){

        }

        return false;
    }

    /**
     * 公众号签名@华灯初上
     * @param $params
     * @return string
     */
    protected function getSign($params)
    {
        $url = $this->arr_to_url($params, false);
        $url = $url . '&key=' . $this->secret_key;

        $sign = md5($url);
        return $sign;
    }

    /**
     * 公众号签名@华灯初上
     * @param $array
     * @param bool $has_sign
     * @return string
     */
    protected function arr_to_url($array, $has_sign = false)
    {
        ksort($array);
        reset($array);
        $arg = "";
        while (list ($name, $val) = each($array)) {
            if ($name == 'sign' && !$has_sign) continue;
            if (strpos($name, "_") === 0)
                continue;
            if (is_array($val))
                $val = join(',', $val);
            if ($val === "")
                continue;
            $arg .= $name . "=" . $val . "&";
        }
        $arg = substr($arg, 0, count($arg) - 2);

        return $arg;
    }
}
