<?php

namespace App\Modules\OfficialAccount\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class CustomMsgSendTimeConfig extends Model
{
    protected $tables = 'custom_msg_send_time_configs';

    protected $guarded = [];




    /**
     *获取站点下客服消息发送时间配置
     */
    static function getConfigs($params){
        return self::where('is_enable','1')->where($params)->get();
    }

    /**
     *批量创建客服消息发送时间配置
     */
    static function BatchCreateSendTimeConfigs($distribution_channel_ids = [],$custom_category = '',$send_times = [])
    {
        $now = date('Y-m-d H:i:s');
        $insert_data = array();
        if(!($distribution_channel_ids&&$custom_category&&$send_times)){
            return false;
        }
        foreach ($distribution_channel_ids as $distribution_channel_id){
            $params['distribution_channel_id'] = $distribution_channel_id;
            $params['is_enable'] = 1;
            foreach ($send_times as $send_time){
                $params['custom_category'] = $custom_category;
                $params['send_time'] = $send_time;
                $params['created_at'] = $now;
                $params['updated_at'] = $now;
                $insert_data[] = $params;
            }

        }
        try {
            DB::beginTransaction();
            //弃用现有配
            DB::table('custom_msg_send_time_configs')
                ->whereIn('distribution_channel_id',$distribution_channel_ids)
                ->where('custom_category' , $custom_category)
                ->update(['is_enable'=>0])
            ;
            //更新最新配置
            $res = DB::table('custom_msg_send_time_configs')->insert($insert_data);
            DB::commit();
            return true;
        } catch (Exception $e) {
            Log::error('book_stacks confirm custom_msg_send_time_configs_insert :' . $e->getMessage());
            return false;
        }

    }



    /**
     *获取站点下客服消息发送时间配置
     */
    static function getTimeConfig($channel_id='',$params=[]){
        $res =  self::where('is_enable','1')
            ->where('distribution_channel_id',$channel_id)->orderBy('send_time');
            if(isset($params['custom_category'])&&$params['custom_category']){
                $res->where('custom_category' , $params['custom_category']);
            }
            if(isset($params['begin_time'])&&$params['begin_time']){
                $res->where('send_time' , '>',$params['begin_time']);
            }
            if(isset($params['end_time'])&&$params['end_time']){
                $res->where('send_time' , '<',$params['end_time']);
            }
        return $res->first();
    }
}


