<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Telegram\Bot\Api;
use App\Models\Telegram\TelegramBotAd;
use App\Models\Transit\TransitWalletCoin;

class SendTgMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SendTgMessage:notice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时tg消息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $time = now();
        
        $data = TelegramBotAd::from('telegram_bot_ad as a')
                ->Join('telegram_bot as b','a.bot_rid','b.rid')
                ->where('a.status',0)
                ->select('a.rid','b.bot_token','a.last_notice_time','a.notice_cycle','a.notice_obj','a.notice_ad','a.bot_rid','a.notice_photo')
                ->get();
                
        if($data->count() > 0){
            foreach ($data as $k => $v) {
                //通知周期:1每分钟,2每10分钟,3每30分钟,4每小时,5每天
                $notice_cycle = $v->notice_cycle;
                
                $send = 'N';
                
                //每分钟,且上次通知已过了一分钟
                if($notice_cycle == 1 && strtotime($v->last_notice_time) + 60 <= strtotime($time)){
                    $send = 'Y';
                //每10分钟
                }elseif($notice_cycle == 2 && strtotime($v->last_notice_time) + 600 <= strtotime($time)){
                    $send = 'Y';
                //每30分钟
                }elseif($notice_cycle == 3 && strtotime($v->last_notice_time) + 1800 <= strtotime($time)){
                    $send = 'Y';
                //每小时
                }elseif($notice_cycle == 4 && strtotime($v->last_notice_time) + 3600 <= strtotime($time)){
                    $send = 'Y';
                //每天
                }elseif($notice_cycle == 5 && strtotime($v->last_notice_time) + 86400 <= strtotime($time)){
                    $send = 'Y';
                }
                
                //添加联系老板
                //内联按钮
                $keyboard = [
                    'inline_keyboard' => [
                        [
                            ['text' => '联系老板', 'callback_data' => '客服']
                        ]
                    ]
                ];
                
                $encodedKeyboard = json_encode($keyboard);
                
                #过了周期
                if($send == 'Y'){
                    $save_data = [];
                    $save_data['last_notice_time'] = $time;
                    TelegramBotAd::where('rid',$v->rid)->update($save_data);
                    
                    $bot_token = $v->bot_token;
                    $notice_obj = $v->notice_obj; #多个逗号隔开
                    
                    $telegram = new Api($bot_token);
                    
                    //定时通知的消息
                    $replytext = $v->notice_ad;
                    $replyphoto = $v->notice_photo;
                    
                    if (strpos($replytext, 'trxusdtrate') !== false || strpos($replytext, 'trxusdtwallet') !== false) {
                        //替换变量
                        $walletcoin = TransitWalletCoin::from('transit_wallet_coin as a')
                                    ->join('transit_wallet as b','a.transit_wallet_id','b.rid')
                                    ->where('b.bot_rid', $v->bot_rid)
                                    ->where('in_coin_name','usdt')
                                    ->where('out_coin_name','trx')
                                    ->select('a.exchange_rate','b.receive_wallet')
                                    ->first();
                        if(!empty($walletcoin)){
                            $paraData = [
                                'trxusdtrate' => $walletcoin->exchange_rate,
                                'trxusdtwallet' => $walletcoin->receive_wallet
                            ];
                            
                            //检查参数是否匹配
                            preg_match_all('/\${.*?}/', $replytext, $matches);
                            $params = $matches[0];
                            $values = [];
                            foreach ($params as $param) {
                                $key = str_replace(['${', '}'], '', $param);
                                $values[$param] = $paraData[$key];
                            }
                     
                            $replytext = strtr($replytext, $values);
                            //替换结束
                        }
                    }
                    
                    $receivelist = explode(',',$notice_obj);
            
                    foreach ($receivelist as $x => $y) {
                        if(!empty($replyphoto)){
                            $response = $telegram->sendPhoto([
                                'chat_id' => $y, 
                                'photo' => $replyphoto,
                                'caption' => $replytext,
                                'parse_mode' => 'HTML',
                                'reply_markup' => $encodedKeyboard
                            ]);
                        }else{
                            $response = $telegram->sendMessage([
                                'chat_id' => $y, 
                                'text' => $replytext,
                                'parse_mode' => 'HTML',
                                'reply_markup' => $encodedKeyboard
                            ]);
                        }
                    }
                }
            }
        }
    }
}