<?php

namespace App\Console\Commands\CustomMsg;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Modules\OfficialAccount\Models\CustomMsgStrategy;
use Illuminate\Console\Command;
use DB;
class CustomMsgStrategyAutoSend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auth_send_custom_msg_by_strategy';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '根据客服消息策略生成客服消息';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //每个小时跑一次,对应这个小时内所有需要发的内容，生成客服消息
        $hour_begin = date('H:00:00');
        $hour_end = date('H:59:59');
        $strategies = CustomMsgStrategy::whereNull('deleted_at')
            ->where('status',1)
            ->where(function ($query) {
                $query->where('last_send_date','<',date('Y-m-d 00:00:00'))
                    ->orWhereNull('last_send_date');
            })
            ->whereBetween('send_time',[$hour_begin,$hour_end])
            ->select([
                'id',
                'appid',
                'name',
                'send_time',
                'content',
                'description',
                'book_name',
                'chapter_name',
                'redirect_url',
                'subscribe_time',
                'sex',
                'balance',
                'order_type',
                'category_id',
                'is_full_send',
                'distribution_channel_id',
                'status',
                'batch_order_sn',
                'custom_type',
            ])
            ->get()
        ;
        $strategies = json_decode(json_encode($strategies), true);
        foreach ($strategies as $strategy){
            $strategy['status']=1;
            $strategy_id = $strategy['id'];
            unset($strategy['id']);
            $strategy['send_time']=date('Y-m-d ').$strategy['send_time'];
            //先判断在发送时间段1小时以内，有没有发起过相同的模板消息，如果有发送过，就提示用户已经创建过相同模板消息，不创建新的模板消息
            $isSendCustomer = CustomMsgService::isSendCustomerAtSameTime($strategy);
            if (!empty($isSendCustomer)) {
                \Log::info('isSendCustomerAtSameTime:' . $strategy['distribution_channel_id']);
            } else {
                CustomMsgStrategy::where('id',$strategy_id)->update(['last_send_date' => date('Y-m-d H:i:s')]);
                $customMsgService = CustomMsgService::addCustomSendMsgs($strategy);


            }
        }


    }
}
