<?php
/**
 * Created by sublime.
 * User: wosinC
 * Date: 2017/12/2
 * Time: 上午11:39
 */

namespace App\Modules\OfficialAccount\Services;

use App\Modules\OfficialAccount\Models\ForceSubscribeUserProperty;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\TempForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\User\Services\UserService;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Models\YqMove;
use App\Libs\OSS;
use Redis;
use App\Jobs\SendTemplate;
use App\Jobs\SendStatisticsList;
use GuzzleHttp\Client;

class ForceSubscribeService
{

	//-----------强关用户---------------

	/**
	* 通过appid和openid获取强关用户
	*/
	static function forceSubscribeUsersByAppidAndOpenId($forceSubscribeUsersPrams)
    {

        //\Log::info('======================get_forceSubscribe_Users11111111111======================'."\n");
        //\Log::info($forceSubscribeUsersPrams);
        $officialAccount = OfficialAccount::officialAccountByAppid($forceSubscribeUsersPrams['appid']);
//         \Log::info('======================get_forceSubscribe_Users222222222222======================'."\n");
//         \Log::info($officialAccount);
        if (!empty($officialAccount)) {
            $distribution_channel_id = $officialAccount['distribution_channel_id'];
            //\Log::info('======================get_forceSubscribe_Users333333333333======================'."\n");
            //\Log::info(ForceSubscribeUsers::forceSubscribeUsersByOpenidAndChannelId($forceSubscribeUsersPrams['openid'],$officialAccount['distribution_channel_id']));
            return ForceSubscribeUsers::forceSubscribeUsersByOpenidAndChannelId($forceSubscribeUsersPrams['openid'],$officialAccount['distribution_channel_id']);
        }


    }
    
    /**
     * 通过distribution_channel_id和openid获取素材强关映射关系
     */
    static function getMaterialForceSubscribeMapping($distribution_channel_id,$openid)
    {
    	$result = array();
    	$result['uid'] = Redis::hget('book:linksubscribe:openid:'.$openid.':channelid:'.$distribution_channel_id,'uid');
    	$result['time'] = Redis::hget('book:linksubscribe:openid:'.$openid.':channelid:'.$distribution_channel_id,'time');
    	\Log::info('key:'.'book:linksubscribe:openid:'.$openid.':channelid:'.$distribution_channel_id);
    	\Log::info('getMaterialForceSubscribeMapping:distribution_channel_id:'.$distribution_channel_id.' openid:'.$openid.' uid:'.$result['uid'].' time:'.$result['time']);
    	return $result;
    }
    


    /**
    * 获取所有强关用户
    */
    static function forceSubscribeUsersAllOf()
    {

        return ForceSubscribeUsers::forceSubscribeUsersAllOf();
    }

    /**
     * 修改切换的
     */
    static function  updateSubscribeUserTransfer($distribution_channel_id,$uid,$from_appid,$to_appid,$to_openid)
    {
    
    	return ForceSubscribeUsers::updateSubscribeUserTransfer($distribution_channel_id,$uid,$from_appid,$to_appid,$to_openid);
    }
   
    
    /**
	* 通过uid获取强关用户
	*/
    static function forceSubscribeUsersByUid($forceSubscribeUsersPrams)
    {

        return ForceSubscribeUsers::forceSubscribeUsersByUid($forceSubscribeUsersPrams['uid']);
    }
    
    static function allForceSubscribeUsersByUid($forceSubscribeUsersPrams)
    {
    
    	return ForceSubscribeUsers::allForceSubscribeUsersByUid($forceSubscribeUsersPrams['uid']);
    }
    

