<?php

namespace App\Http\Controllers\Wap\User;

use App\Libs\AliSMS;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookUrgeUpdateService;
use App\Modules\Book\Services\SignBookService;
use App\Modules\Statistic\Services\AdVisitStatService;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\User\Services\ForceGuidePersonAccountService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserBindPhoneService;
use App\Modules\User\Services\UserWealthyOperateRecordService;
use App\Modules\User\Services\WapReaderPageFissionService;
use Illuminate\Http\Request;
use App\Http\Controllers\Wap\BaseController;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Services\UserService;
use App\Modules\User\Services\UserRandSignService;
use App\Modules\User\Services\UserSignService;
use App\Http\Controllers\Wap\User\Transformers\SignRecordTransformer;
use Log;
use Redis;
use Cookie;
use DB;
use Hashids;

class UserController extends BaseController
{
    /**
     * @apiDefine User 用户
     */


    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取用户信息
     * @api {GET} userinfo 获取用户信息
     * @apiGroup User
     * @apiName index
     * @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_vip 是否vip
     * @apiSuccess {String}  vip_days 364天.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *             "id": 56,
     *             "openid": "sdfs34ssdfdsf",
     *             "unionid": "SDFSD3343S",
     *             "distribution_channel_id": 1212,
     *             "province": "浙江省",
     *             "city": "杭州",
     *             "country": "中国",
     *             "headimgurl": "http://.."
     *             "send_order_id": 323
     *             "balance": 8956
     *             "register_time": "2017-12-12 12:12:12"
     *         }
     *     }
     */
    public function index(){
        if(!$this->checkUid()){
            return response()->error('NOT_LOGIN');
        }

        $data = UserService::getById($this->uid);
        $data['bind'] = 0;
        $data['bind_phone'] = '';
        $data['is_paid'] = $this->is_paid;
        if($this->is_paid){
            $bind_info = UserBindPhoneService::bindInfo($this->uid);
            if($bind_info){
                $data['bind'] = 1;
                $data['bind_phone'] = $bind_info->phone;
            }
        }

        $data['is_vip'] = 0;
        $data['vip_days'] = 0;
        $year_record = YearOrderService::getRecord($this->uid);
        if($year_record){
            $data['is_vip'] = 1;

            $time = strtotime($year_record['end_time'])-time();
            if($time>=86400){
                $data['vip_days'] = floor($time/86400).'天';
            }elseif ($time>3600) {
                $data['vip_days'] = floor($time/3600).'小时';
            }elseif ($time>60) {
                $data['vip_days'] = floor($time/60).'分钟';
            }else{
                $data['vip_days'] = $time.'秒';
            }
        }
        $data['is_all_life'] = 0;
        $activity_id = env('FOREVER_ACTIVITY_ID');
        if($activity_id){
            if(OrderService::userIsParticipateActivity($this->uid,$activity_id)){
                $data['is_vip'] = 0 ;
                $data['vip_days'] = '99年';
                $data['is_all_life'] = 1;
            }
        }
        return response()->success($data);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 用户签到记录
     * @api {GET} user/sign_record 用户签到记录
     * @apiGroup User
     * @apiName signRecord
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {reward}     data.reward 奖励金额.
     * @apiSuccess {sign_time}  data.sign_time 签到时间.
     * @apiParam {page}  page
     * @apiSuccessExample {json} Success-Response:
     *
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *           list: [
     *           {
     *               reward: 50,
     *               sign_time: "2018-03-20 13:43:11"
     *           },
     *           {
     *               reward: 50,
     *               sign_time: "2018-01-18 16:22:33"
     *           },
     *       ],
     *       meta: {
     *           total: 12,
     *           per_page: 15,
     *           current_page: 1,
     *           last_page: 1,
     *           next_page_url: "",
     *           prev_page_url: ""
     *       }
     *       }
     *   }
     */
    public function signRecord(Request $request){
        $sign_result = paginationTransform(new SignRecordTransformer(),UserSignService::getUserSignRecord($this->uid));
        $sign_status = UserSignService::isSign($this->uid);
        $sign_today = [];
        if($sign_status){
            $sign_today = ReadRecordService::getByField($this->uid,'sign_info');
            if($sign_today) $sign_today = json_decode($sign_today,1);
            isset($sign_today['sign_time']) && $sign_today['sign_time'] = date('Y-m-d H:i:s',$sign_today['sign_time']);
            isset($sign_today['sign_at']) && $sign_today['sign_time'] = $sign_today['sign_at'];
            isset($sign_today['price']) && $sign_today['reward'] = $sign_today['price'];
        }
        $result = [
            'sign_status'=>$sign_status,
            'sign_result'=>$sign_result,
            'sign_today'=>$sign_today
        ];
        return response()->success($result);
    }

    public function getCoupons(Request $request){
        $activity_id = $request->input('activity_id');
        if(!DB::table('discount_coupons')->where('uid',$this->uid)->where('activity_id',$activity_id)->count()){
            DB::table('discount_coupons')->insert([
                'uid'=>$this->uid,
                'activity_id'=>$activity_id,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s')
            ]);
        }

        return response()->success();
    }

    public function sign(Request $request){
        //sign_days
        //$day = date('Y-m-d');
        $sign = UserSignService::isSign($this->uid);
        $sign_count = ReadRecordService::getSignCount($this->uid);
        if($sign){
            //如果已经签过到
            if(!$sign_count){
                ReadRecordService::setSignCount($this->uid,1);
                ReadRecordService::setSignDay($this->uid);
                $sign_count = 1;
            }
            $fee = 30;
            if($sign_count>=3){
                $fee = 50;
            }
            $data = ['sign_days'=>$sign_count,'sign_reard'=>$fee,'status'=>1];
            return response()->success($data);
        }

        //还没有签到
        $status = UserSignService::signToday($this->uid);
        $sign_count = ReadRecordService::getSignCount($this->uid);
        $data = ['sign_days'=>$sign_count,'sign_reard'=>$status,'status'=>0];
        return response()->success($data);
    }

    /**
     * @return string
     */
    public function signi()
    {
        /*if(in_array($this->distribution_channel_id,explode(',',redisEnv('NEW_SIGN_CHANNELS','')))){
            $version = UserSignService::getUserSignVersion($this->uid);
        }else{
            $version = 'v1';
        }*/
        $version = UserSignService::getUserSignVersion($this->uid);

        if($version == 'v1'){
            $page = 'wap.sign';
        }else{
            $page = 'wap.signv2';
        }
        $book1= $book2 = null;
        if($version == 'v2' ){
            $sex = $this->_user_info->sex;
            $sex = $sex?$sex:2;
            $book1 = BookConfigService::getRandomOneHighQualityBook($sex);
            $book1->url = sprintf('/reader?bid=%s&cid=%s&source=wechatmsg&fromtype=sign_recommend',Hashids::encode($book1->bid),$book1->first_cid);
            $book2 = SignBookService::getRandomBook($sex);
            \Log::info($book2);
            foreach ($book2 as $item){
                $item->url = sprintf('/reader?bid=%s&cid=%s&source=wechatmsg&fromtype=sign_recommend',Hashids::encode($item->bid),$item->first_cid);
            }

        }
        $tomorrow_pool = $fee_pool = [0,30,50,120,50,50,50,150];
        $day = [0,'一','二','三','四','五','六','七'];
        list($sign,$sign_count) = ReadRecordService::getByMultiField($this->uid,'sign_day','sign_counts');
        if ($sign && $sign == date('Y-m-d')) {
            if($version == 'v1'){
                $fee = $sign_count>=3 ? 50:30;
            }else{
                if ($sign_count % 7 == 1 && $sign_count<=7) {
                    $fee = 30;
                } elseif ($sign_count % 7 == 3) {
                    $fee = 120;
                } elseif ($sign_count % 7 == 0) {
                    $fee = 150;
                } else {
                    $fee = 50;
                }
            }
            if($sign_count >=8){
                $fee_pool[1] = 50;
            }

            $tomorrow = (($sign_count+1) % 7 == 0? 7:($sign_count+1) % 7);
            if($sign_count+1 >=8){
                $tomorrow_pool[1] = 50;
            }
            //签过到了
            $data = ['sign_count'=>$sign_count,'fee'=>$fee,'fee_pool'=>$fee_pool,'day'=>$day,'book1'=>$book1,'book2'=>$book2,'tomorrow_fee'=>$tomorrow_pool[$tomorrow]];
            return view($page,$data);
        }
        $fee = UserSignService::signToday($this->uid,$version);
        if(!$fee){
            return response()->error('WAP_SYS_ERROR');
        }
        $sign_count = ReadRecordService::getSignCount($this->uid);
        if($sign_count >=8){
            $fee_pool[1] = 50;
        }
        if($sign_count+1 >=8){
            $tomorrow_pool[1] = 50;
        }
        $tomorrow = (($sign_count+1) % 7 == 0? 7:($sign_count+1) % 7);
        $data = ['sign_count'=>$sign_count,'fee'=>$fee,'fee_pool'=>$fee_pool,'day'=>$day,'book1'=>$book1,'book2'=>$book2,'tomorrow_fee'=>$tomorrow_pool[$tomorrow]];
        return view($page,$data);
    }

    public function recordShare(Request $request){
        if(!$this->checkUid()){
            return response()->error('NOT_LOGIN');
        }
        $uid = $this->uid;
        $distribution_channel_id = $this->distribution_channel_id;
        $type = 'click';
        $bid = $request->get('bid');
        $cid = $request->get('cid',0);
        if(!$bid){
            return response()->error('PARAM_ERROR');
        }
        !is_numeric($bid) && $bid = Hashids::decode($bid)[0];
        WapReaderPageFissionService::createV2($uid,$bid,$distribution_channel_id,$type,0,$cid);
        $user = $this->_user_info;
        $data = [];
        if(in_array($distribution_channel_id,[2,14,211]) && $user){
            $data['username'] = $user->nickname;
            $data['head_img'] = $user->head_img;
            $url = 'https://'._domain().'/detail?fromtype=readershare&id='.Hashids::encode($bid).'&fromflag='.$uid;
            //$url = str_replace('http://', $h5_scheme . '://', url()->current() . '?' . http_build_query($params));
            $data['share_url'] = $url;
        }
        return response()->success($data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 用户点击广告统计
     * @api {post} user/advisitstat 用户点击广告统计
     * @apiGroup User
     * @apiName signRecord
     * @apiParam {Int} bid      bid
     * @apiParam {Int} cid      cid
     * @apiParam {Int} type     type类型(CLICK|UNLOCK)
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiParam {page}  page
     * @apiSuccessExample {json} Success-Response:
     *
     *    {
     *       code: 0,
     *       msg: "",
     *       data: {
     *           {
     *               reward: 50,
     *               sign_time: "2018-03-20 13:43:11"
     *           },
     *           {
     *               reward: 50,
     *               sign_time: "2018-01-18 16:22:33"
     *           },
     *       }
     *   }
     */
    public function adVisitStat(Request $request){
        $bid = $request->get('bid');
        $cid = $request->get('cid',0);
        $type = $request->get('type');
        if(!$bid || !$type){
            return response()->error('PARAM_ERROR');
        }
        !is_numeric($bid) && $bid = Hashids::decode($bid)[0];
        AdVisitStatService::create($this->uid,$bid,$cid,$type);
        return response()->success();
    }

    public function urgeUpdate(Request $request){
        $bid = $request->get('bid');
        if(!$bid){
            return response()->error('PARAM_ERROR');
        }
        $bid = Hashids::decode($bid)[0];

        $result = BookUrgeUpdateService::UrgeRecord($this->uid,$bid);
        if($result && !$result->id){
            BookUrgeUpdateService::UrgeUpdate($this->uid,$bid,$result->updated_at);
        }
        return response()->success();
    }

    function logout(Request $request,$channel_id,$domain)
    {
        //echo $channel_id.'----';
        //echo $domain;
        $domains = ['zhuishuyun','66kshu','iycdm','leyuee'];

        setcookie(env('COOKIE_AUTH_WEB_WECHAT'), '', -1);
        setcookie('u', '', -1);
        setcookie('force_show_qrcode', '', -1);
        setcookie('sub_random_num', '', -1);
        setcookie('cpc_ad_status', '', -1);
        //return response('logout');
        $param = $request->except('_url');
        $url_format = '%s://site%s.%s.com/logout?%s';
        if(in_array($domain,$domains)){
            $i = 0;
           foreach ($domains as $k=>$v){
               if($v == $domain){
                   $i = $k;
               }
           }
           if(isset($domains[$i+1])){
               $link = sprintf($url_format,env('PROTOCOL'),$channel_id,$domains[$i+1],http_build_query($param)) ;
               return redirect()->to($link);
           }
        }
        return  view('help.logout');
    }

    function setOrderDelCookie(Request $request){
        $param = $request->except('_url');
        $type = isset($param['type']) ?$param['type']:'set';

        foreach ($param as $k=>$v){
            if($k == 'type') continue;
            if($type == 'set'){
                Cookie::queue($k, $v, 1000, null, null, false, false);
            }else{
                setcookie($k, '', -1);
            }
        }
        return response('ok');
    }
    
    function test_add_user_login_cookie(Request $request)
    {
    	$uid = $request->get('uid');
    	\Log::info('test_add_user_login_cookie:'.$uid);
    	Cookie::queue(env('COOKIE_AUTH_WEB_WECHAT'), $uid, env('U_COOKIE_EXPIRE'), null, null, false, false);
    	return response('add_cookie:'.$uid);
    }

    //日常随机签到
    function day_rand_sign(Request $request)
    {
        $uid = $this->uid;
        $day = date('Y-m-d');
        $hasSigned = UserRandSignService::hasSigned(compact('uid','day'));
        $fee = 0;
        if(!$hasSigned)
        {
            $fee = mt_rand(5,15);
            UserRandSignService::sign(compact('uid','day','fee'));
        }
        return view('wap.rand_sign',compact('hasSigned','fee'));
    }

    public function sendCode(Request $request){
        $phone = $request->post('phone');
        $code = random_int(1000,9999);
        Redis::setex('code:'.$phone,120,$code);
        AliSMS::send($phone, 'paid_user_bind_phone', ['code'=>$code]);
        return response()->success();
    }

    public function bindPhone(Request $request){
        $code = $request->post('code');
        $phone = $request->post('phone');
        $from = $request->post('from');
        $old = Redis::get('code:'.$phone);
        if($old && $old == $code){
            Redis::del('code:'.$phone);
            $user_info  = UserService::getById($this->uid);
            if(!$user_info){
                return response()->error();
            }
            try{
                $result = UserBindPhoneService::bind($this->uid,$user_info->openid,$phone,$from);
                if($result == 0){
                    UserService::addBalance($this->uid,100,0,100);
                    UserWealthyOperateRecordService::create($this->uid,100,$this->distribution_channel_id,'bind_phone');
                    return response()->success();
                }
                if($result == -1){
                    return response()->error('WAP_BIND_PHONE_EXIST');
                }
                if($result == -2){
                    return response()->error('WAP_SEND_OPENID_EXIST');
                }
            }catch (\Exception $e){}

        }else{
            return response()->error('WAP_SEND_CODE_ERROR');
        }
        return response()->error();
    }

    public function bindPhoneView(Request $request){
        $from = 'personal';
        $order = '';
        $url = '/personal';
        return view('pay.order.bindPhone', compact('order', 'url','from'));
    }

    public function guidePersonalAccount(Request $request){
        $bid = $request->get('bid');
        $cid = $request->get('cid');
        $prev_cid = $request->get('prev_cid');
        $book_name = $request->get('book_name');
        $bid_no = Hashids::decode($bid)[0];

        $env_config = redisEnvMulti('FORCE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE','FORCE_GUIDE_PERSONAL_ACCOUNT_MAX_UV',
            'FORCE_GUIDE_PERSONAL_ACCOUNT_ID','FORCE_GUIDE_PERSONAL_ACCOUNT_MAX_EVERY_UV');
        $img = empty($env_config[0])?'https://cdn-novel.iycdm.com/h5/personal_account/chenchen.jpg':$env_config[0];
        $max = empty($env_config[1])?100:$env_config[1];
        $one_loop_max = empty($env_config[3])?10:$env_config[3];
        $now_id = (int)$env_config[2];
        $uv = Redis::scard('force_guide_personal_uv');
        $personal_info = DB::table('personal_account_list')->where('id',$now_id)->select('count')->first();
        $total_max = $personal_info->count+$uv;
        //Log::info('$total_max is: '.);
        if($uv >= $one_loop_max || $total_max>=$max){
            if($total_max>=$max){
                DB::table('personal_account_list')->where('id',$now_id)->update([
                    'status'=>2,
                    'count'=>$total_max,
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }else{
                DB::table('personal_account_list')->where('id',$now_id)->increment('count',$uv,[
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
            }

            $account = DB::table('personal_account_list')
                ->where('is_enable',1)
                ->whereIn('status',[1,0])
                ->select('id','url')
                ->where('count','<',$max)
                ->where('group','FORCE')
                ->orderBy('count','asc')
                ->orderBy('id')
                ->first();
            Redis::del('force_guide_personal_uv');
            if($account){
                DB::table('personal_account_list')->where('id',$account->id)->update([
                    'status'=>1,
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
                $img = $account->url;
                $now_id = $account->id;
                Redis::Hmset('env','FORCE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE',$account->url,'FORCE_GUIDE_PERSONAL_ACCOUNT_ID',$account->id);
            }else{
                Redis::Hmset('env','FORCE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE','','FORCE_GUIDE_PERSONAL_ACCOUNT_ID','');
            }
        }
        Redis::sadd('force_guide_personal_uv',$this->uid);

        DB::table('ad_pdd')->insert([
            'uid'=>$this->uid,
            'img'=>'FORCE_GUIDE_PERSONAL_ACCOUNT_'.$now_id,
            'date'=>date('Y-m-d'),
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s')
        ]);

        ForceGuidePersonAccountService::create($this->uid,$bid_no,$cid);

        $link['next'] = sprintf('/reader?bid=%s&cid=%s',$bid,$cid);
        $link['prev'] = sprintf('/reader?bid=%s&cid=%s',$bid,$prev_cid);
        $link['catalog'] = sprintf('/catalog?id=%s',$bid);

        return view('jump.forceGuidePersonalAccount',['img'=>$img,'link'=>$link,'title'=>$book_name]);
    }
    
}