<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/7/18
 * Time: 10:09
 */

namespace App\Modules\User\Services;

use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\User\Models\CrmUser;
use DB;

class CrmUserService
{
    public static function isCrmUser($uid,$is_paid){
        $model = new CrmUser();
        $crmuser = $model->where('uid',$uid)->where('is_enable',1)->select('id')->first();
        if($crmuser) return true;

        $bind_info = DB::table('friend_link_uid_bind')->join('users','friend_link_uid_bind.openid','users.openid')
            ->select('friend_link_uid_bind.created_at')->where('users.id',$uid)->first();

        //2019-07-22 20:00 之前有领过书币或者有绑定过的都可以符合
        if($bind_info && $bind_info->created_at <= '2019-07-22 20:00:00'){
            self::create($uid);
            return true;
        }

        $get_price = UserBindHkWelfareService::isHasGetCrm($uid);
        if($get_price &&  $get_price->created_at <= '2019-07-22 20:00:00'){
            self::create($uid);
            return true;
        }

        //是否充值过
        if(!$is_paid) return false;
        //是否领过书币
        if(!$get_price) return false;

        //3日内有订阅
        //本订
        if(BookOrderService::isHasBookOrderInThreeDay($uid)){
            self::create($uid);
            return true;
        }
        //章订
        if(ChapterOrderService::isHasChapterOrderInThreeDay($uid)){
            self::create($uid);
            return true;
        }

        return false;
    }

    private static function create(int $uid){
        $model = new CrmUser();
        $crmuser = $model->where('uid',$uid)->where('is_enable',0)->select('id')->first();
        if($crmuser){
            $crmuser->is_enable = 1;
            $crmuser->save();return ;
        }
        $model->uid = $uid;
        $model->is_enable = 1;
        $model->save();
    }
}