<?php

namespace App\Http\Controllers\Channel\XChengXu;

use App\Modules\User\Services\UserService;
use Illuminate\Http\Request;

use App\Http\Controllers\Channel\BaseController;
use Redis;
use GuzzleHttp\Client;
use Log;
use App\Modules\User\Models\Xcxuser;
use App\Modules\Subscribe\Models\Order;
use App\Modules\User\Models\XcxUserStat;
use App\Http\Controllers\Channel\XChengXu\Transformers\StasticalTransformer;
class StasticalController extends BaseController
{
    /**
     * @apiDefine XCX 小程序
     */

    public function sendLink(){
        $domain = _domain();
        $url = 'https://'.$domain.'/xcx/yun?channel_id='.$this->getChannelId();
        return  response()->success(['link'=>$url]);
    }

    public function qrcode(Request $request){
        @ header("Content-Type:image/png");
        $channel_id = $request->get('channel_id');
        $uid = $request->has('uid')?$request->get('uid'):0;
        $u = $request->has('u')?$request->get('u'):0;
        echo  $this->getQrcode($channel_id,$uid,$u);
    }

    public function page(Request $request){
        $channel_id = (int)$request->get('channel_id',14);
        $u = (int)$request->get('xcx_send_order_id',0);
        $redirect = $request->has('redirect')?$request->get('redirect'):'';
        $openid = $request->has('openid')?$request->get('openid'):'';
        if(!$redirect &&  empty($openid)){
            $redirect_url  = 'https://'.env('CHANNEL_DOMAIN').'/xcx/yun?redirect=1&channel_id='.$channel_id;
            $appid = env('WECHAT_AUTH_APPID');
            $auth_url = env('AUTH_URL').'?gzh_app_id='.$appid.'&redirect_url='.urlencode($redirect_url);
            return redirect()->to($auth_url);
        }
        if(empty($channel_id)){
            $url = 'https://yueduyun.oss-cn-hangzhou.aliyuncs.com/distribution/xcx/img/qrcode.png';
        }else{
            $uid = $this->user($channel_id,$openid);
            $url = '/xcx/qrcode?channel_id='.$channel_id.'&uid='.$uid.'&u='.$u;
        }
        return view('channel.web.welcome.qrcode',['qrcode'=>$url]);
    }
    /**
     * @apiVersion 1.0.0
     * @apiDescription 今日数据
     * @api {get} xcx/todayData 今日数据
     * @apiGroup XCX
     * @apiName todayData
     * @apiSuccess  {int}       code 状态码
     * @apiSuccess  {String}    msg 信息
     * @apiSuccess  {object}    data 结果集
     * @apiSuccess  {Int}       data.today_recharge 今日充值
     * @apiSuccess  {String}    data.new_user_num 今日新增用户
     * @apiSuccess  {Int}       data.total_recharge 累计充值
     * @apiSuccess  {Int}       data.total_user_num 累计用户
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": {
     *               "today_recharge": 5,
     *               "new_user_num": "第1240章 不是我",
     *               "total_recharge": 1239,
     *               "total_user_num": 1,
     *            }
     *       }
     */
    public function todayData(Request $request){

        $channel_id = $this->getChannelId();
        $recharge = Order::where('status','PAID')
            ->where('pay_merchant_source','XIAOCHENGXU')
            ->where('created_at','>=',date('Y-m-d'))
            ->where('created_at','<=',date('Y-m-d',time()+86400))
            ->where('distribution_channel_id',$channel_id)
            ->sum('price');

        $total_recharge = Order::where('status','PAID')
            ->where('pay_merchant_source','XIAOCHENGXU')
            ->where('created_at','<',date('Y-m-d'))
            ->where('distribution_channel_id',$channel_id)
            ->sum('price');

        $new_user_num = Xcxuser::where('created_at','>=',date('Y-m-d'))
            ->where('created_at','<=',date('Y-m-d',time()+86400))
            ->where('distribution_channel_id',$channel_id)
            ->count();

        $total_user_num = Xcxuser::where('created_at','<',date('Y-m-d'))
            ->where('distribution_channel_id',$channel_id)
            ->count();

        $res = [
            'recharge'=>$recharge,
            'new_user_num'=>$new_user_num,
            'total_recharge'=>$total_recharge,
            'total_user_num'=>$total_user_num,
        ];
        return response()->success($res);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 统计数据
     * @api {get} xcx/statisticalData 统计数据
     * @apiGroup XCX
     * @apiName statisticalData
     * @apiParam    {int}       page 页码
     * @apiSuccess  {int}       code 状态码
     * @apiSuccess  {String}    msg 信息
     * @apiSuccess  {object}    data 结果集
     * @apiSuccess  {Int}       data.date 日期
     * @apiSuccess  {Int}       data.new_user_num 新增用户数
     * @apiSuccess  {String}    data.success_order_num 成功订单数
     * @apiSuccess  {Int}       data.order_num 订单数
     * @apiSuccess  {Int}       data.recharge 充值金额
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "code": 0,
     *       "msg": "",
     *       "data": [.
     *              {
     *               "date":'2018-03-01'
     *               "new_user_num": 5,
     *               "success_order_num": 12321,
     *               "order_num": 1239,
     *               "recharge": 1,
     *            }
     *             ]
     *       }
     */
    public function statisticalData(Request $request){
        $page_size = $request->input('page_size',15);
        $channel_id = $this->getChannelId();
        $res = XcxUserStat::where('distribution_channel_id',$channel_id)
            ->select('date','new_user_num','success_order_num','order_num','recharge')
            ->orderBy('date','desc')
            ->paginate($page_size);
        return response()->pagination(new StasticalTransformer(), $res);
    }

    private function getQrcode($channel_id,$uid,$u){
        $appid = 'wxa0c8331eba3b34d5';
        $secret = '17c01c26dd7873e557710601436774c7';
        $key = "appid:".$appid.":accesstoken";
        $access_token = Redis::get($key);
        $client = new Client(['timeout'  => 3.0,]);
        if(!$access_token){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            try{
                $qrcode_url_res = $client->request('get',$url)->getBody()->getContents();
                if($qrcode_url_res){
                    $qrcode_res = json_decode($qrcode_url_res,true);
                    $access_token = $qrcode_res['access_token'];
                    Redis::setex($key,7200,$access_token);
                }
            }catch (\Exception $e){

            }
        }

        $access_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $scence = '%s_%s_%s';
        $param = ['scene'=>sprintf($scence,$channel_id,$uid,$u)];
        $res = $this->send($access_url,$param);
        return $res;
    }

    static function send($url,$data)
    {
        //$headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $data=json_encode($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    private function user($channel_id,$openid){
        $user = UserService::getUserByUnionAndChannelId($openid,$channel_id);
        if($user){
            return $user->id;
        }
        $user = UserService::addUser([
            'openid'=>$openid,
            'unionid'=>$openid,
            'distribution_channel_id'=>$channel_id
        ]);

        return $user->id;
    }
}
