<?php

namespace App\Modules\Book\Models;

use Illuminate\Database\Eloquent\Model;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\Book\Models\Book;
use DB;
use Redis;

class DataAnalysisBookConfig extends Model
{
    protected  $table = 'data_analysis_book_configs';
    protected  $fillable = ['bid','book_name','template_title','custom_title','site_banner','sex','status','created_at','updated_at'];

    public static function get_data_analysis_book_configs($sex){
    	return self::select('*')->where('status',1)->where('sex',$sex)->orderBy(DB::raw('RAND()'))->get();
    }
    
    /**
     * 获取1本推荐的未订购的书籍
     */
    public static function getUserOneNotOrderBook($uid){
    	try{
    		// 判断性别
    		$sex = ForceSubscribeService::getSimpleSexByUid($uid);
    		// 配置书籍
    		$book_configs = self::get_data_analysis_book_configs($sex);
    		// 获取用户阅读记录详情
    		$read_bids = ReadRecordService::getSimpleReadRecord($uid);
    		// 推荐过的
    		$recommend_bids = Redis::smembers('DataAnalysisBookConfig:'.$uid);
    		$full_bids = array_merge($read_bids,$recommend_bids);
    		\Log::info('getUserOneNotOrderBook_uid:'.$uid.' sex:'.$sex. ' read_bids:'.json_encode($read_bids).' recommend_bids:'.json_encode($recommend_bids).' full_bids:'.json_encode($full_bids));
    		$one_book = $book_configs[0];
    		do{
    			foreach($book_configs as $key=>$book_config){
    				if(in_array($book_config->bid,$full_bids)){
    					\Log::info('getUserOneNotOrderBook_exists:'.$book_config->bid);
    					continue;
    				}
    				Redis::sadd('DataAnalysisBookConfig:'.$uid,$book_config->bid);
    				$one_book =  $book_configs[$key];
    				break;
    			}
    		}while(false);
    		$book = Book::getBook($one_book->bid);
    		$one_book->first_cid = isset($book->first_cid)?$book->first_cid:'0';
    	}catch(Exception $e){
    		\Log::info('getUserOneNotOrderBook_ept:'.$e->getMessage());
    	}
    	\Log::info('getUserOneNotOrderBook_last_book:'.json_encode($one_book));
        return $one_book;
    }

    public static function getUserReaderPagePushBook($uid,$channel_id,$count=3){
        try{
            $sex = ForceSubscribeService::getSimpleSexByUid($uid);
            $result = self::join('books','books.id','=','data_analysis_book_configs.bid')
                ->where('data_analysis_book_configs.sex',$sex)
                ->where('data_analysis_book_configs.status',1)
                ->select('data_analysis_book_configs.id','books.first_cid','data_analysis_book_configs.bid','data_analysis_book_configs.site_banner');
            if($count>1){
                $result= $result->get()->random(3)->all();
                $data = [];
                $link_format = '%s://site%s.%s.com/reader?bid=%s&cid=%s&ru=%s';
                $img_array =  array_rand(range(1,20),3);
                foreach ($result as $k=>$v){
                    $link = sprintf(
                        $link_format,
                        env('PROTOCOL'),
                        encodeDistributionChannelId($channel_id),
                        env('CUSTOM_HOST'),
                        \Hashids::encode($v->bid),
                        $v->first_cid,
                        'title_'.$v->id
                        );

                    $img = 'https://cdn-novel.iycdm.com/h5/20181120/'.($img_array[$k]+1).'.jpg';
                    $data[] = ['title'=>$v->site_banner,'link'=>$link,'img'=>$img];
                }
                return $data;
            }
            $result = $result->get()->random(1)->first();
            $link_format = '%s://site%s.%s.com/reader?bid=%s&cid=%s&ru=%s';
            $link = sprintf(
                $link_format,
                env('PROTOCOL'),
                encodeDistributionChannelId($channel_id),
                env('CUSTOM_HOST'),
                \Hashids::encode($result->bid),
                $result->first_cid,
                'over_'.$result->id
            );
            return ['title'=>'','link'=>$link,'img'=>''];
        }catch (\Exception $e){
            \Log::info($e);
        }
        return [];
    }


    public static function getUserReaderPagePushBookV2($uid,$channel_id,$charge_type,$count=3){
        try{
            $sex = ForceSubscribeService::getSimpleSexByUid($uid);
            $result = self::join('books','books.id','=','data_analysis_book_configs.bid')
                ->where('data_analysis_book_configs.sex',$sex)
                ->where('data_analysis_book_configs.status',1)
                ->where('data_analysis_book_configs.charge_type',$charge_type)
                ->select('data_analysis_book_configs.id','books.first_cid','data_analysis_book_configs.bid','data_analysis_book_configs.site_banner');
            if($count>1){
                $result= $result->get()->random(3)->all();
                $data = [];
                $link_format = '%s://site%s.%s.com/reader?bid=%s&cid=%s&ru=%s';

                foreach ($result as $k=>$v){
                    $link = sprintf(
                        $link_format,
                        env('PROTOCOL'),
                        encodeDistributionChannelId($channel_id),
                        env('CUSTOM_HOST'),
                        \Hashids::encode($v->bid),
                        $v->first_cid,
                        'title_'.$v->id
                    );

                    //$img = 'https://cdn-novel.iycdm.com/h5/20181120/'.($img_array[$k]+1).'.jpg';
                    $img = 'https://cdn-novel.iycdm.com/h5/20181120/'.($v->id).'.jpg';
                    $data[] = ['title'=>$v->site_banner,'link'=>$link,'img'=>$img];
                }
                return $data;
            }
            $result = $result->get()->random(1)->first();
            $link_format = '%s://site%s.%s.com/reader?bid=%s&cid=%s&ru=%s';
            $link = sprintf(
                $link_format,
                env('PROTOCOL'),
                encodeDistributionChannelId($channel_id),
                env('CUSTOM_HOST'),
                \Hashids::encode($result->bid),
                $result->first_cid,
                'over_'.$result->id
            );
            return ['title'=>'','link'=>$link,'img'=>''];
        }catch (\Exception $e){
            \Log::info($e);
        }
        return [];
    }
}
