<?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;
					// 		}
					// 	}
					// }
					if(in_array($et['user_id'],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();
				}
			}
		}
		//执行 客户群群发 定时任务
		$this->groupMsgTask();
		return 'success';
	}

	private function groupMsgTask(){
        $msgGroupTask = (new Model('qy_et_group_msg_task'))->where(['send_mode'=>2,'status'=>3])->list_all();
        foreach ($msgGroupTask as $task){
            if(time() >= strtotime($task->timing_time)){
                $QyWechatApi = QyWechatApi::getInstance();
                $qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$task->wid]);
                $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
                //先改变成发送中
                $task->status = 0;
                $task->save();
                //开始发送
                //1.因为会有多个群主，循环创建群发任务
                $userWhere['id'] = json_decode($task->owner,1);
                $qyUser = new Model('qy_user_list');
                $owners =  $qyUser->where($userWhere)->list_all();
                foreach ($owners as $u) {
                    //给每一个群主创建群发任务
                    $msg = [];
                    $msg['chat_type'] = 'group';
                    $msg['sender'] = $u->userid;
                    $msg['text'] = ['content'=>$task->text_content];
                    if($task->other_type == 2){//图片
                        //$image_url_arr = explode("/", $msgTemplate->image_url);
                        //$image_media_id = $etApp->media->uploadImage("./tmpImg/{$image_url_arr[count($image_url_arr)-1]}")["media_id"];
                        $msg['image'] = ['media_id'=>$etApp->media->uploadImage($task->image_url)['media_id']];
                    }elseif($task->other_type == 3){//图文
                        $msg['link'] = [
                            'title'=>$task->link_title,
                            'picurl'=>$task->link_picurl,
                            'desc'=>$task->link_desc,
                            'url'=>$task->link_url
                        ];
                    }elseif($task->other_type == 4){//小程序
                        //$miniprogram_pic_arr = explode("/", $msgTemplate->miniprogram_picurl);
                        //$miniprogram_pic_media_id = $etApp->media->uploadImage("./tmpImg/{$miniprogram_pic_arr[count($miniprogram_pic_arr)-1]}")["media_id"];
                        $msg['miniprogram'] = [
                            'title'=>$task->miniprogram_title,
                            'pic_media_id'=>$etApp->media->uploadImage($task->miniprogram_picurl)['media_id'],
                            'appid'=>$task->miniprogram_appid,
                            'page'=>$task->miniprogram_page
                        ];
                    }
                    $messageRes = $etApp->external_contact_message->submit($msg);
                    if($messageRes['errcode'] == 0){
                        $task->status = 1;
                        $task->save();
                        if($messageRes['msgid']){
                            $taskDetail =  new Model('qy_et_group_msg_detail');
                            $taskDetail->wid = $task->wid;
                            $taskDetail->gtid = $task->id;
                            $taskDetail->owner = $u->id;
                            $taskDetail->msgid = $messageRes['msgid'];
                            $taskDetail->result = '';
                            $taskDetail->ctime = date('Y-m-d H:i:s');
                            $taskDetail->save();
                        }
                    }else{
                        $task->status = 2;
                        $task->save();
                    }
                }
            }
        }
    }
}