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

namespace App\Modules\OfficialAccount\Services;

use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\WechatTemplates;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\WechatTemplateMsgs;
use App\Modules\OfficialAccount\Models\CustomSendMsgs;
use App\Modules\OfficialAccount\Models\WechatPublicTemplates;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\OfficialAccount\Models\BatchCustomSendMsgs;
use App\Libs\OSS;
use Redis;
use App\Jobs\SendTemplate;
use GuzzleHttp\Client;
use App\Jobs\TemplateMsgSendJob;


class WechatTemplateService
{

    //-----------模板消息---------------

    /**
    * 通过Appid和common_template_id获取模板
    */
    static function wechatTemplateByAppidAndCommonTemplateId($wechatTemplatePrams)
    {

        return WechatTemplates::wechatTemplateByAppidAndTemplateId($wechatTemplatePrams['appid'],$wechatTemplatePrams['common_template_id']);

    }

    /**
    * wechatTemplateMsgById 通过id获取模板
    */
    static function wechatTemplateMsgById($wechatTemplatePrams)
    {

        return WechatTemplateMsgs::wechatTemplateMsgsById($wechatTemplatePrams['id']);

    }

    /**
    * 获取推送模板消息列表
    */
    static function wechatTemplateMsgBydistributionChannelId($wechatTemplatePrams)
    {

        return WechatTemplateMsgs::wechatTemplateMsgsBydistributionChannelId($wechatTemplatePrams['distribution_channel_id']);

    }

