<?php

namespace App\Console\Commands;

use App\Modules\Push\Models\QappPushUser;
use Illuminate\Console\Command;
use DB;
use Log;

class FixPushUserChannel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'FixPushUserChannel {--channel_id=} {--distribution_channel_id=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $channel_id = $this->option('channel_id');
        $distribution_channel_id = $this->option('distribution_channel_id');
        //
        $qapp_push_users = QappPushUser::leftjoin('users','users.id','qapp_push_user.uid')
            ->leftjoin('qapp_push_app',function($join){
                $join->on('users.distribution_channel_id','=','qapp_push_app.uid')
                    ->on('qapp_push_user.provider','=','qapp_push_app.provider');
            })
            ->where('qapp_push_user.channel_id',$channel_id)
            ->where('users.distribution_channel_id',$distribution_channel_id)
            ->select('qapp_push_user.*','users.send_order_id','users.distribution_channel_id','qapp_push_app.app_id as appId')
            ->get();
        if(!$qapp_push_users->isEmpty()){
            try {
                $i = $j = 0;
                foreach($qapp_push_users as $item){
                    $j++;
                    if($item->distribution_channel_id != $item->channel_id && $item->app_id != $item->appId){
                        DB::table('qapp_push_user')->where('id',$item->id)->update([
                            'app_id' => $item->appId,
                            'channel_id' => $item->distribution_channel_id,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                        $i++;
                    }
                }
                \Log::info('FixPushUserChannel_count:'.$j.' fix_count:'.$i);
            } catch (\Exception $e) {
                \Log::info('FixPushUserChannel_error:channel_id'.$channel_id.' distribution_channel_id:'.$distribution_channel_id);
                \Log::info('FixPushUserChannel_error:'.$e->getMessage());
            }

        }
    }

}
