<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/11/21
 * Time: 10:42
 */

namespace App\Modules\User\Services;

use App\Modules\User\Models\User;
use DB;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;

class UserService
{
    /**
     * 创建用户
     * $params
     * 必穿参数 openid、unionid、distribution_channel_id
     * 可传 province、city、country、headimgurl、send_order_id、sex、register_ip
     */
    static function addUser($params)
    {
        return User::addUser($params);
    }

    static function getUserList($limit, $offset)
    {
        return User::getUserList($limit, $offset);
    }

    static function getUserByNickAndChannelId($distribution_channel_id, $nickname)
    {
        return User::getUserByNickAndChannelId($distribution_channel_id, $nickname);
    }


    /**
     * 获取用户信息列表
     * @param $pageSize 每页显示的条数
     */
    static function getPaginationList($pageSize = 20)
    {
        return User::getPaginationList($pageSize);
    }


    /**
     * 获取用户信息列表
     * @param $pageSize 每页显示的条数
     */
    static function getUsers($pageSize = 20, $careStatus)
    {
        return User::getPaginationList($pageSize, $careStatus);
    }

    /**
     * 根据id获取用户信息
     * @return  user object
     */
    static function getById($id)
    {
        return User::getById($id);
    }

    /**
     * 根据id获取用户信息
     * @return  user object
     */
    static function getUserDataById($id)
    {
        return User::getUserDataById($id);
    }

    /**
     * 根据id获取用户信息
     * @return  user object
     */
    static function getUserDataDetailById($id)
    {
        return User::getUserDataDetailById($id);
    }

    /**
     * 根据id获取用户名称
     * @return  string [用户昵称]
     */
    static function getNicknameById($id)
    {
        return User::getById($id)->nickname;
    }

    /**
     * 更新用户信息
     * @param  int $id 用户ID
     * @param  array $params 可传 province、city、country、headimgurl、sex
     * @return boolen
     */
    static function updateInfo($id, $params)
    {
        \Log::info('~~~~~~~~~~~~~~~~~====update User====~~~~~~~~~~~~~~~~' . "\n");
        \Log::info($id);
        \Log::info($params);
        return User::updateInfo($id, $params);
    }

    /**
     * 根据union和分销id获取用户信息
     * @param $union
     * @param $channel_id
     * @return mixed
     */
    static function getUserByUnionAndChannelId($openid, $channel_id)
    {
        return User::where('openid', $openid)->where('distribution_channel_id', $channel_id)->select('id', 'openid', 'unionid')->first();
    }

    /**
     * 用户余额充值
     * @param $uid
     * @param $fee
     * @return mixed
     */
    static function addBalance($uid, $fee, $charge, $given)
    {
        return User::addBalance($uid, $fee, $charge, $given);
    }

    /**
     * 查询推广注册用户总数
     * @param $send_order_id
     * @return mixed
     */
    static function getPromotionTotal($send_order_id)
    {
        return User::getPromotionTotal($send_order_id);
    }

    /**
     * 查询渠道某天注册用户总数
     * @param $channel_id
     * @param $date
     * @return mixed
     */
    static function getChannelDayTotal($channel_id, $date)
    {
        return User::getChannelDayTotal($channel_id, $date);
    }

    /**
     * 查询渠道注册用户总数
     * @param $channel_id
     * @return mixed
     */
    static function getChannelTotal($channel_id)
    {
        return User::getChannelTotal($channel_id);
    }

    /**
     * 查询渠道某段时间注册用户总数
     * @param $channel_id
     * @param $startDate
     * @param $endDate
     * @return mixed
     */
    static function getChannelDayToDayTotal($channel_id, $startDate = '', $endDate = '')
    {
        return User::getChannelDayToDayTotal($channel_id, $startDate, $endDate);
    }

    /**
     * 查询渠道某段时间注册用户总数
     * @param array $channelIds
     * @param $startDate
     * @param $endDate
     * @return mixed
     */
    static function getChannelsDayToDayTotal($channelIds, $startDate = '', $endDate = '')
    {
        return User::getChannelsDayToDayTotal($channelIds, $startDate, $endDate);
    }