    /**
    * 发送模板消息
    */
    static function add_template_task($wechatTemplateMsgs,$templateMsgs){
       
        try {

            $appid = $wechatTemplateMsgs['appid'];
            $template_id = $wechatTemplateMsgs['template_id'];
            $name = $wechatTemplateMsgs['name'];
            $send_time = $wechatTemplateMsgs['send_time'];
            $template_content = $wechatTemplateMsgs['template_content'];
            \Log::info('================== template_content');
            \Log::info($template_content);
            $redirect_url = $wechatTemplateMsgs['redirect_url'];

            $distribution_channel_id = $wechatTemplateMsgs['distribution_channel_id'];
            $remark = $wechatTemplateMsgs['remark'];
            $task_id = $wechatTemplateMsgs['id'];
            \Log::info('-----------------模板消息参数--------------');
            \Log::info($appid);
            \Log::info($wechatTemplateMsgs['distribution_channel_id']);
            \Log::info($wechatTemplateMsgs['subscribe_time']);
            \Log::info($wechatTemplateMsgs['sex']);
            \Log::info($wechatTemplateMsgs['balance']);
            \Log::info($wechatTemplateMsgs['category_id']);
            \Log::info($wechatTemplateMsgs['order_type']);
            //1,通过筛选得到条件符合的强关用户
            $skip = 0;
            while ( $skip <= 2500000) {
                \Log::info('-------------模板消息-----分页取强关用户，目前页数----------'.$skip);
                $users = ForceSubscribeService::forceUserCountByTemplatePrams($appid,$wechatTemplateMsgs['distribution_channel_id'],$wechatTemplateMsgs['subscribe_time'],$wechatTemplateMsgs['sex'],$wechatTemplateMsgs['balance'],$wechatTemplateMsgs['category_id'],$wechatTemplateMsgs['order_type'],$skip);
                \Log::info('-----------------实际发送模板消息用户数量-------------'.count($users));
                if(count($users)>0){
                    for ($i=0; $i < count($users); $i++) {

                        //2，循环用户发送模板消息
                        //发送到最后一条时，将
                        if ($i == count($users)-1) {

                            $data = array();
                            $data['statusstr'] = (time());
                            $data['openid'] = $users[$i]['openid'];
                            $data['appid'] = $appid;
                            $data['template_id'] = $template_id;

                            $templateSendContents = array();

                            //3，处理前台传过来的json数据，格式化后转成指定格式的数组在json_encode
                            // $templateContentArray = json_decode(str_replace(".DATA","",$template_content),true);
                            // for ($j=0; $j < count($templateContentArray); $j++) {

                            //     $templateSendContents[] = $templateContentArray[$j];

                            // }

                            //4，通过RebitMQ发送模板消息
                            // $data['template_content'] = $templateSendContents;
                            $data['template_content'] =str_replace(".DATA","",$template_content);
                            $data['type'] = 'last_task';// last_task,one_task
                            $data['url'] = $redirect_url;
                            $data['task_id'] = $task_id;
                            $data['send_time'] = $send_time;
                            $send_data=array(
                                'send_time'=>$send_time,
                                'data' => $data
                            );

                            $now_time = strtotime($send_time)-time();
                            \Log::info('------------------！！！发送模板消息时间！！！----------');
                            \Log::info($send_time);
                            \Log::info($now_time);

                            $delay = $now_time;

                            try {
                                \Log::info('------------------发送最后一条模板消息----------'.$task_id);
                                $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_template_list');
                                dispatch($job);
                            } catch (\Exception $e) {
                                \Log::info($e->getMessage());
                            }

                        }else{
                            $data = array();
                            $data['statusstr'] = (time());
                            $data['openid'] = $users[$i]['openid'];
                            $data['appid'] = $appid;
                            $data['template_id'] = $template_id;

                            // $templateSendContents = array();
                            // $templateContentArray = json_decode(str_replace(".DATA","",$template_content),true);
                            // for ($j=0; $j < count($templateContentArray); $j++) {

                            //     $templateSendContents[] = $templateContentArray[$j];

                            // }

                            \Log::info('========================[[[[send template message]]]]====================');
                            \Log::info(str_replace(".DATA","",$template_content));

                            // $data['template_content'] = $templateSendContents;
                            $data['template_content'] =str_replace(".DATA","",$template_content);
                            $data['type'] = 'one_task';// last_task,one_task
                            $data['url'] = $redirect_url;
                            $data['task_id'] = $task_id;
                            $data['send_time'] = $send_time;
                            $send_data=array(
                                'send_time'=>$send_time,
                                'data' => $data
                            );

                            $now_time = strtotime($send_time)-time();
                            \Log::info('------------------！！！发送模板消息时间！！！----------');
                            \Log::info($send_time);
                            \Log::info($now_time);

                            $delay = $now_time;

                    //      v('delay:'.$delay);die();
                            \Log::info('========================发送模板消息2222222===================='.$task_id);
                            \Log::info($data['openid']);
                            try {
                                $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_template_list');
                                dispatch($job);
                            } catch (\Exception $e) {
                                \Log::info($e->getMessage());
                            }
                        }

                    }

                }else{
                    \Log::info('========================发送模板消息_没找到用户===================='.$task_id);
                    break;
                }

                $skip += count($users);
            }

            $templateMsgs['user_num'] = $skip;
            $templateMsgs->save();

            $officialAccountArray = $templateMsgs->toArray();
            Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

//            Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', '[{id:'.$templateMsgs['id'].'},{appid:'.$templateMsgs['appid'].'},{common_template_id:'.$templateMsgs['common_template_id'].'},{name:'.$templateMsgs['name'].'},{send_time:'.$templateMsgs['send_time'].'},{template_content:'.$templateMsgs['template_content'].'},{redirect_url:'.$templateMsgs['redirect_url'].'},{distribution_channel_id:'.$templateMsgs['distribution_channel_id'].'},{remark:'.$templateMsgs['remark'].'},{subscribe_time:'.$templateMsgs['subscribe_time'].'},{sex:'.$templateMsgs['sex'].'},{balance:'.$templateMsgs['balance'].'},{order_type:'.$templateMsgs['order_type'].'},{category_id:'.$templateMsgs['category_id'].'}]');


        } catch (\Exception $e) {
            \Log::info('========================循环用户发送模板消息报错====================');
            \Log::info($e->getMessage());
        }
        
    }


