<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2018/11/19
 * Time: 11:20
 */

namespace App\Modules\Statistic\Services;

use App\Modules\Statistic\Models\DataAnalysisChapter;
use DB;

class DataAnalysisChapterService
{
    /**
     * 用户是否可以加入到表中的信息
     * @param int $type
     * @param int $uid
     * @return array
     */
    public static function getAccessInfo(int $uid){
        $sql_fromat = "SELECT users.id,users.send_order_id,send_orders.charge_type,c.uid,users.created_at,b.order_count,d.subscribe_time,e.type,e.counts
from users
LEFT JOIN send_orders on users.send_order_id = send_orders.id
LEFT JOIN data_analysis_short_and_long_chapter c on users.id=c.uid
LEFT JOIN (SELECT COUNT(*) as order_count from orders where uid = %s and `status` = 'PAID')  b on 1=1
LEFT JOIN (SELECT created_at as subscribe_time from force_subscribe_users WHERE uid =%s LIMIT 1 )d on 1=1
left join (SELECT type,COUNT(*) as counts FROM data_analysis_short_and_long_chapter GROUP BY `type` ORDER BY counts  LIMIT 1 ) e  on 1=1
WHERE users.id = %s";
        $result = DB::select(sprintf($sql_fromat,$uid,$uid,$uid));
        if($result && isset($result[0])){
            return (array)$result[0];
        }
        return [];
    }

    public static function createUser(int $uid,int $type,int $distribution_channel_id){
        try{
            DataAnalysisChapter::create([
                'uid'=>$uid,
                'type'=>$type,
                'distribution_channel_id'=>$distribution_channel_id
            ]);
        }catch (\Exception $e){}
    }

    /**
     * 根据用户获取类型
     * @param int $uid
     * @return int
     */
    public static function getByUid(int $uid){
        $result = DataAnalysisChapter::where('uid',$uid)->select('type')->first();
        if($result && $result->type){
            return (int)$result->type;
        }
        return 0;
    }
    
    /**
     * 根据用户类型获取uid集合
     */
    public static function getByTypes($types):array {
    	return DataAnalysisChapter::whereIn('type',$types)->select('uid')->groupBy('uid')->get()->pluck('uid')->all();
    }
    
}