<?php

namespace App\Modules\User\Services;

use App\Modules\Activity\Services\ActivitySwitchService;
use App\Modules\Subscribe\Models\Order;
use App\Modules\User\Models\User;
use App\Modules\User\Models\UserSign;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use Hashids;
use App\Modules\Book\Services\BookConfigService;
use DB;
use Redis;
use App\Modules\User\Services\UserService;
use App\Modules\Activity\Services\ActivityService;

class UserSignService
{
    protected $table = 'user_sign';
    protected $fillable = ['uid', 'price', 'day', 'sign_time'];

    /**
     * 用户是否已签到
     * @param $uid
     * @param $day
     * @return mixed
     */
    public static function isSign($uid)
    {
        //return UserSign::isSign($uid, $day);
        $sign_day = ReadRecordService::getSignDay($uid);
        //异常
        if($sign_day == -1){
            return true;
        }
        if($sign_day && $sign_day == date('Y-m-d')){
            return true;
        }
        return false;
    }

    /**
     * 新用户首次签到获得书币调整为30书币，连续签到2天后，赠送书币量提升至50，断签后重新按30开始
     * 用户是否已签到(升级版)
     * @param $uid
     * @param $day
     * @return mixed
     */
    public static function isSigni($uid, $day){
        $day_2 = date('Y-m-d',strtotime($day)-86400*2);
        $sign_stat = UserSign::where('uid',$uid)->where('day','>=',$day_2)->select('day')->orderBy('id','desc')->limit(3)->get();

        if(!$sign_stat->isEmpty()){
            $day_1 = date('Y-m-d',strtotime($day)-86400);
            $sign_day = [];
            foreach ($sign_stat as $v){
                $sign_day[] = $v->day;
            }
            if(in_array($day,$sign_day)){
                return 0;
            }
            if( in_array($day_1,$sign_day) && in_array($day_2,$sign_day)){
                return 50;
            }
            return 30;
        }
        return 30;
    }

    /**
     * 用户签到记录
     */
    public static function getUserSignRecord($uid){
        return UserSign::getUserSignRecord($uid);
    }

