<?php
namespace Addons\QyWechat\Controller\Api\Qy;
use Models\BaseModel as Model;
use Addons\QyWechat\Services\QyWechatApi;

class TimingAddMsgTemplate extends \BaseController
{
	public function index(){
		$msgTemplates=(new Model('qy_et_msg_template'))->where(['send_mode'=>2,'status'=>0])->list_all();
		foreach($msgTemplates as $msgTemplate){
			if(time() >= strtotime($msgTemplate->timing_time)){
				$QyWechatApi = QyWechatApi::getInstance();
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$msgTemplate->wid]);
				$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
				
				$externalcontact = (new Model('qy_externalcontact_list'))->where(['wid'=>$msgTemplate->wid])->list_all_array();
				$external_userids = [];
				if($msgTemplate->send_to == 1){
					foreach($externalcontact as $et){
						$external_userids[] = $et['external_userid'];
					}
				}elseif($msgTemplate->send_to == 2){
					foreach($externalcontact as $et){
						if(array_intersect(json_decode($et['tags'],1),json_decode($msgTemplate->send_tag,1))){
							$external_userids[] = $et['external_userid'];
						}
					}
				}elseif($msgTemplate->send_to == 3){
					foreach($externalcontact as $et){
						$follow_user = json_decode($et['follow_user'],1);
						foreach($follow_user as $user){
							if(in_array($user['userid'],json_decode($msgTemplate->send_user,1))){
								$external_userids[] = $et['external_userid'];
								break;
							}
						}
					}
				}
				
				$msg['external_userid'] = $external_userids;
				$msg['text'] = ['content'=>$msgTemplate->text_content];
				if($msgTemplate->other_type == 2){//图片
					$msg['image'] = ['media_id'=>$etApp->media->uploadImage($msgTemplate->image_url)['media_id']];
				}elseif($msgTemplate->other_type == 3){//图文
					$msg['link'] = [
						'title'=>$msgTemplate->link_title,
						'picurl'=>$msgTemplate->link_picurl,
						'desc'=>$msgTemplate->link_desc,
						'url'=>$msgTemplate->link_url
					];
				}elseif($msgTemplate->other_type == 4){//小程序
					$msg['miniprogram'] = [
						'title'=>$msgTemplate->miniprogram_title,
						'pic_media_id'=>$etApp->media->uploadImage($msgTemplate->miniprogram_picurl)['media_id'],
						'appid'=>$msgTemplate->miniprogram_appid,
						'page'=>$msgTemplate->miniprogram_page
					];
				}
					
				$messageRes = $etApp->external_contact_message->submit($msg);
				if($messageRes['errcode'] == 0){
					$msgTemplate->status = 1;
					$msgTemplate->save();
				}else{
					$msgTemplate->status = 2;
					$msgTemplate->save();
				}
			}
		}
		return 'success';
	}
}