<?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 App\Modules\Channel\Services\ChannelService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
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;
    }


    public static function signV2($uid, $day)
    {
        \Log::info('signv2: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;
        }

        $fee = 30;
        if ($count % 7 == 1 && $count<=7) {
            $fee = 30;
        } elseif ($count % 7 == 3) {
            $fee = 120;
        } elseif ($count % 7 == 0) {
            $fee = 150;
        } else {
            $fee = 50;
        }
        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 {
            $user_sign_model = new UserSign();
            $user_sign_model->setCurrentTable(date('Ym'));
            $data = ['uid'=>$uid,'price'=>$fee,'day'=>$day,'sign_time'=>time()];
            $user_sign_model->create($data);
        }
        return compact('count','fee');
    }


    /**
     * 新签到回复
     * @param $openid
     * @param bool $check_sign
     * @param int $price
     * @return string
     */
    public static function userSignReturnContent3($openid,$distribution_channel_id='',$WECHAT_CUSTOM_HOST='zhuishuyun')
    {
        return self::userSignReturnContent($openid,$distribution_channel_id,$WECHAT_CUSTOM_HOST);
    }

    public static function userSignReturnContent($openid,$distribution_channel_id='',$WECHAT_CUSTOM_HOST='zhuishuyun'){
        //强关信息
        $user = ForceSubscribeUsers::getOneForceSubscribeUsersByOpenid($openid);
        if (!$user) {
            return self::defaultSignContent($distribution_channel_id,$WECHAT_CUSTOM_HOST);
        }
        //用户信息
        $user_info = User::where('id',$user->uid)->first();
        if (!$user_info){
            return self::defaultSignContent($distribution_channel_id,$WECHAT_CUSTOM_HOST);
        }
        $encode_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
        $continueReadUrl = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $WECHAT_CUSTOM_HOST . '.com/continue';
        $sign_url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $WECHAT_CUSTOM_HOST . '.com/sign';

        //是否签到
        $sign_status = self::isSign($user->uid);
        if($sign_status){
            $content = self::hadSignContent($continueReadUrl);
        }else{
            //直接签到
            $direct_sites = explode(',',env('DIRECT_SIGN_SITES'));
            $is_direct_sign = in_array($distribution_channel_id,$direct_sites) ? true : false;
            if ($is_direct_sign) {
                $content = self::directSignContent($user->uid,$user_info->nickname,$continueReadUrl,$sign_url);
            } else {
                $content = '尊敬的会员：'.$user_info->nickname."\n\n"."<a href='".$sign_url."'>💰点击此处签到领书币</a>" ;
            }
        }

        $content  .= self::bookContent($user->uid,$distribution_channel_id,$encode_distribution_channel_id,$WECHAT_CUSTOM_HOST);
        $activity_attach_content = '';
        try{
            $activity_attach_content = self::signCallBackPushActivityInfoV2($user->uid,$distribution_channel_id);
        }catch (\Exception $e){
        }
        if($activity_attach_content){
            $content .= "\n\n" .$activity_attach_content;
        }
        return $content;
    }

    private static function bookContent($uid,$distribution_channel_id,$encode_distribution_channel_id,$host){
        //展示用户最近阅读的三本书,倒叙排列
        //如果没有阅读记录则
        $read_record_list = ReadRecordService::getReadRecord($uid);
        if($read_record_list){
            $temp = 0;
            $content = "\n\n" . '历史阅读记录';
            foreach ($read_record_list as $item){
                if($temp >=3) break;
                $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $host . '.com/reader?bid=' . Hashids::encode($item['bid']) . '&cid=' . $item['cid'];
                $content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $item['book_name'] . '》</a>';
                $temp++;
            }
            return $content;
        }
        //正常推荐3本书
        //男女频
        $channel_sex = ChannelService::getChannelCompanySex($distribution_channel_id);
        if($channel_sex == 1){
            $sign_recomm_bid_key = '男频';
        }else{
            $sex = ForceSubscribeService::getUserRealSexByUid($uid);
            $sign_recomm_bid_key = $sex==1?'男频':'女频';
        }
        $recomm_books = BookConfigService::getSignRecommendBooksFromCache([], $sign_recomm_bid_key,3);
        if ($recomm_books) {
            // 判断是否不展示书名
            $content = "\n\n" . '热门书籍推荐';
            foreach ($recomm_books as $key=>$book) {
                $book_name = $book->book_name;
                $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $host . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                $content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
            }
            return $content;
        }
        return '';
    }


    //直接签到
    private static function directSignContent($uid,$user_name,$continueReadUrl,$sign_url){
        $result = self::signV2($uid,date('Y-m-d'));
        if($result){
            $content = "本日签到成功，您已连续签到{$result['count']}天，赠送{$result['fee']}书币，连续签到，最高赠送150书币~";
            $content .= "\n\n<a href=" . '"' . $continueReadUrl . '"' . '> ☞ 点我继续上次阅读</a>';
            return $content;
        }else{
            //签到失败
            $content = '尊敬的会员：'.$user_name."\n\n"."<a href='".$sign_url."'>💰点击此处签到领书币</a>" ;
            return $content;
        }
    }

    //已经签过到
    private static function hadSignContent($continueReadUrl){
        $content = '今日已经签到过了,明日继续签到得书币哦~' ;
        $content .= "\n\n<a href=" . '"' . $continueReadUrl . '"' . '> ☞ 点我继续上次阅读</a>';
        return $content;
    }

    //默认签到文案
    private static function defaultSignContent($distribution_channel_id,$host){
        $encode_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
        $url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $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::connection('api_mysql')->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::connection('api_mysql')->table('user_sign_push_activity')->insert($data);
            } catch (\Exception $e) {

            }
        }
    }


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

        $activity_info = ActivityService::selectNowActiveActivity($distribution_channel_id);
        if(empty($activity_info))
            return false;
        $acyivity_id = $activity_info->id;
        $activity_setting = $activity_info->setting;
        if(!$activity_setting ) return false;
        $activity_setting = json_decode($activity_setting,1);
        if(!isset($activity_setting['sign_text']) || empty($activity_setting['sign_text'])) return false;
        if($activity_info->create_type == 5){
            //渠道自定义活动
            if(!isset($activity_setting['sign_enter_point_switch']) || empty($activity_setting['sign_enter_point_switch'])){
                return false;
            }
        }else{
            if(!ActivitySwitchService::isShowInPage($acyivity_id,$distribution_channel_id,'sign')){
                return false;
            }
        }

        $user = UserService::getById($uid);
        if(empty($user))
            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_setting['sign_text'] . '</a>';
        }

        return false;
    }


    private static function rfmActivity($uid,$distribution_channel_id,$created_at,&$status){
        $rfm_user = DB::connection('api_mysql')->table('rfm_ab_test_user')->where('uid',$uid)->select('uid','type')->first();
        if(!$rfm_user){
            $status = 0;
            return '';
        }
        $time = time() - strtotime($created_at);
        if($time > 3600*4 && $time < 23*3600){
            if($rfm_user->type == 'A'){
                $status = 1;
                return '';
            }
            $level = UserService::rfmLevel($uid,strtotime($created_at));
            if($level){
                $level_str = implode('',$level);
            }
            $status = 1;
            return '';
        }

        if($time > 23*3600){
            $level = UserService::rfmLevel($uid,strtotime($created_at));
            if($level){
                $level_str = implode('',$level);
            }
            $status = 1;
            return '';
        }
        $status = 1;
        return '';
    }

    public static function guideFans($uid,$distribution_channel_id,$openid,$created_at){
        list($inner_sites,$qrcode,$second_qrcode) = Redis::hmget('env','GUIDE_PERSONAL_ACCOUNT_SITES','ACTIVE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE','SECOND_ACTIVE_GUIDE_PERSONAL_ACCOUNT_OURS_QRCODE');
        if ($inner_sites && in_array($distribution_channel_id, explode(',', $inner_sites))){
            if (!self::isAccess($openid, $type)) return false;
            //注册时按
            if ($type == 'INNER_ACTIVE') {
                if (!$qrcode) return false;
            }
            if ($type == 'SECOND_INNER_ACTIVE') {
                if (!$second_qrcode) return false;
            }
            if (strtotime($created_at) <= strtotime('-1 day')) {
                $sql = sprintf("select id from orders where uid in (select id from users where openid = '%s' ) and status = 'PAID' and price >=10 limit 1",$openid);
                $result = DB::connection('api_mysql')->select( $sql );
                if($result){
                    return true;
                }else{
                    //openid充值金额小于10:不曝光
                    return false;
                }
            }
            $sql = sprintf("select id from orders where uid  = %s and status = 'PAID' and price >=10 limit 1",$uid);
            $result = DB::connection('api_mysql')->select( $sql );
            //uid下注册时间小于24小时
            if ($result) {
                return true;
            }  else {
                //uid下充值金额小于10:不曝光
                return false;
            }
        }
        return false;
    }

    //crm 访问权限
    private static function isAccess($openid, &$type)
    {
        //二次到分
        $second_result = DB::connection('api_mysql')->table('crm_second_guide')->where('openid',$openid)->select('status')->first();
        if($second_result && $second_result->status == 0){
            $type = 'SECOND_INNER_ACTIVE';
            return true;
        }
        $first_result = DB::connection('api_mysql')->table('user_bind_hk_welfare')->where('openid',$openid)->select('id')->first();
        if ($first_result) {
            //领过书币不曝光
            return false;
        }
        $type = 'INNER_ACTIVE';
        return true;
    }


}
