<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/10/23
 * Time: 16:44
 */

namespace App\Console\Commands\SmartPush;

use App\Modules\User\Services\UserSignService;
use Illuminate\Console\Command;
use DB;
use Redis;
use GuzzleHttp\Client;
use App\Http\Controllers\WechatController;
use GuzzleHttp\Psr7\Request as GuzzleRequest;
use GuzzleHttp\Pool;

class remindSign extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SmartPush:remindSign {--start=} {--end=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '签到提醒';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->send();
    }

    private  function generateRequest()
    {
        $switch_array = [];
        $start = $this->option('start',0);
        $end = $this->option('end');
        $temp = $start;
        $continueReadUrlFormat = 'https://site%s.%s.com/sign';
        $info = DB::connection('api_mysql')->table('custom_msg_switchs')->where('custom_category','remind_sign')->first();
        if(!$info) return ;
        $default_status = $info->default_switch_status;
        while (true){
            if($end == -1){
                $user =  DB::connection('api_mysql')->table('temp_force_subscribe_users')
                    ->select('id','uid','distribution_channel_id','openid','appid')
                    ->where('id','>',$temp)
                    ->where('last_interactive_time','>',date('Y-m-d H:i:s',time()-86400*2))
                    ->orderBy('id')
                    ->limit(5000)
                    ->get();
            }else{
                $user =  DB::connection('api_mysql')->table('temp_force_subscribe_users')
                    ->select('id','uid','distribution_channel_id','openid','appid')
                    ->where('id','>',$temp)
                    ->where('id','<=',$end)
                    ->where('last_interactive_time','>',date('Y-m-d H:i:s',time()-86400*2))
                    ->orderBy('id')
                    ->limit(5000)
                    ->get();
            }

            if(!$user) break;

            foreach ($user as $item){
                //if(!in_array($item->distribution_channel_id,[70])) continue;
                //\Log::info( '---------------------------start--start-------------------------------------------' );
                //\Log::info('$item->distribution_channel_id is :'.$item->distribution_channel_id  );
                //\Log::info( 'remindSign $item->id is :'.$item->id );
                if(!isset($switch_array[$item->distribution_channel_id])){
                    $switch = DB::connection('api_mysql')->table('custom_msg_switchs_msgs')
                        ->where('distribution_channel_id',$item->distribution_channel_id)
                        ->where('custom_category','remind_sign')
                        ->select('status')
                        ->first();
                    if($switch){
                        $switch_array[$item->distribution_channel_id] = $switch->status;
                    }else{
                        $switch_array[$item->distribution_channel_id] = $default_status;
                    }
                }

                $switch_status = $switch_array[$item->distribution_channel_id];
                if($switch_status != 1) continue;
                //\Log::info( 'remindSign $item->distribution_channel_id in is :'.$item->distribution_channel_id );

                $is_sign = $this->isSign($item->uid);
                if(!$item->uid)$item->uid = 0;
                //\Log::info( $read_info );
                //\Log::info( 'uid is :'.$item->uid  );
                if($is_sign) continue;
                $user_info = DB::connection('api_mysql')->table('users')->where('id',$item->uid)->select('nickname','openid','created_at')->first();
                $nickname = '读者';
                if($user_info && $user_info->nickname)$nickname = $user_info->nickname;

                $openid = $item->openid;
                $appid = $item->appid;
                //$url = sprintf($continueReadUrlFormat,encodeDistributionChannelId($item->distribution_channel_id),env('CUSTOM_HOST'));
                $url = 'weixin://bizmsgmenu?msgmenucontent=签到&msgmenuid=hudonglian';
                $guide_status = false;
                if($user_info){
                    $guide_status = UserSignService::guideFans($item->uid,$item->distribution_channel_id,$user_info->openid,$user_info->created_at);
                }
                if($guide_status){
                    $guide_link = 'https://site'.encodeDistributionChannelId($item->distribution_channel_id).'.leyuee.com/guidestrem?uid='.$item->uid.'&fee=500';
                    $content_format = "亲爱的%s，您今日还未签到，本次签到最高可领取150书币哦\r\n\r\n❤<a href='%s'>点击此处签到领书币</a>\r\n\r\n<a href='%s'>免费领取500书币奖励>></a> \r\n\r\n为了方便下次阅读，请<a href='%s'>置顶公众号</a>";
                    $content = sprintf($content_format,$nickname,$url,$guide_link,
                        'https://help.zhuishuyun.com/top.html'
                    );
                }else{
                    $content_format = "亲爱的%s，您今日还未签到，本次签到最高可领取150书币哦\r\n\r\n❤<a href='%s'>点击此处签到领书币</a>\r\n\r\n\r\n为了方便下次阅读，请<a href='%s'>置顶公众号</a>";
                    $content = sprintf($content_format,
                        $nickname,$url,
                        'https://help.zhuishuyun.com/top.html'
                    );
                }

                $accecc_token = $this->getAccessToken($appid);
                if(!$accecc_token)continue;

                $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$accecc_token;
                $request = new GuzzleRequest('post',$url,[],\GuzzleHttp\json_encode([
                    'touser'=>$openid,
                    'msgtype'=>'text',
                    'text'=>['content'=>$content]
                ],JSON_UNESCAPED_UNICODE));

                //\Log::info( '----------------------------end-end-end-------------------------------------------' );
                yield $request;
            }
            $temp = $item->id;

        }
    }


    private function getAccessToken($appid){
        try{
            $WechatController = new WechatController($appid);
            $accessToken = $WechatController->app->access_token; // EasyWeChat\Core\AccessToken 实例
            $token = $accessToken->getToken(); // token 字符串
            return $token;
        }catch(\Exception $e){
            \Log::error($e->getMessage());
        }
        return '';
    }

    private function send(){
        $client = new Client();
        $requests = $this->generateRequest();
        $pool = new Pool($client, $requests, [
            'concurrency' => 5,
            'fulfilled' => function ($response, $index) {

            },
            'rejected' => function ($reason, $index) {

            },
        ]);
        $promise = $pool->promise();
        $promise->wait();
    }

    private function isSign($uid){
        $sign_day = Redis::hget('book_read:' . $uid,'sign_day');
        if ($sign_day && $sign_day == date('Y-m-d')) {
            return true;
        }
        return false;
    }
}