<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/9/16
 * Time: 17:58
 */

namespace App\Console\Commands\SmartPush;

use App\Jobs\SendTexts;
use App\Modules\User\Services\ReadRecordService;
use DB;
use Redis;
use Hashids;
use Illuminate\Console\Command;

class BookUpdatePush extends Command
{

    const BOOK_LAST_UPDATE_INFO = 'book:last_update'; //list

    const BOOK_LAST_UPDATE_INFO_STATUS = 'book:last_update_status';

    const CUSTOM_CATEGORY = 'book_update_push';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SmartPush:BookUpdatePush';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '图书更新推送';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    private $switch = [];
    private $default_status;

    public function __construct()
    {
        parent::__construct();
    }

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


    private function start(){
        /*$info = DB::connection('api_mysql')->table('custom_msg_switchs')->where('custom_category',self::CUSTOM_CATEGORY)->first();
        if(!$info) return ;
        $this->default_status = $info->default_switch_status;*/
        $this->default_status = 0;
        $update_status = Redis::get(self::BOOK_LAST_UPDATE_INFO_STATUS);
        if($update_status == '1'){
            Redis::set(self::BOOK_LAST_UPDATE_INFO_STATUS,2);
            $this->getBookAndSend();
        }
    }

    private function getBookAndSend(){
        $length = Redis::llen(self::BOOK_LAST_UPDATE_INFO);
        if($length <= 0) return [];
        $count = ceil($length/100);
        for ($i=0;$i <$count;$i++){
            $start = $i*100;
            $end = $start+99;
            $result = Redis::Lrange(self::BOOK_LAST_UPDATE_INFO,$start,$end);
            foreach ($result as $item){
                $record = json_decode($item,1);
                $bid = $record['bid'];
                $book_name = $record['book_name'];
                $chapter_name = $record['chapter_name'];
                $this->sendByBook($bid,$book_name,$chapter_name);
            }
        }
        Redis::del(self::BOOK_LAST_UPDATE_INFO);
    }


    private function sendByBook($bid,$book_name,$chapter_name){
        $user_list = $this->userList($bid);
        if(!$user_list) return ;
        foreach ($user_list as $uid){
            $user_force_subscribe_info = $this->userPushInfo($uid);
            if(!$user_force_subscribe_info) continue;
            $cid_time = ReadRecordService::getRecordByUidBid($uid,$bid);
            if(!$cid_time) continue;
            list($cid,$time) = explode('_',$cid_time);
            if(!$cid) continue;
            $link = 'https://site'.encodeDistributionChannelId($user_force_subscribe_info['distribution_channel_id']).'.zhuishuyun.com/reader?bid='.Hashids::encode($bid).'&cid='.$cid.'&fromtype=book_update_push';
            $content_fromat = "小说更新提醒\r\n\r\n<a href='%s'>《%s》已更新到《%s》</a>\r\n\r\n精彩内容不容错过~\r\n";
            $content = sprintf($content_fromat,$link,$book_name,$chapter_name);
            $data = [
                'openid'=>$user_force_subscribe_info['openid'],
                'appid'=>$user_force_subscribe_info['appid'],
                'type'=>'one_task',
                'task_id'=>1,
                'send_time'=>date('Y-m-d H:i:s'),
                'content'=>$content
            ];
            $send_data=array(
                'send_time'=>date("Y-m-d H:i:s"),
                'data' => $data
            );
            $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay(0)->onQueue('send_texts_list');
            dispatch($job);
        }
    }


    private function userPushInfo($uid){
        $user_force_subscribe_info = DB::connection('api_mysql')->table('temp_force_subscribe_users')
            ->select('distribution_channel_id','openid','appid')
            ->where('uid',$uid)
            ->where('is_subscribed',1)
            ->where('last_interactive_time','>',date('Y-m-d H:i:s',time()-86400*2))
            ->first();
        if(!$user_force_subscribe_info) return [];
        if(!$this->switchStatus($user_force_subscribe_info->distribution_channel_id)) return [];
        return [
            'distribution_channel_id'=>$user_force_subscribe_info->distribution_channel_id,
            'openid'=> $user_force_subscribe_info->openid,
            'appid'=>$user_force_subscribe_info->appid
        ];
    }

    private function userList($bid){
        // [8426169,14128];
        return DB::connection('api_mysql')->table('user_last_chapter_order')->where('bid',$bid)->select('uid')->pluck('uid');
    }


    private function switchStatus($distribution_channel_id){

        return false;
        if(isset($this->switch[$distribution_channel_id])){
            return $this->switch[$distribution_channel_id] == 1;
        }
        $switch = DB::connection('api_mysql')->table('custom_msg_switchs_msgs')
            ->where('distribution_channel_id',$distribution_channel_id)
            ->where('custom_category',self::CUSTOM_CATEGORY)
            ->select('status')
            ->first();
        if($switch){
            $this->switch[$distribution_channel_id] = $switch->status;
        }else{
            $this->switch[$distribution_channel_id] = $this->default_status;
        }
        return $this->switch[$distribution_channel_id] == 1;
    }
}