<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\OfficialAccount\Services\BatchCustomMsgService;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Models\CustomMsgSendTimeConfig;
use DB;
class AutoSendTrusteeShipCustomerMsg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AutoSendTrusteeShipCustomerMsg';

    /**
     * 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
     */

    private $hour_begin;
    private $hour_end;

    public function handle()
    {
        $this->hour_begin = date('H:00:00');
        $this->hour_end = date('H:59:59');
        $batch_no =  '默认批次';
        //所有开启推送的渠道
        $all_channel_ids = DB::table('custom_msg_switchs_msgs')
            ->where('status',1)
            ->where('custom_category','auto_custom_trusteeship')
            ->select(DB::raw("distinct distribution_channel_id as unique_distribution_channel_id"))
            ->pluck('unique_distribution_channel_id')
            ->toArray();

        //自定义时间的渠道
        $customize_time_channel_ids = CustomMsgSendTimeConfig::where('is_enable',1)
            ->where('custom_category','auto_custom_trusteeship')
            ->whereIn('distribution_channel_id',$all_channel_ids)
            ->select(DB::raw("distinct distribution_channel_id as unique_distribution_channel_id"))
            ->pluck('unique_distribution_channel_id')
            ->toArray();

        //获取没有自定义发送时间的站点19点统一发送
        if($this->hour_begin == '19:00:00'){
            //判断今天是否已经发送过
            $today_send_status = DB::table('batch_custom_send_msgs')
                ->where('send_time','>',date('Y-m-d'))
                ->where('name','like','%'.$batch_no.'%')
                ->first();
            if(!$today_send_status){

                //需要跑的站点=  所有开启推送的站点 - 自定义时间的站点
                $channel_ids = array_diff($all_channel_ids,$customize_time_channel_ids);
                dump($batch_no);
                $this->autoSendTrusteeShipCustomerMsg($channel_ids,$batch_no);
            }

        }

        //获取有自定义发送时间且在一小时内需要创建的站点
        $channel_ids = CustomMsgSendTimeConfig::where('is_enable',1)
            ->where('custom_category','auto_custom_trusteeship')
            ->whereBetween('send_time',[$this->hour_begin,$this->hour_end])
            ->whereIn('distribution_channel_id',$all_channel_ids)
            ->where(function ($query) {
                $query->where('last_send_date','<',date('Y-m-d'))
                    ->orWhereNull('last_send_date');
            })
            ->select(DB::raw("distinct distribution_channel_id as unique_distribution_channel_id"))
            ->pluck('unique_distribution_channel_id')
            ->toArray();
        $batch_no ='自定义批次';
        dump($batch_no);
         $this->autoSendTrusteeShipCustomerMsg($channel_ids,$batch_no);
    }


    /**
     * 创建客服消息
     */
    public function autoSendTrusteeShipCustomerMsg($channel_ids,$batch_no = '')
    {
        \Log::info('autoSendTrusteeShipCustomerMsg:');
        $sexs = ['a', 'b'];
        $customMsgPrams['send_time'] = date('Y-m-d H:00:00');
        $customMsgPrams['redirect_url'] = '';
        $customMsgPrams['subscribe_time'] = 'g';// 关注1天前，有过交互的
        $customMsgPrams['trusteeship'] = '1'; // 托管
        $customMsgPrams['balance'] = 'z';
        $customMsgPrams['order_type'] = 'z';
        $customMsgPrams['category_id'] = 'z';
        $customMsgPrams['status'] = '1';
        $customMsgPrams['is_show_list'] = '0';// 分销界面不展示
        $batch_name = $batch_no;
        //设置书籍标题的站点
        $book_title_channel_ids = DB::table('custom_msg_switchs_msgs')
            ->where('status',1)
            ->where('custom_category','auto_custom_trusteeship')
            ->where('title_type','BOOK')
            ->select(DB::raw("distinct distribution_channel_id as unique_distribution_channel_id"))
            ->pluck('unique_distribution_channel_id')
            ->toArray();
        //
        dump('需要跑的站点');
        dump($channel_ids);
        dump('设置书籍标题的站点');
        dump($book_title_channel_ids);
        //带书名标题的站点
        dump('需要跑的设置书籍标题的站点');
        $book_title_channels = array_intersect($channel_ids,$book_title_channel_ids);
        dump($book_title_channels);
        dump('需要跑的带系统标题的站点');
        //带系统标题的站点
        $default_title_channels = array_diff($channel_ids,$book_title_channels);
        dump($default_title_channels);
        //带默认标题
        if ($default_title_channels) {
            dump('带系统标题');
            foreach ($sexs as $sex) {
                $customMsgPrams['content'] = $this->getMsgContent($sex, 'SYS');
                $customMsgPrams['sex'] = $sex;
                $customMsgPrams['name'] = '自动发送托管客服消息_系统标题'.date('YmdH').$batch_name;
                \Log::info($customMsgPrams);
                $batch_res = BatchCustomMsgService::addBatchCustomSendMsgs($customMsgPrams, $batch_no);
                if ($batch_res == 1) {
                    //创建客服消息
                    $this->BatchCreateCustomSendMsgs($customMsgPrams,$default_title_channels,$batch_no);
                }
            }
        }
        //带书名标题
        if ($book_title_channels) {
            dump('带书名标题');
            foreach ($sexs as $sex) {
                $customMsgPrams['content'] = $this->getMsgContent($sex, 'BOOK');
                $customMsgPrams['sex'] = $sex;
                $customMsgPrams['name'] = '自动发送托管客服消息_书名标题'.date('YmdH').$batch_name;
                \Log::info($customMsgPrams);
                $batch_res = BatchCustomMsgService::addBatchCustomSendMsgs($customMsgPrams,$batch_no);
                \Log::info('batch_res:' . $batch_res . ' batch_no:' . $batch_no);
                if ($batch_res == 1) {
                    //创建客服消息
                    $this->BatchCreateCustomSendMsgs($customMsgPrams,$book_title_channels,$batch_no);
                }
            }
        }

    }


    public function getMsgContent($sex,$title_type='')
    {
        // 男生
        if($sex == 'a'){
            $books = BookConfigService::getTrusteeShipChannelBook('','男频', 4);
        }
        // 女生
        else{
            $books = BookConfigService::getTrusteeShipChannelBook('','女频', 4);
        }
        $books = CustomMsgService::get_book_full_infos($books,$sex,$title_type);
        return json_encode($books);
    }

    public function BatchCreateCustomSendMsgs($customMsgPrams,$in_channel_ids=[],$batch_no=''){
        $customMsgPrams['batch_no'] = $batch_no;
        //按站点取其下公众号创建摸板消息
        foreach($in_channel_ids as $channel_id){
            $time_config = CustomMsgSendTimeConfig::getTimeConfig($channel_id,[
                'begin_time'=>$this->hour_begin,
                'end_time'=>$this->hour_end,
            'custom_category'=>'auto_custom_trusteeship',
            ]);
            if($time_config){
                $customMsgPrams['send_time']=date('Y-m-d').' '.$time_config->send_time;
                $time_config->last_send_date =date('Y-m-d');
                $time_config->save();
            }

            $officialAccountParams['in_channle_ids'] = [$channel_id];
            $official_accounts =  OfficialAccountService::getTrusteeshipOfficialAccountsWithParams($officialAccountParams);
            \Log::info($official_accounts);
            $customMsgPrams['distribution_channel_id'] = $channel_id;
            foreach($official_accounts as $official_account){
                $customMsgPrams['appid'] = $official_account->appid;
                \Log::info('getTrusteeshipOfficialAccounts:appid:'.$official_account->appid.' distribution_channel_id:'.$channel_id);
                //先判断在发送时间段1小时以内，有没有发起过相同的模板消息，如果有发送过，就提示用户已经创建过相同模板消息，不创建新的模板消息
                $isSendCustomer = CustomMsgService::isSendCustomerAtSameTimeAndSex($customMsgPrams);
                if (!empty($isSendCustomer)) {
                    \Log::info('isSendCustomerAtSameTime already_send:appid:'.$customMsgPrams['appid'].' distribution_channel_id:'.$customMsgPrams['distribution_channel_id']);
                    continue;
                }
                $customMsgService = CustomMsgService::addCustomSendMsgs($customMsgPrams);

            }
        }

    }

}
