<?php

namespace App\Modules\User\Models;

use Illuminate\Database\Eloquent\Model;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use DB;

class SubscribeRecord extends Model
{
	protected $connection = 'api_mysql';
	
    protected $table = 'subscribe_records';

    protected $fillable = ['id', 'uid', 'appid', 'distribution_channel_id', 'openid','is_subscribed',
        'subscribe_time','unsubscribe_time','created_at','updated_at'
    ];
    
    static public function create_subscribe_record($param){
    	$data = [];
    	$forceSubscribeUsers = ForceSubscribeUsers::forceSubscribeUsersByOpenidAndAC($param['openid'],$param['appid'],$param['distribution_channel_id']);
    	$data['uid'] = isset($forceSubscribeUsers->uid)?$forceSubscribeUsers->uid:null;
    	 
    	$data['appid'] = $param['appid'];
    	$data['openid'] = $param['openid'];
    	$data['is_subscribed'] = $param['is_subscribed'];
    	
    	if(isset($param['distribution_channel_id']) && $param['distribution_channel_id']){
    		$data['distribution_channel_id'] = $param['distribution_channel_id'];
    	}else{
    		$data['distribution_channel_id'] = isset($forceSubscribeUsers->distribution_channel_id)?$forceSubscribeUsers->distribution_channel_id:null;
    	}
    	if(isset($param['subscribe_time']) && $param['subscribe_time']){
    		$data['subscribe_time'] = $param['subscribe_time'];
    	}else{
    		$data['subscribe_time'] = isset($forceSubscribeUsers->subscribe_time)?$forceSubscribeUsers->subscribe_time:null;
    	}
    	if(isset($param['unsubscribe_time']) && $param['unsubscribe_time']){
    		$data['unsubscribe_time'] = $param['unsubscribe_time'];
    	}else{
    		$data['unsubscribe_time'] = isset($forceSubscribeUsers->unsubscribe_time)?$forceSubscribeUsers->unsubscribe_time:null;
    	}
//     	\Log::info('create_subscribe_record:'.$data['uid'].' data:'.json_encode($data));
    	
    	self::firstOrCreate($data);
    }

}