    /**
     * 签到
     * @param $uid
     * @param $day
     * @return mixed
     */
    public static function sign($uid, $day)
    {
    	\Log::info('sign:uid:'.$uid.' day:'.$day);
        //查看签到日期
        $sign_day = ReadRecordService::getSignDay($uid);
        if($sign_day == -1){
            return false;
        }
        //已经签过到
        if($sign_day == $day){
            return false;
        }

        $count = ReadRecordService::getSignCountSimple($uid);
        //记录签到日期
        if($sign_day && $sign_day == date('Y-m-d',time()-86400)){
            $continue = true;
            //昨天有签过到
            ReadRecordService::sign((int)$uid,true);
            $count += 1;
        }else{
            $continue = false;
            //昨天没有签过到
            ReadRecordService::sign((int)$uid,false);
            $count = 1;
        }

        $return_fee = $fee = 30;
        //连续签到两天 50书币
        if($continue && $count>=3){
            $return_fee = $fee = 50;
        }
        if($count%15 == 7){
            $fee += 100;
        }
        if($count%15 == 0){
            $fee += 150;
        }
        UserService::addBalance($uid, $fee, 0, $fee);
        // 先扔到redis里面，异步更新user_sign表
        $use_redis_user_sign = true;
        if($use_redis_user_sign){
        	$sign_data = ['uid'=>$uid,'price'=>$fee,'day'=>$day,'sign_time'=>time(),'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
        	Redis::sadd('user_sign:uid',$uid);
        	Redis::hset('user_sign:uid:info',$uid,json_encode($sign_data));
            ReadRecordService::setSignInfo($uid,json_encode($sign_data));
        }else{
        	UserSign::sign($uid, $day,$fee);
        }
        return $return_fee;
    }

    public static function signToday($uid){
        return self::sign($uid,date('Y-m-d'));
    }


    /**
     * 新签到回复
     * @param $openid
     * @param bool $check_sign
     * @param int $price
     * @return string
     */
    public static function userSignReturnContent3($openid,$distribution_channel_id='')
    {
        $content = '';
        $day = date('Y-m-d');
        $user = ForceSubscribeUsers::getOneForceSubscribeUsersByOpenid($openid);
        if ($user) {
            $user_wechat = User::where('id',$user->uid)->first();
            $new_user_activity_content = '';
            if(!Order::where('uid',$user->uid)->where('status','PAID')->select('id')->first()){
                $new_user_activity_content = self::newUserActivity($user);
            }
            $encode_distribution_channel_id = encodeDistributionChannelId($user->distribution_channel_id);
            $attach_content = self::signCallBackPushActivityInfo($user->uid,$user->distribution_channel_id);
            $continueReadUrl = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('WECHAT_CUSTOM_HOST') . '.com/continue';
            $sign_url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('WECHAT_CUSTOM_HOST') . '.com/sign';

            $sign_stat = self::isSign($user->uid);
            if ($sign_stat) {
                $content = '今日已经签到过了,明日继续签到得书币哦~' ;
                //$content .= '<a href=' . '"' . $continueReadUrl . '"' . '> ☞ 点我继续上次阅读</a>';
            }else{
                $content = '尊敬的会员：'.($user_wechat?$user_wechat->nickname:'')."\n\n"."<a href='".$sign_url."'>💰点击此处签到领书币</a>" ; 
                //$content .= '继续阅读\n\n<a href=' . '"' . $continueReadUrl . '"' . '> ☞ 点我继续上次阅读</a>';
            }

            $res = ReadRecordService::getReadRecord($user->uid);
//             foreach ($res as $key => $record) {
//                 if ($key == 1) break;
//                 $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($record['bid']) . '&cid=' . $record['cid'];
//                 $content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $record['book_name'] . '》</a>';
//             }

            $read_bid_arr = [];
            $read_bid_arr[] = -1;
            foreach ($res as $vbook) {
                $read_bid_arr[] = $vbook['bid'];
            }

            $user_detail = UserService::getById($user->uid);
            $sign_recomm_bid_key = '男频';
            if ($user_detail && isset($user_detail->sex)) {
                if ($user_detail->sex == 2) {
                    $sign_recomm_bid_key = '女频';
                }
            }

            $hot_book_num = 3;
            $recomm_books = BookConfigService::getSignRecommendBooks($read_bid_arr, $sign_recomm_bid_key,$hot_book_num);
            $content .= "\n\n" . '热门书籍推荐';
            if ($recomm_books) {
                foreach ($recomm_books as $book) {
                    $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('WECHAT_CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                    $content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book->book_name . '》</a>';
                }
            }
            //$content .= "\n\n" . '为方便下次阅读，请置顶公众号';
            $content .= "\n\n" . '为方便下次阅读，请<a href="'.'https://help.'. env('WECHAT_CUSTOM_HOST') .'.com/top.html"'.'>置顶公众号</a>';

            if($attach_content){
                $content .= "\n\n" .$attach_content;
            }
            if($new_user_activity_content){
                $content .= $new_user_activity_content;
            }
        }
        // 空用户推默认的文案
        else{
        	$encode_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
        	$url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('WECHAT_CUSTOM_HOST') . '.com/sign';
        	$content = "尊敬的会员：\n\n" . '<a href="' . $url . '"> 💰点击此处签到领书币</a>';
        }
        return $content;
    }

    private static function newUserActivity($user){
        $content = '';
        $status = self::newUserActivityStatus($user->uid);
        $record = [];
        //新关未付费用户42小时后充推送活动 68元的活动 文案：全年免费看书
        if(strtotime($user->created_at)+42*3600 < time() &&
            $user->distribution_channel_id == 123 &&
            !in_array(1,$status)
        ){
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($user->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/seYearActivity?fromtype=signcallback_forever&send_time='.time() ;
            $content .=  "\n\n" .'<a href="' . $url . '"> 💰全年免费看书</a>';
            $record[] = ['uid'=>$user->uid,'type'=>1,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
        }
        //20小时的 文字链的文案：书币充值特惠
        if(strtotime($user->created_at)+20*3600 < time() && !in_array(2,$status)){
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($user->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserSale?fromtype=signcallback_newUserSale&send_time='.time() ;
            $content .=  "\n\n" .'<a href="' . $url . '"> 💰书币充值特惠</a>';
            $record[] = ['uid'=>$user->uid,'type'=>2,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
        }
        //36小时的。文案：充9.9送2000书币
        if(strtotime($user->created_at)+36*3600 < time() && !in_array(3,$status)){
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($user->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/sale/newUserActivity?fromtype=signcallback_newUserActivity&send_time='.time() ;
            $content .=  "\n\n" .'<a href="' . $url . '"> 💰充9.9得2000书币</a>';
            $record[] = ['uid'=>$user->uid,'type'=>3,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
        }
        self::recordnewUserActivityPush($record);
        return $content;
    }

    private static function  newUserActivityStatus($uid){
        $data = [-1];
        if(!$uid){
            return $data;
        }
        $result = DB::table('user_sign_push_activity')->where('uid',$uid)->select('type')->get();
        if($result){
            foreach ($result as $v){
                array_push($data,$v->type);
            }
        }
        return $data;
    }

    private static function recordnewUserActivityPush($data){
        if($data){
            try{
                DB::table('user_sign_push_activity')->insert($data);
            }catch (\Exception $e){

            }
        }
    }
    /**
     *
     * @param $openid
     * @return string
     */
    public static function userSignReturnContent($openid)
    {
        $content = '';
        $day = date('Y-m-d');
        $user = ForceSubscribeUsers::getOneForceSubscribeUsersByOpenid($openid);
        if ($user) {
            $encode_distribution_channel_id = encodeDistributionChannelId($user->distribution_channel_id);
            $attach_content = self::signCallBackPushActivityInfo($user->uid);
            $continueReadUrl = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('CUSTOM_HOST') . '.com/continue';
            $is_sign = self::isSign($user->uid);
            if ($is_sign) {
                $content = '今日已经签到过了,明日继续签到得书币哦~' . "\n\n" . '<a href=' . '"' . $continueReadUrl . '"' . '> >>点我继续上次阅读</a>';
                /*if($attach_content){
                    $content .= "\n\n" .$attach_content;
                }*/
                //return $content;
            }else{
                $sign_stat = self::sign($user->uid, $day);

                $content = '今日签到成功，赠送'.$sign_stat.'书币，明日继续签到得书币哦~' . "\n\n" . '<a href=' . '"' . $continueReadUrl . '"' . '> >>点我继续上次阅读</a>' . "\n\n" . '阅读记录：';

                if($sign_stat == 30){
                    $content = '今日签到成功，赠送30书币，连续签到2日后，赠送书币增加至50哦~' . "\n\n" . '<a href=' . '"' . $continueReadUrl . '"' . '> >>点我继续上次阅读</a>' . "\n\n" . '阅读记录：';
                }
            }
            $new_user_activity_content = '';
            if(!Order::where('uid',$user->uid)->where('status','PAID')->select('id')->first()){
                $new_user_activity_content = self::newUserActivity($user);
            }
            $res = ReadRecordService::getReadRecord($user->uid);
            foreach ($res as $key => $record) {
                if ($key == 3) break;
                $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($record['bid']) . '&cid=' . $record['cid'];
                $content .= "\n\n" . '<a href="' . $url . '"> >>《' . $record['book_name'] . '》</a>';
            }

            $read_bid_arr = [];
            $read_bid_arr[] = -1;
            foreach ($res as $vbook) {
                $read_bid_arr[] = $vbook['bid'];
            }

            $user_detail = UserService::getById($user->uid);
            $sign_recomm_bid_key = '男频';
            if ($user_detail && isset($user_detail->sex)) {
                if ($user_detail->sex == 2) {
                    $sign_recomm_bid_key = '女频';
                }
            }

            $recomm_books = BookConfigService::getSignRecommendBooks($read_bid_arr, $sign_recomm_bid_key);
            $content .= "\n\n" . '热门书籍推荐';
            if ($recomm_books) {
                foreach ($recomm_books as $book) {
                    $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                    $content .= "\n\n" . '<a href="' . $url . '"> >>《' . $book->book_name . '》</a>';
                }
            }
            //$content .= "\n\n" . '为方便下次阅读，请置顶公众号';
            $content .= "\n\n" . '为方便下次阅读，请<a href="'.'https://help.leyuee.com/top.html"'.'>置顶公众号</a>';


            if($attach_content){
                $content .= "\n\n" .$attach_content;
            }

            if($new_user_activity_content){
                $content .= "\n\n" .$new_user_activity_content;
            }
        }
        return $content;
    }

    public static function signCallBackPushActivityInfo($uid,$distribution_channel_id){

        $activity_setting = ActivityService::getActivitySetting();
        if(!$activity_setting)
            return false;
        $acyivity_id = isset($activity_setting['activity_id'])?$activity_setting['activity_id']:0;
        $other = env('OTHER_ACTIVITY_ID',0);
        if($acyivity_id == $other && !in_array($distribution_channel_id,explode(',', env('OTHER_ACTIVITY_CHANNEL', '1')))){
            return false;
        }
        if(!$acyivity_id)
            return false;
        $activity_title = isset($activity_setting['sign_call_back_text'])?$activity_setting['sign_call_back_text']:'';;
        if(empty($activity_title))
            return false;
        $activity_info = ActivityService::getById($acyivity_id);
        if(empty($activity_info))
            return false;

        if(time()< strtotime($activity_info->start_time) || time()> strtotime($activity_info->end_time)){
            return false;

        }
        $user = UserService::getById($uid);
        if(empty($user))
            return false;

        if(!ActivitySwitchService::isShowInPage($acyivity_id,$distribution_channel_id,'sign')){
            return false;
        }
        /*
         $no_participate_activity = env('no_participate_activity','');
        if($no_participate_activity && in_array($user->distribution_channel_id, explode(',',$no_participate_activity))){
            return false;
        }*/
        if($user && isset($user->created_at) && (time() - strtotime($user->created_at)) >= 86400*2) {
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com'.$activity_info->activity_page . '&fromtype=signcallback' ;
            return   '<a href="' . $url . '"> ' . $activity_title . '</a>';
        }

        return false;
    }

    /**
     * 签到统计
     */
    public static function getSignTotalByChnnelId(array $data = [])
    {
        $search_obj = UserSign::join('users', 'user_sign.uid', '=', 'users.id');
        if (isset($params['distribution_channel_id'])) $search_obj->where('users.distribution_channel_id', $params['distribution_channel_id']);
        if (isset($params['begin_time']) && $params['begin_time']) $search_obj->where('user_sign.created_at', '>=', $params['begin_time']);
        if (isset($params['end_time']) && $params['end_time']) $search_obj->where('user_sign.created_at', '<=', $params['end_time']);
        return $search_obj->groupBy('user_sign.day', 'users.distribution_channel_id')->select(DB::raw('count(*) as sign_num'), DB::raw('user_sign.day as day'), 'users.distribution_channel_id')->get();
    }
}
