<?php
/**
其他平台公众号用户迁移到我们平台
 */
namespace App\Console\Commands\Tool;

use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\TempForceSubscribeUsers;
use Log;
use Illuminate\Console\Command;
use App\Modules\User\Services\UserService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use DB;

class ThirdPlatomUserTranser extends Command
{
    /**
     * 执行命令   Tool:ThirdPlatomUserTranser {appid}
     *
     * nohup php artisan Tool:ThirdPlatomUserTranser --appid=wxdbc486f1b4f6a8c3 --next_openid='-1' --add_balance=500 &
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Tool:ThirdPlatomUserTranser {--appid=} {--next_openid=} {--add_balance=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '其他平台公众号用户迁移到我们平台';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');
        print_r('memory_used:'.memory_get_usage()."\n");
        print_r("======其他平台公众号用户迁移到我们平台【任务执行开始】=====".date("y-m-d H:i:s"."\n"));
        
        $appid = $this->option('appid');
        $next_openid = $this->option('next_openid');
        $add_balance = $this->option('add_balance');

        if(empty($appid) || empty($next_openid) || empty($add_balance)){
        	\Log::info('ThirdPlatomUserTranser_appid_is_null:'.$appid);
        	exit();
        }
        
        \Log::info('ThirdPlatomUserTranser_start:$appid:'.$appid.' $next_openid:'.$next_openid);
        // 检查appid是否存在
        $param_official_account = ['appid'=>$appid];
        $official_account  = OfficialAccountService::officialAccountByAppid($param_official_account);
        
        $distribution_channel_id = isset($official_account->distribution_channel_id)?$official_account->distribution_channel_id:'';
        
        if(empty($official_account) || empty($distribution_channel_id)){
        	\Log::info('ThirdPlatomUserTranser_official_account_is_null:'.$appid.' $distribution_channel_id:'.$distribution_channel_id);
        	exit();
        }
        \Log::info('ThirdPlatomUserTranser_exist:'.$appid.' official_account：'.json_encode($official_account));
        
        if($next_openid == '-1'){
        	$next_openid = '';
        }
        if($add_balance == '-1'){
        	$add_balance = 0;
        }
        $skip = $loop = 0;
        
        while ( $loop <= 100) {
        	$loop++;
        	$users = array();
        	// 全服务号粉丝发，要记录next_openid
        	if($loop > 1 && empty($next_openid)){
        		\Log::info('OfficialAccountUserTranse_break,loop:'.$loop.' skip:'.$skip);
        		break;
        	}
        	$user_res = ForceSubscribeService::getFullOfficialAccountUsers($appid,$next_openid);
        	$users = $user_res['openids'];
        	$next_openid = $user_res['next_openid'];

        	\Log::info('loop'.$loop.' user_num:'.count($users).' next_openid：'.$next_openid);
        	//                         \Log::info($users);
        	$skip += count($users);
        	if(count($users)>0){
        		for ($i=0; $i < count($users); $i++) {
        			\Log::info('loop:'.$loop.' i:'.$i);
        			try{
        				$openid = isset($users[$i]['openid'])?$users[$i]['openid']:'';
        				$unionid = $openid;
        				$userinfo = ForceSubscribeService::getUserInfoAll($appid, $openid);
        				$nickname = isset($userinfo['nickname'])?$userinfo['nickname']:'';
        				$province = isset($userinfo['province'])?$userinfo['province']:'';
        				$city = isset($userinfo['city'])?$userinfo['city']:'';
        				$country = isset($userinfo['country'])?$userinfo['country']:'';
        				$headimgurl = isset($userinfo['headimgurl'])?$userinfo['headimgurl']:'';
        				$sex = isset($userinfo['sex'])?$userinfo['sex']:'0';
        				\Log::info('openid:'.$openid.' nickname:'.$nickname);
        				// 先用openid 判断强关表是否存在
        				$forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($openid,$appid,$distribution_channel_id);
        				if(!empty($forceSubscribeUsers)){
        					\Log::info('user_exist:'.$openid);
        					continue;
        				}
        				 
        				// user表
        				$user = [
	        				'openid'=>$openid,
	        				'unionid'=>$unionid,
	        				'nickname'=>$nickname,
	        				'distribution_channel_id'=>$distribution_channel_id,
	        				'province'=>$province,
	        				'city'=>$city,
	        				'country'=>$country,
	        				'headimgurl'=>$headimgurl,
	        				'sex'=>$sex,
        				];
        				// 实际是根据union_id和distribution_channel_id做更新
        				$added_user = UserService::addUser($user);
        				$uid = $added_user->id;
        				\Log::info('add_user_id:'.$uid);
        				if(!empty($uid)){
        					// force_subsribe_users
        					$add_forceSubscribeUsers = [
	        					'uid'=>$uid,
	        					'openid'=>$openid,
	        					'appid'=>$appid,
	        					'is_subscribed'=>1,
	        					'subscribe_time'=>date('Y-m-d H:i:s'),
	        					'distribution_channel_id'=>$distribution_channel_id,
	        					'last_interactive_time'=>date('Y-m-d H:i:s'),
        					];
        					\Log::info('create_force_subscribe_user:'.$openid);
        					//ForceSubscribeUsers::firstOrCreate($add_forceSubscribeUsers);
        					 
        					// temp_force_subsribe_users
        					$add_tempForceSubscribeUsers = [
	        					'uid'=>$uid,
	        					'openid'=>$openid,
	        					'appid'=>$appid,
	        					'is_subscribed'=>1,
	        					'subscribe_time'=>date('Y-m-d H:i:s'),
	        					'distribution_channel_id'=>$distribution_channel_id,
	        					'last_interactive_time'=>date('Y-m-d H:i:s'),
        					];
        					\Log::info('create_temp_force_subscribe_user:'.$openid);
        					//TempForceSubscribeUsers::firstOrCreate($add_tempForceSubscribeUsers);
        					
        					// 加书币
        					if($add_balance > 0){
        						$fee = $add_balance;
        						$charge = 0;
        						$given = $add_balance;
        						\Log::info('addbalance:'.$uid.' fee:'.$fee);
        						UserService::addBalance($uid, $fee, $charge, $given);
        					}
        				}
        				 
        			}catch(\Exception $e){
        				\Log::info('auto_subscribe_ept:'.$e->getMessage());
        			}
        			
        		}
        	}
        }
       
        \Log::info('ThirdPlatomUserTranser_end loop:'.$loop.' $skip:'.$skip);
        
        print_r("======其他平台公众号用户迁移到我们平台 【任务执行结束】=====".date("y-m-d H:i:s"."\n"));
        print_r('memory_used:'.memory_get_usage()."\n");
    }
}