<?php

namespace App\Http\Controllers\Wechat\Staff;

use App\Http\Models\OfficialAccount;

use App\Http\Requests;
use App\Http\Controllers\WechatController;
use App\Http\Controllers\Wechat\Staff\StaffsController;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use EasyWeChat\Foundation\Application;
use App\Http\Models\WechatUser;
use App\Http\Models\WechatTemplateSendInfo;
use App\Http\Models\WechatTemplateTask;
use App\Http\Models\WechatTemplateOfficialInfo;
use Redis;


/**
 * 自定义消息定时发送类
 * @author zhoulingjie
 *
 */
class TextsWorksController extends WechatController
{
    
    public function __construct($template_info)
    {
    	$this->template_info = $template_info;
//     	v('$template_info');v($this->template_info);
    	$this->gzh_app_id = isset($this->template_info['appid'])?$this->template_info['appid']:'';
    	if(!empty($this->gzh_app_id)){
    		parent::__construct($this->gzh_app_id);
    		$this->Staff = new StaffsController($this->param);
    	}else{
    		v('template_work_appid is null');
    	}
    	$this->error_msg = '';
    }
    
    /**
     * 执行模板消息
     */
    public function do_work()
    {
    	if(empty($this->gzh_app_id)) return false;
    	v('do_work_start_text');
    	
    	// 检查表数据
    	$openid = $this->template_info['openid'];
    	$appid = $this->template_info['appid'];
    	$task_id = $this->template_info['task_id'];
    	$type = $this->template_info['type'];
    	$content = $this->template_info['content'];
    	if(empty($openid) || empty($task_id) || empty($content)){
    		v('invalid_null_task_id:'.$task_id.' openid:'.$openid);
    		return false;
    	}
    	
    	$template_task = $this->WechatApi->get_template_task($task_id);
    	$status = isset($template_task['status']) ? $template_task['status']:'';
    	v('task_id:'.$task_id.' status:'.$status);
    	if($status == 4){
    		v('task_id_close:'.$task_id);
    		return false;
    	}
    
    	$this->send_one_template($openid,$content,$task_id);
    	
    	if($type == 'last_task' && $status != 3){
    		v('update_text_task_status:'.$task_id);
    		$status = 3;
    		$this->WechatApi->update_template_task_status($task_id, $status, $this->error_msg);
    	}

    	v('update_text_task_end:'.$task_id);

    }
    
    function send_one_template($openid,$content,$task_id=''){
    	try{
    		v('send_text_to_openid:'.$openid);
//     		v('content:');v($content);

    		$result = $this->param['app']->staff->message($content)->to($openid)->send();
            if($task_id && is_object($result) && isset($result->errcode) && $result->errcode == 0)
            {
                Redis::sadd('cus_ok:'.$task_id,$openid);//记录真正发送成功数
            }
//     		v('send_text_result');v($result);
    	}
    	// 加上\ 全局抓取
    	catch(\Exception $e){
    		v('send_openid_ept:'.$openid.' info:'.$e->getMessage());
    		$this->error_msg = $e->getMessage();
    	}
    }
  
    
}