    /**
     * 查询注册用户总数
     * @param $params
     */
    static function getTotalCount($params)
    {
        return User::getTotalCount($params);
    }

    /**
     * 查询渠道是否有登录
     * @param $channelId
     * @param $start_time
     * @param $end_time
     * @return int
     */
    static function judgeUserYesterdayLogin($channelId, $start_time, $end_time)
    {
        $user_behavior = DB::table('channel_operate_record')
            ->where([
                ['distribution_channel_id', '=', $channelId],
                ['created_at', '>=', $start_time],
                ['created_at', '<=', $end_time]
            ])
            ->first();
        if ($user_behavior) return 1;
        return 0;
    }

    /**
     * @param $date
     * @param $company_id
     * @return mixed
     */
    static function getCompanyDayTotal($date, $company_id)
    {
        $end_date = date('Y-m-d', strtotime($date) + 86400);
        $info = User::leftjoin('distribution_channels', 'distribution_channels.id', '=', 'users.distribution_channel_id')
            ->leftjoin('channel_users', 'channel_users.id', '=', 'distribution_channels.channel_user_id')
            ->where([
                ['users.created_at', '>=', $date],
                ['users.created_at', '<', $end_date],
                ['channel_users.company_id', '=', $company_id]
            ])
            ->groupBy('channel_users.company_id')
            ->select(DB::raw("count(users.id) as register_sum"))
            ->first();
        if ($info) return $info->register_sum;
        //\Log::info('getCompanyDayTotal error:' . $company_id);
        return $info;
    }

    static function getCompanyTotal($company_id)
    {
        $info = User::leftjoin('distribution_channels', 'distribution_channels.id', '=', 'users.distribution_channel_id')
            ->leftjoin('channel_users', 'channel_users.id', '=', 'distribution_channels.channel_user_id')
            ->where('channel_users.company_id', $company_id)
            ->groupBy('channel_users.company_id')
            ->select(DB::raw("count(users.id) as register_sum"))
            ->first();
        if ($info) return $info->register_sum;
        //\Log::error('getCompanyTotal error:' . $company_id);
        return $info;
    }

    static function transfromBalanceByUser($from_uid, $to_uid)
    {
        $add_balance_sql = "update users,(select * from users where id =" . $from_uid . ") as u2 
        set users.balance = users.balance + u2.balance,
        users.reward_balance = users.reward_balance +u2.reward_balance, 
        users.charge_balance = users.charge_balance +u2.charge_balance where users.id =" . $to_uid;

        $res = DB::update($add_balance_sql);

        return User::updateInfo($from_uid, ['balance' => 0, 'reward_balance' => 0, 'charge_balance' => 0]);
    }
    
    /**
     * http://test3.ycsd.cn/szzg/other/otherusercharge.aspx?action=addUser&uid=1&openid=1&token=none&username=%E6%9A%82%E6%97%A0&timestamp=1552378761&ip=0.0.0.0&sign=04bc37da70df587f77440afbaaf67224
     * 
     * @param unknown_type $param
     */
    static public function request_ycsd_action($param) {
    	$time = time();
    	$sign = md5($time.'ycsd2019');
    	$param['timestamp'] = $time;
    	$param['sign'] = $sign;
    	$param['ip'] = isset($param['ip'])?$param['ip']:'0.0.0.0';

    	\Log::Info('request_ycsd_action_param');\Log::Info($param);
    
    	//获取封面图片media_id
    	$ycsdJson = self::getYcsdClient()->request("GET",'',
    			['query'=>$param,'connect_timeout' => 5]
    	)->getBody()->getContents();
    
    	\Log::info("request_ycsd_action:".$param['action']);
    	\Log::info($ycsdJson);
    
    	$ycsdJson = json_decode($ycsdJson,true);
    	return $ycsdJson;
    }
    
    static public function getYcsdClient(){
    	return new Client(['base_uri' => env('YCSD_REQUEST_URL')]);
    }
    
}