    /**
    * 发送模板消息
    */
    static function addWechatTemplateMsg($wechatTemplatePrams)
    {        

    	try {

            $appids = $wechatTemplatePrams['appid'];
            \Log::info('addWechatTemplateMsg:appid======'.$appids);
            // $wechatTemplatePrams['template_id'] = $wechatTemplatePrams['template_id'];
            // $wechatTemplatePrams['appid'] = $appidArray[$i];
            // $templateMsgs = WechatTemplateMsgs::create($wechatTemplatePrams);
            $appidArray  = explode(',', $appids);

            for ($i=0; $i < count($appidArray); $i++) { 

                $wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($appidArray[$i],$wechatTemplatePrams['common_template_id']);

                if(empty($wechatTemplates)) {
                    \Log::info('addWechatTemplateMsg:======未找到模板');
                    // return 2;
                }else{

                    $isSendTemplate = WechatTemplateMsgs::isSendTemplateAtSameTime($wechatTemplatePrams['distribution_channel_id'],$wechatTemplatePrams['appid'],$wechatTemplatePrams['send_time'],$wechatTemplates['template_id']);
                    if (!empty($isSendTemplate)) {
                        \Log::info('addWechatTemplateMsg已经发送过该模板消息');
                        \Log::info($isSendTemplate['id']);
                        \Log::info($isSendTemplate['template_id']);
                        \Log::info($isSendTemplate['status']);
                        \Log::info($isSendTemplate['del_flag']);
                        return 3;
                    }

                    $wechatTemplatePrams['template_id'] = $wechatTemplates['template_id'];
                    $wechatTemplatePrams['appid'] = $appidArray[$i];
                    $wechatTemplatePrams['status'] = '1';
                    $wechatTemplatePrams['del_flag'] = 0; 
                 
                    $wechatTemplatePrams['user_num'] = 0; 
                    \Log::info('save_wechat_template:======');
                    \Log::info($wechatTemplatePrams);
                    
                    $templateMsgs = WechatTemplateMsgs::create($wechatTemplatePrams);

                    $officialAccountArray = $templateMsgs->toArray();
                    Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));
//                    Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplatePrams['id'].'},{appid:'.$wechatTemplatePrams['appid'].'},{common_template_id:'.$wechatTemplatePrams['common_template_id'].'},{name:'.$wechatTemplatePrams['name'].'},{send_time:'.$wechatTemplatePrams['send_time'].'},{template_content:'.$wechatTemplatePrams['template_content'].'},{redirect_url:'.$wechatTemplatePrams['redirect_url'].'},{distribution_channel_id:'.$wechatTemplatePrams['distribution_channel_id'].'},{remark:'.$wechatTemplatePrams['remark'].'},{subscribe_time:'.$wechatTemplatePrams['subscribe_time'].'},{sex:'.$wechatTemplatePrams['sex'].'},{balance:'.$wechatTemplatePrams['balance'].'},{order_type:'.$wechatTemplatePrams['order_type'].'},{category_id:'.$wechatTemplatePrams['category_id'].'}]');


                    $wechatTemplatePrams['id'] = $templateMsgs['id'];
                    \Log::info('send_template66666666666:======'.$wechatTemplatePrams['template_id']."\n");
//                    WechatTemplateService::add_template_task($wechatTemplatePrams,$templateMsgs);

//                    /**
//                     *  通过Job方式发送模板消息-----queue
//                     */
//                    $job = (new TemplateMsgSendJob($wechatTemplatePrams))->delay(20);
//                    dispatch($job);

                }

            }


