<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use Illuminate\Support\Facades\Redis;

class WechatGroupGzh extends Model
{
    protected $table = 'wechat_group_gzhs';
    protected $guarded = ['id'];
   
    static function getAllList()
    {
    	$all = self::all();

    	return $all;
    }
    
    static function save_group_gzh($insert_data){
    	$origin_group_gzh = self::get_group_gzh($insert_data['appid'],$insert_data['group_nick']);
//     	v('$origin_group_gzh');v($origin_group_gzh);
    	if(empty($origin_group_gzh)){
    		v('group_gzh_not_exist:'.$insert_data['appid']);
    		$data = array();
    		$data['group_nick'] = isset($insert_data['group_nick'])?$insert_data['group_nick']:'';
    		$data['appid'] = isset($insert_data['appid'])?$insert_data['appid']:'';
    		$data['status'] = 1;
    		v('save_data');v($data);
    		$result = self::firstOrCreate($data);
    		return $result;
    	}else{
    		v('group_gzh_exist:'.$insert_data['appid']);
    	}
    }
    
    static function get_group_gzh($appid,$group_nick){
    	$group_gzh = self::where('appid',$appid)->where('group_nick',$group_nick)->first();
    	return $group_gzh;
    }
    
    static function get_wechat_group_gzh($appid){
        // 从redis取
    	$redis_group_gzh = Redis::get('wechat_group_gzh:appid:'.$appid);
    	$group_gzh = '';
    	if(!empty($redis_group_gzh)){
    		$group_gzh = json_decode($redis_group_gzh);
    	}else{
    		$group_gzh = self::where('appid',$appid)->where('status',1)->first();
    		v('redis_group_gzh_set:'.$appid);
    		// 重要判断，否则新号有bug
    		if(!empty($group_gzh)){
    			Redis::set('wechat_group_gzh:appid:'.$appid,json_encode($group_gzh));
    		}
    	}
    	$group_nick = isset($group_gzh->group_nick)?$group_gzh->group_nick:'';
    	$result = array('group'=>null,'group_api'=>null);
    	if(!empty($group_gzh)){
    		$group = Redis::get('wechat_group:group_nick:'.$group_nick);
    		if(empty($group)){
    			$group = WechatGroup::get_group($group_nick);
    			Redis::set('wechat_group:group_nick:'.$group_nick,json_encode($group));
    			v('redis_group_set:'.json_encode($group));
    		}else{
    			$group = objectToArray(json_decode($group));
    		}
    		
    		$group_api = Redis::get('wechat_group_api:group_nick:'.$group_nick);
    		if(empty($group_api)){
    			$group_api = WechatGroupApi::get_group_api($group_nick);
    			Redis::set('wechat_group_api:group_nick:'.$group_nick,json_encode($group_api));
    			v('redis_group_api_set:'.json_encode($group_api));
    		}else{
    			$group_api = objectToArray(json_decode($group_api));
    		}
    		
    		$result['group'] = $group;
    		$result['group_api'] = $group_api;
    	}
//     	$result['group']['domain'] = 'http://api.zsy.com/api/';
//     	v('$get_wechat_group_gzh');v($result);
    	return $result;
    }
    
}