    /**
     * 根据distribution_channel_id获取强关用户
     */
    static function forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams)
    {
        return ForceSubscribeUsers::forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams['distribution_channel_id'],$forceSubscribeUsersPrams['timeset']);
    }

    /**
     * 获取关注12小时的新用户
     */
    static function forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams)
    {
        return ForceSubscribeUsers::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams['distribution_channel_id'],$forceSubscribeUsersPrams['timeset']);
    }
    
    /**
     * 获取未付费的新关用户24-48小时
     */
    static function forceSubscribeNewUnpaidUsersByTime($forceSubscribeUsersPrams)
    {
    	return ForceSubscribeUsers::forceSubscribeNewUnpaidUsersByTime($forceSubscribeUsersPrams['distribution_channel_id'],$forceSubscribeUsersPrams['start_time'],$forceSubscribeUsersPrams['end_time']);
    }
    
    

    /**
    * 通过uid和appid获取强关用户
    */
    static function forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUsersPrams)
    {

        return ForceSubscribeUsers::forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUsersPrams['uid'],$forceSubscribeUsersPrams['appid'],$forceSubscribeUsersPrams['distribution_channel_id']);
    }

    /**
    * 通过openid获取强关用户
    */
    static function forceSubscribeUsersByOpenid($forceSubscribeUsersPrams)
    {

        return ForceSubscribeUsers::forceSubscribeUsersByOpenid($forceSubscribeUsersPrams['openid']);
    }

    /**
     * 通过openid获取性别
     */
    static function getSexByOpenid($distribution_channel_id,$openid)
    {
    	return ForceSubscribeUsers::getSexByOpenid($distribution_channel_id,$openid);
    }
    
    /**
     * 通过openid获取性别，只根据强关书的性别
     */
    static function getSimpleSexByOpenid($distribution_channel_id,$openid)
    {
    	return ForceSubscribeUsers::getSimpleSexByOpenid($distribution_channel_id,$openid);
    }
    /**
     * 通过uid获取性别，只根据强关书的性别
     */
    static function getSimpleSexByUid($uid)
    {
    	return ForceSubscribeUsers::getSimpleSexByUid($uid);
    }
    

    /**
     * 通过uid获取强关用户 包括取关用户
     */
    static function forceSubscribeUsersByUidIncludeCancel($forceSubscribeUsersPrams){
        return ForceSubscribeUsers::forceSubscribeUsersByUidIncludeCancel($forceSubscribeUsersPrams['uid']);
    }

    /**
    * 通过openid,appid,distribution_channel_id获取强关用户
    */
    static function forceSubscribeUsersByOpenidAndAppidAndChannelId($forceSubscribeUsersPrams)
    {

        return ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($forceSubscribeUsersPrams['openid'],$forceSubscribeUsersPrams['appid'],$forceSubscribeUsersPrams['distribution_channel_id']);
    }
    
    static public function add_subscribe_statistics($uid){
    	try {
    		\Log::info('add_subscribe_statistics_start:'.$uid);
    		$send_data = array(
    				'type' => 'subscribe',
    				'data' => ['openid'=>'','uid'=>$uid]
    		);
    		$send = new \App\Jobs\SendStatisticsList($send_data);
    		$job = ($send)->onConnection('rabbitmq')->delay(0)->onQueue('send_statistics_list');
    		dispatch($job);
    	} catch (\Exception $e) {
    		\Log::info('add_subscribe_statistics_ept:'.$e->getMessage());
    	}
    }


    /**
    * 增加强关用户
    */
    static function addForceSubscribeUsers($forceSubscribeUsersPrams) {

    	try {
            \Log::info('~~~~~~~~~~~~~~~~~~~addForceSubscribeUsers~~~~~~~~~~~~~~~~~~~~'."\n");
            $officialAccount = OfficialAccount::officialAccountByAppid($forceSubscribeUsersPrams['appid']);
            if (!empty($officialAccount)) {
                # code...
                $forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($forceSubscribeUsersPrams['openid'],$forceSubscribeUsersPrams['appid'],$officialAccount['distribution_channel_id']);
                // dd($forceSubscribeUsers);
                if(empty($forceSubscribeUsers)) {
                    // $data = $request->all();
                    $bid = Redis::hget('force_subscribe_from_bid',$forceSubscribeUsersPrams['appid'].'_'.$forceSubscribeUsersPrams['uid']);
                    if (empty($bid)) {
                        # code...
                        $bid = '0';
                    }

                    $sendOrderId = Redis::hget('force_subscribe_from_send_order_id',$forceSubscribeUsersPrams['appid'].'_'.$forceSubscribeUsersPrams['uid']);
                    if (empty($sendOrderId)) {
                        # code...
                        $sendOrderId = '0';
                    }
                    if($bid && $sendOrderId){
                        $send_order_bid = Redis::hget('sendOrderIdToBid',$sendOrderId);
                        if(!$send_order_bid){
                            $send_order_info = SendOrderService::getById($sendOrderId);
                            if($send_order_info){
                                $send_order_bid = $send_order_info->book_id;
                                Redis::hset('sendOrderIdToBid',$sendOrderId,$send_order_bid);
                            }
                        }
                        if($send_order_bid && $bid == $send_order_bid){
                            $key = 'accurateSendOrderSubscribeNum:bid:%s:send_order_id:'.$sendOrderId;
                            Redis::sadd(sprintf($key,$bid),$forceSubscribeUsersPrams['uid']);
                        }
                    }
                    $data['is_subscribed'] = 1;
                    $data['subscribe_time'] = date("Y-m-d H:i:s");
                    $data['last_interactive_time'] = $forceSubscribeUsersPrams['last_interactive_time'];
                    $data['uid'] = $forceSubscribeUsersPrams['uid'];
                    $data['appid'] = $forceSubscribeUsersPrams['appid'];
                    $data['openid'] = $forceSubscribeUsersPrams['openid'];
                    $data['distribution_channel_id'] = $forceSubscribeUsersPrams['distribution_channel_id'];
                    $data['bid'] = $bid;
                    $data['send_order_id'] = $sendOrderId;
                    $data['official_account_id'] = isset($forceSubscribeUsersPrams['official_account_id'])?$forceSubscribeUsersPrams['official_account_id']:0;

                    $forceSubscribeUsers = ForceSubscribeUsers::create($data);
                    //Redis::hset('www.zhuishuyun.com'.'force_subscribe:scene:'.$forceSubscribeUsersPrams['uid'].':'.$forceSubscribeUsersPrams['appid'], 'is_subscribe', '[{is_subscribed:1},{subscribe_time:'.date("Y-m-d H:i:s").'}]');

                    //在Redis中记录一个appid下每天的强关用户数量
                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],date("Y-m-d"),1);
                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],'total',1);


                    // $user['openid'] = $forceSubscribeUsersPrams['openid'];
                    // $user['unionid'] = $forceSubscribeUsersPrams['unionid'];
                    // $user['distribution_channel_id'] = $forceSubscribeUsersPrams['distribution_channel_id'];
                    $user['province'] = isset($forceSubscribeUsersPrams['province']) ? $forceSubscribeUsersPrams['province'] : '';
                    $user['nickname'] = isset($forceSubscribeUsersPrams['nick_name']) ? $forceSubscribeUsersPrams['nick_name'] : '';
                    $user['city'] = isset($forceSubscribeUsersPrams['city']) ? $forceSubscribeUsersPrams['city'] : '';
                    $user['country'] = isset($forceSubscribeUsersPrams['country']) ? $forceSubscribeUsersPrams['country'] : '';
                    $user['head_img'] = isset($forceSubscribeUsersPrams['headimgurl']) ? $forceSubscribeUsersPrams['headimgurl'] : '';
                    $user['sex'] = isset($forceSubscribeUsersPrams['sex']) ? $forceSubscribeUsersPrams['sex'] : '';
                    $user['id'] = isset($forceSubscribeUsersPrams['uid']) ? $forceSubscribeUsersPrams['uid'] : '';

                    \Log::info('~~~~~~~~~~~~~~~~~~~addForceSubscribeUsers~~~~~~~~~~~~~~~~~~~~'."\n");
                    \Log::info($user);

                    UserService::updateInfo($user['id'],$user);
                    // UserService::addUser($user);
                    
                    // 新关统计
                    \Log::info('addForceSubscribeUsers_redis_new:'.$forceSubscribeUsersPrams['uid']);
                    $sub_key = 'gzh_new_sub:'.$forceSubscribeUsersPrams['appid'].':'.date('Y-m-d');
                    Redis::SADD($sub_key,$forceSubscribeUsersPrams['uid']);
                    //Redis::EXPIRE($sub_key,24*3600*3);
                    
                    self::add_subscribe_statistics($forceSubscribeUsersPrams['uid']);
                    
                    return 1;

                } else {
                    $forceSubscribeUsers['is_subscribed'] = 1;
                    $forceSubscribeUsers['subscribe_time'] = date("Y-m-d H:i:s");
                    $forceSubscribeUsers->save();
                    //Redis::hset('www.zhuishuyun.com'.'force_subscribe:scene:'.$forceSubscribeUsersPrams['uid'].':'.$forceSubscribeUsersPrams['appid'], 'is_subscribe', '[{is_subscribed:1},{subscribe_time:'.date("Y-m-d H:i:s").'}]');

                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],date("Y-m-d"),1);
                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],'total',1);

                    // $user['openid'] = $forceSubscribeUsersPrams['openid'];
                    // $user['unionid'] = $forceSubscribeUsersPrams['unionid'];
                    // $user['distribution_channel_id'] = $forceSubscribeUsersPrams['distribution_channel_id'];
                    $user['province'] = isset($forceSubscribeUsersPrams['province']) ? $forceSubscribeUsersPrams['province'] : '';
                    $user['nickname'] = isset($forceSubscribeUsersPrams['nick_name']) ? $forceSubscribeUsersPrams['nick_name'] : '';
                    $user['city'] = isset($forceSubscribeUsersPrams['city']) ? $forceSubscribeUsersPrams['city'] : '';
                    $user['country'] = isset($forceSubscribeUsersPrams['country']) ? $forceSubscribeUsersPrams['country'] : '';
                    $user['head_img'] = isset($forceSubscribeUsersPrams['headimgurl']) ? $forceSubscribeUsersPrams['headimgurl'] : '';
                    $user['sex'] = isset($forceSubscribeUsersPrams['sex']) ? $forceSubscribeUsersPrams['sex'] : '';
                    $user['id'] = isset($forceSubscribeUsersPrams['uid']) ? $forceSubscribeUsersPrams['uid'] : '';

                    \Log::info('~~~~~~~~~~~~~~~~~addForceSubscribeUsers~~~~~~~~~~~~~~~~'."\n");
                    //\Log::info($user);
                    UserService::updateInfo($user['id'],$user);

                    // 老关统计
                    \Log::info('addForceSubscribeUsers_redis_old:'.$forceSubscribeUsersPrams['uid']);
                    $sub_key = 'gzh_old_sub:'.$forceSubscribeUsersPrams['appid'].':'.date('Y-m-d');
                    Redis::SADD($sub_key,$forceSubscribeUsersPrams['uid']);
                    Redis::EXPIRE($sub_key,24*3600*3);
                    
                    self::add_subscribe_statistics($forceSubscribeUsersPrams['uid']);
                    
                    return 1;


                }

            }


    	} catch (\Exception $e) {
            // \Log($e);
            return 0;

    	}

    }

    /**
     * 更新强关用户uid
     */
    static function updateSubscribeUsersUid($forceSubscribeUsersPrams) {
    	try {
    		$forceSubscribeUsers = ForceSubscribeUsers::getOneForceSubscribeUsersByOpenid($forceSubscribeUsersPrams['openid']);
    
    		if(empty($forceSubscribeUsers)) {
    			return 2;
    		} else {
    			\Log::info('updateSubscribeUsersUid,openid'. $forceSubscribeUsersPrams['openid']. ' old_uid:'.$forceSubscribeUsers->uid.' new_uid:'.$forceSubscribeUsersPrams['uid']);
    			$forceSubscribeUsers['uid'] = $forceSubscribeUsersPrams['uid'];
    			$forceSubscribeUsers->save();
    			return 1;
    		}
    
    	} catch (\Exception $e) {
    		\Log::info($e->getMessage());
    		return 0;
    	}
    }

    /**
    * 更新强关用户最后交互时间
    */
    static function forceSubscribeUsersLastTimeUpdate($forceSubscribeUsersPrams) {

    	try {

    		$forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($forceSubscribeUsersPrams['openid'],$forceSubscribeUsersPrams['appid'],$forceSubscribeUsersPrams['distribution_channel_id']);

	        if(empty($forceSubscribeUsers)) {

                 return 2;

	        } else {
	            $forceSubscribeUsers['last_interactive_time'] = $forceSubscribeUsersPrams['last_interactive_time'];
	            $forceSubscribeUsers->save();
	            return 1;
	        }

    	} catch (\Exception $e) {
    		// \Log($e);
            return 0;

    	}


    }
    
    /**
     * 更新强关用户最后交互时间
     */
    static function tempForceSubscribeUsersLastTimeUpdate($forceSubscribeUsersPrams) {
    
    	try {
    		$forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($forceSubscribeUsersPrams['openid'],$forceSubscribeUsersPrams['appid'],$forceSubscribeUsersPrams['distribution_channel_id']);
    		
//     		\Log::info('tempForceSubscribeUsersLastTimeUpdate:'.json_encode($forceSubscribeUsers));
    		if(empty($forceSubscribeUsers)) {
    			\Log::info('empty_origin_update_temp_force_subscribe_user:'.$forceSubscribeUsersPrams['openid']);
    			return 2;
    
    		} else {
    			$tempForceSubscribeUsers = TempForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($forceSubscribeUsersPrams['openid'],$forceSubscribeUsersPrams['appid'],$forceSubscribeUsersPrams['distribution_channel_id']);
    			if(!empty($tempForceSubscribeUsers)){
    				\Log::info('exist_update_temp_force_subscribe_user2:'.$forceSubscribeUsersPrams['openid']);
    				$tempForceSubscribeUsers->last_interactive_time = $forceSubscribeUsers->last_interactive_time;
    				$tempForceSubscribeUsers->bid = $forceSubscribeUsers->bid;
    				$tempForceSubscribeUsers->is_subscribed = $forceSubscribeUsers->is_subscribed;
    				$tempForceSubscribeUsers->subscribe_time = $forceSubscribeUsers->subscribe_time;
    				$tempForceSubscribeUsers->unsubscribe_time = $forceSubscribeUsers->unsubscribe_time;
    				// 跨渠道迁移的bug
    				$tempForceSubscribeUsers->distribution_channel_id = $forceSubscribeUsers->distribution_channel_id;
    				$tempForceSubscribeUsers->uid = $forceSubscribeUsers->uid;
//     				\Log::info('$tempForceSubscribeUsers:'.json_encode($tempForceSubscribeUsers));
    				$tempForceSubscribeUsers->save();
    			} else{
    				$tempForceSubscribeUsers = [
    			       'uid'=>$forceSubscribeUsers->uid,
    				   'openid'=>$forceSubscribeUsers->openid,
    				   'appid'=>$forceSubscribeUsers->appid,
    				   'bid'=>$forceSubscribeUsers->bid,
    				   'is_subscribed'=>$forceSubscribeUsers->is_subscribed,
    				   'subscribe_time'=>$forceSubscribeUsers->subscribe_time,
    				   'unsubscribe_time'=>$forceSubscribeUsers->unsubscribe_time,
    				   'distribution_channel_id'=>$forceSubscribeUsers->distribution_channel_id,
    				   'last_interactive_time'=>$forceSubscribeUsersPrams['last_interactive_time'],
    				];
    				\Log::info('not_exist_create_temp_force_subscribe_user:'.$forceSubscribeUsersPrams['openid']);
    				TempForceSubscribeUsers::firstOrCreate($tempForceSubscribeUsers);
    			}
    			
    			return 1;
    		}
    
    	} catch (\Exception $e) {
    		\Log::info('tempForceSubscribeUsersLastTimeUpdate_ept:'.$e->getMessage());
    		return 0;
    	}
    }

    static function getOfficalAccountNickName($uid)
    {
        return ForceSubscribeUsers::getOfficalAccountNickName($uid);
    }


    /**
    * 强关用户取关
    */
    static function cancelForceSubscribeUsers($forceSubscribeUsersPrams) {

    	try {
    		\Log::info('cancelForceSubscribeUsers_start:'.$forceSubscribeUsersPrams['openid']);

            $forceSubscribeUsers = ForceSubscribeUsers::forceAllSubscribeUsersByOpenid($forceSubscribeUsersPrams['openid']);


            if(count($forceSubscribeUsers)>0) {

                for ($i=0; $i < count($forceSubscribeUsers); $i++) {
                	 
                    # code...
                    $cancelforceSubscribeUsers = $forceSubscribeUsers[$i];
                    $cancelforceSubscribeUsers['is_subscribed'] = 0;
                    $cancelforceSubscribeUsers['unsubscribe_time'] = date("Y-m-d H:i:s");

                    $cancelforceSubscribeUsers->save();
                    
                    \Log::info('cancelForceSubscribeUsers_id:'.$cancelforceSubscribeUsers->id);
                    
                    Redis::hincrby('day_appid_fans_nums_appid:cancel:'.$forceSubscribeUsersPrams['appid'],date("Y-m-d"),1);
                    Redis::hincrby('day_appid_fans_nums_appid:cancel:'.$forceSubscribeUsersPrams['appid'],'total',1);

                    $theCancelForceSubscribeUserArray = $cancelforceSubscribeUsers->toArray();
                    $send_data=array(
                        'type'=>'unsubscribe_user',
                        'data' => $theCancelForceSubscribeUserArray
                    );
                    $delay = 0;
                    $job = (new SendStatisticsList($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_statistics_list');
                    dispatch($job);

                }

                return 1;


            } else {
                return 2;
            }


    	} catch (\Exception $e) {
    		\Log::info('cancelForceSubscribeUsers_ept:'.$e->getMessage());
            return 0;
    	}


    }


    /**
    * 强制关注
    */
    static function subscribeForceSubscribeUsers($forceSubscribeUsersPrams) {

       try {
	       	// 老关统计
	       	\Log::info('subscribeForceSubscribeUsers_redis_old:'.$forceSubscribeUsersPrams['uid']);
	       	$sub_key = 'gzh_old_sub:'.$forceSubscribeUsersPrams['appid'].':'.date('Y-m-d');
	       	Redis::SADD($sub_key,$forceSubscribeUsersPrams['uid']);
	       	Redis::EXPIRE($sub_key,24*3600*3);
	       	
	       	self::add_subscribe_statistics($forceSubscribeUsersPrams['uid']);
       	
            $forceSubscribeUsers = ForceSubscribeUsers::forceAllUnSubscribeUsersByOpenid($forceSubscribeUsersPrams['openid']);
            // \Log::info($forceSubscribeUsers);

            if(count($forceSubscribeUsers)>0) {
                // \Log::info(count($forceSubscribeUsers));
                for ($i=0; $i < count($forceSubscribeUsers); $i++) {
                    # code...
                    // \Log::info($forceSubscribeUsers[$i]['is_subscribed']);
                    // \Log::info($forceSubscribeUsers[$i]['subscribe_time']);
                    $forceSubscribeUsers[$i]['is_subscribed'] = 1;
                    $forceSubscribeUsers[$i]['subscribe_time'] = date("Y-m-d H:i:s");
                    $forceSubscribeUsers[$i]['last_interactive_time'] = date("Y-m-d H:i:s");
                    $forceSubscribeUsers[$i]->save();
                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],date("Y-m-d"),1);
                    Redis::hincrby('day_appid_fans_nums_appid:add:'.$forceSubscribeUsersPrams['appid'],'total',1);
                    //Redis::hset('www.zhuishuyun.com'.'force_subscribe:scene:'.$forceSubscribeUsers[$i]['uid'].':'.$forceSubscribeUsersPrams['appid'], 'is_subscribe', '[{is_subscribed:1},{subscribe_time:'.date("Y-m-d H:i:s").'}]');
                }
                
                return 1;


            } else {
                return 2;
            }



       } catch (\Exception $e) {
            \Log::info('subscribeForceSubscribeUsers_ept:'.$e->getMessage());
            return 0;

       }


    }
    
    /**
     * temp表强制关注
     */
    static function tempSubscribeForceSubscribeUsers($forceSubscribeUsersPrams) {
    
    	try {
    		\Log::info('tempSubscribeForceSubscribeUsers2:'.$forceSubscribeUsersPrams['openid']);
    
    		$forceSubscribeUsers = TempForceSubscribeUsers::forceAllUnSubscribeUsersByOpenid($forceSubscribeUsersPrams['openid']);
    
    		if(count($forceSubscribeUsers)>0) {
    			for ($i=0; $i < count($forceSubscribeUsers); $i++) {
    				$forceSubscribeUsers[$i]['is_subscribed'] = 1;
    				$forceSubscribeUsers[$i]['subscribe_time'] = date("Y-m-d H:i:s");
    				$forceSubscribeUsers[$i]['last_interactive_time'] = date("Y-m-d H:i:s");
    				$forceSubscribeUsers[$i]->save();
    			}
    			return 1;
    
    
    		} else {
    			return 2;
    		}
    	} catch (\Exception $e) {
    		return 0;
    	}
    
    }


    //获取推广带来的净关粉丝总数
    static function getFansNum($send_order_id)
    {
        return ForceSubscribeUsers::getFansNum($send_order_id);
    }

    //获取推广带来的新关粉丝总数
    static function getNewFansNum($send_order_id)
    {
        return ForceSubscribeUsers::getNewFansNum($send_order_id);
    }





    //根据模板消息传的各项条件检索用户
    static function forceUserCountByTemplatePrams($appids,$distribution_channel_id,$subscribe_time,$sex,$balance,$category_id,$order_type,$skip){

        $forceSubscribes = ForceSubscribeUsers::forceUserCountByTemplatePrams($appids,$distribution_channel_id,$subscribe_time,$sex,$balance,$category_id,$order_type,$skip);

        return $forceSubscribes;

    }



    //根据客服消息传的各项条件检索用户
    static function forceUserCountByCustomPrams($appids,$distribution_channel_id,$subscribe_time,$sex,$balance,$category_id,$order_type,$sign_time,$skip,$subscribe_time_attach=''){

        $forceSubscribes = ForceSubscribeUsers::forceUserCountByCustomPrams($appids,$distribution_channel_id,$subscribe_time,$sex,$balance,$category_id,$order_type,$sign_time,$skip,$subscribe_time_attach);

        return $forceSubscribes;

    }
    
    // 指定用户的基础信息获取
    static function simpleForceUserCountByPrams($uids, $param,$skip){
    
    	$forceSubscribes = ForceSubscribeUsers::simpleForceUserCountByPrams($uids, $param,$skip);
    
    	return $forceSubscribes;
    
    }
   



    // 根据渠道号和日期获取强关用户数量
    /**
    * startTime endTime 如果两个参数都传会查询这两个时间段内的的强关用户数量
    * startTime endTime 如果只传一个，则会查询当天的强关用户数量，传哪个都可以
    * startTime endTime 如果都不传， 则会获取该渠道下的所有强关用户数量
    */
    static function forceSubscribeUserCountByChannelIdAndDate($distribution_channel_id,$startTime,$endTime){
         return ForceSubscribeUsers::forceSubscribeUserCountByChannelIdAndDate($distribution_channel_id,$startTime,$endTime);
    }
    
    /**
     * 获取全服务号粉丝
     */
    static function getFullOfficialAccountUsers($appid,$next_openid){
//     	\Log::info('getFullOfficialAccountUsers_start,appid:'.$appid.' next_openid:'.$next_openid);
    	 
    	$result = array();
    	
    	try {
    		$timestamp = time();
    		$params = array("next_openid"=>$next_openid,'gzh_app_id'=>$appid,"timestamp"=>$timestamp);
    		$sign = get_sign($params);
    	
    		$res = self::getUserClient()->request("GET","get_full_official_account_users",
    				['query'=>['next_openid'=>$next_openid,'gzh_app_id'=>$appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
    		)->getBody()->getContents();
//     		\Log::info($res);
    		$res = object_to_array(json_decode($res));
    		 // 组装格式,方便后面统一处理
    		 $openids= isset($res['data']['data']['openid'])?$res['data']['data']['openid']:array();
    		 $result['openids'] = array();
    		 if(!empty($openids)){
    		 	foreach($openids as $key=> $openid){
    		 		$result['openids'][$key]['openid'] = $openid;
    		 	}
    		 }
    		 
    		$result['next_openid'] = isset($res['data']['next_openid'])?$res['data']['next_openid']:'';
    		$result['count'] = isset($res['data']['count'])?$res['data']['count']:0;
    		$result['total'] = isset($res['data']['total'])?$res['data']['total']:0;
    		//\Log::info('getFullOfficialAccountUsers_end,appid:'.$appid.' next_openid:'.$result['next_openid'].' count:'.$result['count'].' total:'.$result['total'].' num:'.count($result['openids']));
    		 
    	} catch (\Exception $e) {
    		\Log::info($e);
    	}

    	return $result;
    }

    /**
     * 获取客服消息有效公众号用户
     */
    static function getCustomActiveOfficialAccountUsers($appid,$next_openid)
    {

        $result = array();

        try {

            $key = 'gzh_custom:openid:'.$appid;
            $start = !$next_openid ? 0 : Redis::zrank($key,$next_openid);
            $end = $start + 10000;

            $total = 0;
            $openids = Redis::zrangebyscore($key,$start,$end);
            $result['openids'] = array();
            if($openids){
                foreach($openids as $key=> $openid){
                    $result['openids'][$key]['openid'] = $openid;
                }
            }

            $result['next_openid'] = 0;
            $result['count'] = count($openids);
            $result['total'] = 100;

        } catch (\Exception $e) {
            \Log::info($e);
        }

        return $result;
    }
    
    /**
     * 获取单个粉丝信息
     */
    static function getUserInfo($appid,$openid){
    	\Log::info('getUserInfo_start,appid:'.$appid.' openid:'.$openid);
    
    	$result = array();
    	 
    	try {
    		$timestamp = time();
    		$params = array("openid"=>$openid,'gzh_app_id'=>$appid,"timestamp"=>$timestamp);
    		$sign = get_sign($params);
    		 
    		$res = self::getUserClient()->request("GET","get_userinfo",
    				['query'=>['openid'=>$openid,'gzh_app_id'=>$appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
    		)->getBody()->getContents();
    		$res = object_to_array(json_decode($res));
    		
    		$result['nickname'] = isset($res['data']['nickname'])?$res['data']['nickname']:0;
    		\Log::info('getUserInfo_end,appid:'.$appid.' openid:'.$openid.' nickname:'.$result['nickname']);
    		 
    	} catch (\Exception $e) {
    		\Log::info('getUserInfo_ept:'.$e->getMessage());
    	}
    
    	return $result;
    }

    static function getUserInfoAll($appid,$openid){
        \Log::info('getUserInfo_start,appid:'.$appid.' openid:'.$openid);

        $result = array();

        try {
            $timestamp = time();
            $params = array("openid"=>$openid,'gzh_app_id'=>$appid,"timestamp"=>$timestamp);
            $sign = get_sign($params);

            $res = self::getUserClient()->request("GET","get_userinfo",
                ['query'=>['openid'=>$openid,'gzh_app_id'=>$appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
            )->getBody()->getContents();
            $res = object_to_array(json_decode($res));
            if(isset($res['data']) && !empty($res['data'])){
                return $res['data'];
            }

        } catch (\Exception $e) {
            \Log::info('getUserInfo_ept:'.$e->getMessage());
        }

        return $result;
    }
    
    /**
     * 占位符替换
     * @param unknown_type $content
     * @param unknown_type $type
     * @return string
     */
    static public function  change_placeholder($content,$params){
    	\Log::info('change_placeholder_before：'.$content);
    	$wx_name = isset($params['nickname'])?$params['nickname']:'';
    	$content = str_replace('{wx_name}',$wx_name,$content);
    	\Log::info('change_placeholder_end：'.$content);
    	return $content;
    }
    
    
    static public function getUserClient(){
    	return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }

    /**
     * 获取派单的枪管用户
     * @param int $send_order_id
     * @param int $distribution_channel_id
     * @return mixed
     */
    static public function getUidByParam(int $send_order_id,int $distribution_channel_id){
        return ForceSubscribeUsers::where('send_order_id',$send_order_id)->where('distribution_channel_id',$distribution_channel_id)->select('uid')->limit(100)->get();
    }
    
    /**
     * 获取云栖迁移的特殊回复
     * @param unknown_type $distribution_channel_id
     * @param unknown_type $openid
     */
    static public function getYqMoveReply($distribution_channel_id,$openid){
    	$text = '';
    	$encode_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
    	// 检查是否第一次
    	$move_user = YqMove::getUser($distribution_channel_id,$openid);
    	// 是否订阅大于50章的用户
    	$is_big_50_user = isset($move_user['read_count']) && $move_user['read_count'] >= 50 ? '1':'0';
    	$yq_distribution_channel_id = isset($move_user['yq_distribution_channel_id']) && $move_user['yq_distribution_channel_id'] ? $move_user['yq_distribution_channel_id']:$distribution_channel_id;
    	$encode_yq_distribution_channel_id = encodeDistributionChannelId($yq_distribution_channel_id);
    	$not_recommend_old_sites = array('4042','4043','4044'); 
    	\Log::info('getYqMoveReply:zsy_distribution_channel_id:'.$distribution_channel_id.' yq_distribution_channel_id:'.$yq_distribution_channel_id.' openid:'.$openid.' is_big_50_user:'.$is_big_50_user);
    	// 已经迁移过用户的文案
    	if(!empty($move_user)){
    		if($is_big_50_user == '0'){
    			$text = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com'>点击进入新站</a>\n\n";
    			$text .= "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com/recent'>点击查看最近阅读</a>";
    		}else{
    			if(in_array($distribution_channel_id,$not_recommend_old_sites)){
    				\Log::info('not_recommend_old_site:'.$distribution_channel_id.' openid:'.$openid);
    				$text = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com'>点击进入新站</a>\n\n";
    				$text .= "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com/recent'>点击查看最近阅读</a>";
    			}else{
    				$text = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com/recent'>追书云：点此进入新站，看海量优质小说</a>\n\n".
    						"<a href='http://site".$encode_yq_distribution_channel_id."."."imycmh".".com/recent'>云栖：点此进入老站继续阅读 </a>\n";
    			}
    		}
    	}
    	// 第一次回复的文案
    	else 
    	{
    		$text = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com'>点击进入新站</a>\n\n";
    		$text .= "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('CUSTOM_HOST').".com/recent'>点击查看最近阅读</a>";
    	}
    	
    	return $text;
    }

    /**
     * @param $distribution_channel
     * 获取老用户关注数
     */
    public static function getOldUserNewSubsribeNum($params){
        return ForceSubscribeUsers::getOldUserNewSubsribeNum($params);
    }

    /**
     * 临时表数据更新 客服消息交互修改后版本
     */
    static function updateTempForceUser($params)
    {
        TempForceSubscribeUsers::updateInfo($params);
    }

    /**
     * 获取强关用户属性
     * @param $openids
     */
    static function getForceUsersNickname($openids = [])
    {
        return ForceSubscribeUserProperty::getForceUsersNickname($openids);
    }


    static function getForceUsersNicknameByOpenid($openid){
        $nick_name_info = ForceSubscribeUserProperty::getForceUsersNicknameByOpenid($openid);
        if($nick_name_info){
            return $nick_name_info->current_nickname;
        }
        return '';
    }
    
}