            return 1;
    		

    	} catch (\Exception $e) {
    		\Log::info("正式发送模板消息-更新日志：");
            \Log::info($e->getMessage());
            
    		return 0;

    	}

    }


    /**
    * 单个用户测试发送模板消息
    */
    static function testAddWechatTemplateMsg($wechatTemplatePrams)
    {
    	\Log::info('testAddWechatTemplateMsg_start:');
    	\Log::info($wechatTemplatePrams);
    	// 测试链接加上域名
    	$wechatTemplatePrams['redirect_url'] = TemplateCustomSendService::checkAddDomain($wechatTemplatePrams['distribution_channel_id'],$wechatTemplatePrams['redirect_url']);
    	
    	try {

            //1，获取指定的用户
            $appids = $wechatTemplatePrams['appid'];
 
            $appidArray  = explode(',', $appids);

            for ($i=0; $i < count($appidArray); $i++) { 

                $wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($appidArray[$i],$wechatTemplatePrams['common_template_id']);

                if(empty($wechatTemplates)) {
                	\Log::info('testAddWechatTemplateMsg_empty_wechat_template:'.$wechatTemplatePrams['distribution_channel_id']);

                    return 2;
                }else{
                	\Log::info('testAddWechatTemplateMsg_in:'.$wechatTemplatePrams['distribution_channel_id']);
                	 
                    $forceSubscribeUserPram['uid'] = $wechatTemplatePrams['uid'];
                    $forceSubscribeUserPram['appid'] = $appidArray[$i];
                    $forceSubscribeUserPram['distribution_channel_id'] = $wechatTemplatePrams['distribution_channel_id'];
                    
                    $force_user = array();
                    $temp_force_user = ForceSubscribeService::forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUserPram);
                    \Log::info('temp_force_user');\Log::info($temp_force_user);
                    if(count($temp_force_user) == 0){
                    	\Log::info('testAddWechatTemplateMsg_has_no_user:'.$wechatTemplatePrams['uid']);
                    	$direct_user = array('openid'=>$wechatTemplatePrams['uid']);
                    	$force_user[] = $direct_user;
                    }else{
                    	$force_user = $temp_force_user;
                    }
                    \Log::info('force_user');\Log::info($force_user);
                    
                    if (count($force_user)>0) {

                        for ($j=0; $j < count($force_user); $j++) {

                            //2，测试循环用户发送客服消息
                            $data = array();
                            $data['openid'] = $force_user[$j]['openid'];
                            $data['appid'] = $appidArray[$i];
                            $data['template_id'] = $wechatTemplates['template_id'];
                            \Log::info('testAddWechatTemplateMsg_openid:'.$data['openid']);
                            
                            // 此处用户昵称统一从接口拿，兼容openid
                            $nickname = '';
                            try{
                            	$userinfo = ForceSubscribeService::getUserInfo($data['appid'], $data['openid']);
                            	$nickname = isset($userinfo['nickname'])?$userinfo['nickname']:'';
                            }catch(\Exception $e){
                            	\Log::info('testAddWechatTemplateMsg_getuserinfo_ept:openid:'.$data['openid'].' ept:'.$e->getMessage());
                            }
                            
                            \Log::info('change_placeholder openid:'.$data['openid']);
                            // 占位符替换
                            $place_holder_params = array();
                            $place_holder_params['nickname'] = $nickname;
                            $wechatTemplatePrams['template_content'] = ForceSubscribeService::change_placeholder($wechatTemplatePrams['template_content'],$place_holder_params);

                            $data['template_content'] = str_replace(".DATA","",$wechatTemplatePrams['template_content']);
                            $data['url'] = $wechatTemplatePrams['redirect_url'];
                            $data['type'] = 'last_task';
                            $data['task_id'] = 3;
                            $data['send_time'] = date("Y-m-d H:i:s");
                            $send_data=array(
                                'send_time'=>date("Y-m-d H:i:s"),
                                'data' => $data
                            );

                            $delay = 0;
                            \Log::info('========================[[[[test send template message]]]]====================');
                            \Log::info(str_replace(".DATA","",$wechatTemplatePrams['template_content']));
                            $job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_template_list');
                            dispatch($job);
                        }

                        
                    }
                    
                    \Log::info('testAddWechatTemplateMsg_end:'.$wechatTemplatePrams['distribution_channel_id']);
                }
            }
            
            return 1;

	
    	} catch (\Exception $e) {
            \Log::info("测试发送模板消息-更新日志：");
    		\Log::info($e->getMessage());
            
    		return 0;
    	}
    	
    }

    /**
    * 增加模板
    */
    static function addWechatTemplate($wechatTemplatePrams)
    {

    	try {
    		
    		$wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($wechatTemplatePrams['appid'],$wechatTemplatePrams['common_template_id']);

	        if(empty($wechatTemplates)) {
	            
	            $wechatTemplates['appid'] = $wechatTemplatePrams['appid'];
	            $wechatTemplates['common_template_id'] = $wechatTemplatePrams['common_template_id'];
	            $wechatTemplates['template_id'] = $wechatTemplatePrams['template_id'];
	            WechatTemplates::create($wechatTemplates);

	            return 1;

	        }else{
	        	return 2;
	            
	        }

    	} catch (\Exception $e) {
            // \Log("增加模板消息-更新日志：".$e);
    		
    		return 0;

    	} 

    }
   
    /**
     * 更新模板的template_id
     */
    static function updateWechatTemplateId($wechatTemplatePrams)
    {
    	 
    	try {
    
    		$wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($wechatTemplatePrams['appid'],$wechatTemplatePrams['common_template_id']);
    
    		if(!empty($wechatTemplates)) {
    			\Log::info('updateWechatTemplate:old_template_id:'.$wechatTemplates['template_id'].' new_template_id:'.$wechatTemplatePrams['template_id']);
    			// 更新映射模板
    			WechatTemplates::updateWechatTemplateId($wechatTemplatePrams['appid'],$wechatTemplatePrams['common_template_id'],$wechatTemplatePrams['template_id']);
    			 
    			WechatTemplateMsgs::updateWechatTemplateMsgsByTemplateId($wechatTemplatePrams['template_id'],$wechatTemplates['template_id']);
    
    			return 1;
    
    		}else{
    			\Log::info('updateWechatTemplate_false: new_template_id:'.$wechatTemplatePrams['template_id']);
    
    			return 2;
    
    		}
    
    	} catch (\Exception $e) {
    		\Log::info('updateWechatTemplateId,ept::'.$e->getMessage());
    		
    		return 0;
    
    	}
    	return 1;
    
    }

    /**
    * 删除模板消息
    */
    static function delWechatTemplateMsg($wechatTemplatePrams)
    {

        try {

            $task_id = $wechatTemplatePrams['id'];
         
            $wechatTemplateMsgs = WechatTemplateMsgs::wechatTemplateMsgsById($wechatTemplatePrams['id']);

            if(!empty($wechatTemplateMsgs)) {

                if($wechatTemplateMsgs['status'] == '8'){
                    \Log::info('该模板已经在发送状态，不允许编辑'.$wechatTemplatePrams['id']);
                    return 4;
                }

                $wechatTemplateMsgs['status'] = '4';
                $wechatTemplateMsgs['del_flag'] = 1;
                $wechatTemplateMsgs->save();

                $officialAccountArray = $wechatTemplateMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));
//                Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplateMsgs['id'].'},{appid:'.$wechatTemplateMsgs['appid'].'},{common_template_id:'.$wechatTemplateMsgs['common_template_id'].'},{name:'.$wechatTemplateMsgs['name'].'},{send_time:'.$wechatTemplateMsgs['send_time'].'},{template_content:'.$wechatTemplateMsgs['template_content'].'},{redirect_url:'.$wechatTemplateMsgs['redirect_url'].'},{distribution_channel_id:'.$wechatTemplateMsgs['distribution_channel_id'].'},{remark:'.$wechatTemplateMsgs['remark'].'},{subscribe_time:'.$wechatTemplateMsgs['subscribe_time'].'},{sex:'.$wechatTemplateMsgs['sex'].'},{balance:'.$wechatTemplateMsgs['balance'].'},{order_type:'.$wechatTemplateMsgs['order_type'].'},{category_id:'.$wechatTemplateMsgs['category_id'].'}]');

//                $templateMsgsArray = $wechatTemplateMsgs->toArray();
//                Redis::hmset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'],$templateMsgsArray);
                return 1;
            }else{
                return 2;
                
            }     

        } catch (\Exception $e) {
            // \Log("模板消息状态-更新日志：".$e);
            return 0;
        }

    }


    /**
    * 更新模板消息或者客服消息状态（灵杰 wechat 调用）
    */
    static function updateWechatTemplateStatus($wechatTemplatePrams)
    {

    	try {

    		\Log::info('==========================更新 模板消息/客服消息推送状态'.$wechatTemplatePrams['id']);

            $task_id = $wechatTemplatePrams['id'];
            $taskidArray  = explode('_', $task_id);
            if (count($taskidArray)>1) {
                if ($taskidArray[0] == 'custom') {

                    \Log::info('updateWechatTemplateStatus：'.$task_id.' status:'.$wechatTemplatePrams['status']);
                    $customSendMsgs = CustomSendMsgs::customSendMsgsByTaskid($task_id);

                    if(!empty($customSendMsgs)) {
                        $customSendMsgs['status'] = $wechatTemplatePrams['status'];
                        $customSendMsgs->save();
                        $officialAccountArray = $customSendMsgs->toArray();
                        Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));

                        // 如果是智能托管有批次号，更新下批次状态
                        if($customSendMsgs['trusteeship'] == 1 && $wechatTemplatePrams['status'] == 3){
                        	\Log::info('try_update_batch_custom_send_msgs_status:'.$customSendMsgs['id']);
                        	$batchCustomMsg = BatchCustomSendMsgs::batchCustomMsgById($customSendMsgs['batch_no']);
                        	if(isset($batchCustomMsg->status) && $batchCustomMsg->status !=3 ){
                        		\Log::info('update_batch_custom_send_msgs_status:'.$customSendMsgs['id'].' batch_no:'.$customSendMsgs['batch_no']);
                        		BatchCustomSendMsgs::updateBatchCustomSendMsgStatusById($customSendMsgs['batch_no'],3,0);
                        	}else{
                        		\Log::info('already_update_batch_custom_send_msgs_status:'.$customSendMsgs['id'].' batch_no:'.$customSendMsgs['batch_no']);
                        	}
                        }else{
                        	\Log::info('not_update_batch_custom_send_msgs_status:'.$customSendMsgs['id']);
                        }

                        return 1;
                    }else{
                        \Log::info('==========================客服消息 数据未找到'.$task_id);
                        return 2;
                    }
                }
                
            }else{

                \Log::info('==========================模板消息推送'.$task_id);
                $wechatTemplateMsgs = WechatTemplateMsgs::wechatTemplateMsgsById($wechatTemplatePrams['id']);

                if(!empty($wechatTemplateMsgs)) {
                    
                   
                    $wechatTemplateMsgs['status'] = $wechatTemplatePrams['status'];

                    $wechatTemplateMsgs->save();

                    $officialAccountArray = $wechatTemplateMsgs->toArray();
                    Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

//                    Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplateMsgs['id'].'},{appid:'.$wechatTemplateMsgs['appid'].'},{common_template_id:'.$wechatTemplateMsgs['common_template_id'].'},{name:'.$wechatTemplateMsgs['name'].'},{send_time:'.$wechatTemplateMsgs['send_time'].'},{template_content:'.$wechatTemplateMsgs['template_content'].'},{redirect_url:'.$wechatTemplateMsgs['redirect_url'].'},{distribution_channel_id:'.$wechatTemplateMsgs['distribution_channel_id'].'},{remark:'.$wechatTemplateMsgs['remark'].'},{subscribe_time:'.$wechatTemplateMsgs['subscribe_time'].'},{sex:'.$wechatTemplateMsgs['sex'].'},{balance:'.$wechatTemplateMsgs['balance'].'},{order_type:'.$wechatTemplateMsgs['order_type'].'},{category_id:'.$wechatTemplateMsgs['category_id'].'}]');


                    return 1;
                }else{
                    \Log::info('==========================模板消息 数据未找到'.$task_id);
                    return 2;
                }

            }

    		

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

    }


    /**
     * 更新模板消息状态（南哥）
     */
    static function wechatTemplateStatusChange($wechatTemplatePrams)
    {

        try {

            \Log::info('==========================修改 模板消息发送状态'.$wechatTemplatePrams['id']);

            $task_id = $wechatTemplatePrams['id'];

            $wechatTemplateMsgs = WechatTemplateMsgs::wechatTemplateMsgsById($wechatTemplatePrams['id']);

            if(!empty($wechatTemplateMsgs)) {

                if($wechatTemplateMsgs['status'] == '8'){
                    \Log::info('该模板已经在发送状态，不允许编辑'.$wechatTemplatePrams['id']);
                    return 4;
                }

                $wechatTemplateMsgs['status'] = $wechatTemplatePrams['status'];

                $wechatTemplateMsgs->save();

                $officialAccountArray = $wechatTemplateMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

//                    Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplateMsgs['id'].'},{appid:'.$wechatTemplateMsgs['appid'].'},{common_template_id:'.$wechatTemplateMsgs['common_template_id'].'},{name:'.$wechatTemplateMsgs['name'].'},{send_time:'.$wechatTemplateMsgs['send_time'].'},{template_content:'.$wechatTemplateMsgs['template_content'].'},{redirect_url:'.$wechatTemplateMsgs['redirect_url'].'},{distribution_channel_id:'.$wechatTemplateMsgs['distribution_channel_id'].'},{remark:'.$wechatTemplateMsgs['remark'].'},{subscribe_time:'.$wechatTemplateMsgs['subscribe_time'].'},{sex:'.$wechatTemplateMsgs['sex'].'},{balance:'.$wechatTemplateMsgs['balance'].'},{order_type:'.$wechatTemplateMsgs['order_type'].'},{category_id:'.$wechatTemplateMsgs['category_id'].'}]');


                return 1;
            }else{

                \Log::info('==========================模板消息 数据未找到'.$task_id);
                return 2;

            }

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

    }


    //判断1小时内是否有相同的模板消息插入过
    static function isSendTemplateAtSameTime($wechatTemplatePrams){

        return WechatTemplateMsgs::isSendTemplateAtSameTime($wechatTemplatePrams['distribution_channel_id'],$wechatTemplatePrams['appid'],$wechatTemplatePrams['send_time'],$wechatTemplatePrams['template_id']);

    }


    /**
    * 更新模板消息内容
    */
    static function updateWechatTemplateMsgById($wechatTemplatePrams)
    {

    	try {

    		$wechatTemplateMsgs = WechatTemplateMsgs::wechatTemplateMsgsById($wechatTemplatePrams['id']);

	        if(!empty($wechatTemplateMsgs)) {

	            if($wechatTemplateMsgs['status'] == '8'){
                    \Log::info('该模板已经在发送状态，不允许编辑'.$wechatTemplatePrams['id']);
                    return 4;
                }
                //先停止原来的模板，然后删除
				$wechatTemplateMsgs['status'] = '4';
                $wechatTemplateMsgs['del_flag'] = 1;
                $wechatTemplateMsgs->save();

                $officialAccountArray = $wechatTemplateMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

//                Redis::hset('send_wechat_msg:task_id:'.$wechatTemplateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplateMsgs['id'].'},{appid:'.$wechatTemplateMsgs['appid'].'},{common_template_id:'.$wechatTemplateMsgs['common_template_id'].'},{name:'.$wechatTemplateMsgs['name'].'},{send_time:'.$wechatTemplateMsgs['send_time'].'},{template_content:'.$wechatTemplateMsgs['template_content'].'},{redirect_url:'.$wechatTemplateMsgs['redirect_url'].'},{distribution_channel_id:'.$wechatTemplateMsgs['distribution_channel_id'].'},{remark:'.$wechatTemplateMsgs['remark'].'},{subscribe_time:'.$wechatTemplateMsgs['subscribe_time'].'},{sex:'.$wechatTemplateMsgs['sex'].'},{balance:'.$wechatTemplateMsgs['balance'].'},{order_type:'.$wechatTemplateMsgs['order_type'].'},{category_id:'.$wechatTemplateMsgs['category_id'].'}]');


                //创建新的模板
                $appids = $wechatTemplatePrams['appid'];
               
                $appidArray  = explode(',', $appids);

                for ($i=0; $i < count($appidArray); $i++) { 

                    $wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($appidArray[$i],$wechatTemplatePrams['common_template_id']);

                    if(empty($wechatTemplates)) {
  
                    }else{
                        $wechatTemplatePrams['template_id'] = $wechatTemplates['template_id'];
                        $wechatTemplatePrams['appid'] = $appidArray[$i];  
                        // $users = ForceSubscribeService::forceUserCountByTemplatePrams($appidArray[$i],$wechatTemplatePrams['distribution_channel_id'],$wechatTemplatePrams['subscribe_time'],$wechatTemplatePrams['sex'],$wechatTemplatePrams['balance'],$wechatTemplatePrams['category_id'],$wechatTemplatePrams['order_type']);
                        $isSendTemplate = WechatTemplateMsgs::isSendTemplateAtSameTime($wechatTemplatePrams['distribution_channel_id'],$wechatTemplatePrams['appid'],$wechatTemplatePrams['send_time'],$wechatTemplates['template_id']);
                        if (!empty($isSendTemplate)) {
                            \Log::info('已经发送过该模板消息');
                            \Log::info($isSendTemplate['id']);
                            \Log::info($isSendTemplate['template_id']);
                            \Log::info($isSendTemplate['status']);
                            \Log::info($isSendTemplate['del_flag']);
                            return 3;
                        }


                        $skip = 0;
                        $userCount = 0;
                        $wechatTemplatePrams['status'] = '1';
                        $wechatTemplatePrams['user_num'] = 0;    

                        $wechatTemplatePrams['del_flag'] = 0;            
                        $templateMsgs = WechatTemplateMsgs::create($wechatTemplatePrams);
                        $wechatTemplatePrams['id'] = $templateMsgs['id'];
//                        $templateMsgsArray = $templateMsgs->toArray();
//                        Redis::hmset('send_wechat_msg:task_id:'.$templateMsgs['id'],$templateMsgsArray);

                        $officialAccountArray = $templateMsgs->toArray();
                        Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

//                        Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', '[{id:'.$wechatTemplatePrams['id'].'},{appid:'.$wechatTemplatePrams['appid'].'},{common_template_id:'.$wechatTemplatePrams['common_template_id'].'},{name:'.$wechatTemplatePrams['name'].'},{send_time:'.$wechatTemplatePrams['send_time'].'},{template_content:'.$wechatTemplatePrams['template_content'].'},{redirect_url:'.$wechatTemplatePrams['redirect_url'].'},{distribution_channel_id:'.$wechatTemplatePrams['distribution_channel_id'].'},{remark:'.$wechatTemplatePrams['remark'].'},{subscribe_time:'.$wechatTemplatePrams['subscribe_time'].'},{sex:'.$wechatTemplatePrams['sex'].'},{balance:'.$wechatTemplatePrams['balance'].'},{order_type:'.$wechatTemplatePrams['order_type'].'},{category_id:'.$wechatTemplatePrams['category_id'].'}]');

//                        WechatTemplateService::add_template_task($wechatTemplatePrams,$templateMsgs);

//                        /**
//                         *  通过Job方式发送模板消息-----queue
//                         */
//                        $job = (new TemplateMsgSendJob($wechatTemplatePrams))->delay(20);
//                        dispatch($job);

                    }

                }

	            return 1;
	        }else{
	            
	            return 2;
	        }
    		
    	} catch (\Exception $e) {
            // \Log("模板消息-更新日志：".$e);
    		return 0;
    		
    	}   
    }  


    /**
    * 获取微信公告模板
    */
    static function wechatPublicTemplateList()
    {

        return WechatPublicTemplates::wechatPublicTemplateList();

    }
    
    /**
     * 搜索
     */
    static function searchWechatTemplateMsgs($param,$is_all=false)
    {
    
    	return WechatTemplateMsgs::searchWechatTemplateMsgs($param,$is_all);
    
    }

    /**
     * 检测模板状态
     * 1、正常使用
     * 2、检测异常，已修复请重试
     * 3、模板被封，请等待解封
     * 4、模板分类错误，请修改分类至(IT科技->IT软件与服务、文体娱乐->文化|传媒),然后重新授权后再重试
     */
    static function checkTemplateStatus($appids,$common_template_id)
    {
    
    	$result = ['code'=>1,'msg'=>''];

    	if(!empty($appids)){
    		foreach($appids as $appid){
    			try {
    				$timestamp = time();
    				$params = array('gzh_app_id' => $appid,'common_template_id'=>$common_template_id, "timestamp" => $timestamp);
    				$sign = get_sign($params);
    				 
    				$resJson = self::getUserClient()->request("POST", "check_template_status",
    						['query' => ['gzh_app_id' => $appid,'common_template_id'=>$common_template_id, 'timestamp' => $timestamp, 'sign' => $sign], 'connect_timeout' => 10]
    				)->getBody()->getContents();
    				$resJson = object_to_array(json_decode($resJson));
    				\Log::info('check_template_status_end,appid:'.$appid.' common_template_id:'.$common_template_id);
    				\Log::info($resJson);
    				 $result = [
    					   'code'=>$resJson['code'],
    					   'msg'=>$resJson['msg']
    				  ];
    			} catch (\Exception $e) {
    				$result = [
	    				'code'=>0,
	    				'msg'=>'测试请求异常，请稍后重试'
    				];
    				\Log::info('checkTemplateStatus_ept:'.$e->getMessage());
    			}
    		}
    	}
    	
    	\Log::info('check_template_status_end:'.json_encode($result));
    	return $result;
    }
    
    static function getUserClient()
    {
    	return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }
}