<?php

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

namespace App\Modules\User\Services;

use App\Consts\QuickConst;
use App\Modules\Book\Models\BookGiftsSend;
use App\Modules\Book\Models\UserShelfBooks;
use App\Modules\Subscribe\Models\BookOrder;
use App\Modules\Subscribe\Models\ChapterOrder;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\User\Models\User;
use App\Modules\User\Models\UserEnv;
use DB;
use App\Jobs\ActionTrigger;
use App\Jobs\UserAddDeskJob;
use App\Modules\OfficialAccount\Models\DistributionSelfDefineConfig;
use App\Modules\Channel\Models\Channel;
use App\Modules\Trade\Models\Order;
use App\Modules\User\Models\QappUserAddDestop;
use App\Modules\UserTask\Services\BaseTask;
use App\Modules\UserTask\Services\UserTaskService;
use Redis;

class UserService
{
    public static function setUserSendOrder(int $uid, int $send_order_id)
    {
        return Redis::hset('book_read:' . $uid, 'send_order_id', $send_order_id);
    }

    public static function getUserSendOrder(int $uid)
    {
        $send_order_id = Redis::hGet('book_read:' . $uid, 'send_order_id');
        $send_order_id = (int) ($send_order_id ? $send_order_id : 0);
        return $send_order_id;
    }


    public static function qappAddDesktop(int $uid, int $status)
    {
        myLog('incrAddDeskTop')->info('qappAddDesktop', compact('uid', 'status'));
        $log = QappUserAddDestop::where('uid', $uid)->orderBy('id', 'desc')->first();
        if ((!$log && $status == 1) || ($log && $log->status != $status)) {
            if ($status == 1) {
                $job = new UserAddDeskJob($uid);
                dispatch($job)->onConnection('rabbitmq')->onQueue('qapp_user_add_desk')->delay(now()->addMinutes(3));
            }
            QappUserAddDestop::create([
                'uid' => $uid,
                'status' => $status
            ]);
        }

        // 加桌统计
        if (!$log && $status === 1) {
            QappAddDeskTopService::incrAddDeskTop($uid, QuickConst::FIELD_ADD_DESKTOP);
            UserTaskService::addUserTaskQueue($uid, BaseTask::add_desk, UserTaskService::add_trigger);
        }
    }

    /**
     * 创建用户
     * $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', 'balance', 'charge_balance', 'reward_balance')->first();
    }

    static function getUserByOpenidAndChannelId($openid, $channel_id)
    {
        return User::where('openid', $openid)->where('distribution_channel_id', $channel_id)->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]);
    }

    // 扔用户一些动作到队列，异步处理一些额外逻辑
    static function PushUserActionToQueue($action_type, $distribution_channel_id, $param)
    {
        try {
            //     		\Log::info('PushUserActionToQueue_param_start:'.$distribution_channel_id.' action_type:'.$action_type. ' param:'.json_encode($param));

            // 判断站点是否需要额外逻辑
            $distribution_self_define_config = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id, 'action_call_ycsd');
            if (empty($distribution_self_define_config)) {
                //     			\Log::info('not_action_call_ycsd:'.$distribution_channel_id);
                return '';
            } else {
                \Log::info('PushUserActionToQueue_param:' . $distribution_channel_id . ' action_type:' . $action_type . ' param:' . json_encode($param));
                // 如果支付通道已经切换回去，则不推送了
                //     			$pay_merchant_id = env('YCSD_CALL_PAY_MERCHANT_ID');

                // 当前默认
                $pay_merchant_id = Redis::get('YCSD_CALL_PAY_MERCHANT_ID');
                $channel = Channel::getById($distribution_channel_id);
                $current_pay_merchant_id = isset($channel->pay_merchant_id) ? $channel->pay_merchant_id : '';
                \Log::info('action_call_ycsd:' . $distribution_channel_id . ' $pay_merchant_id:' . $pay_merchant_id . ' $current_pay_merchant_id:' . $current_pay_merchant_id);
                if ($current_pay_merchant_id != $pay_merchant_id) {
                    //  判断订单是否是默认支付，放行，切换期间的bug
                    if ($action_type == 'CallBackOrder') {
                        $order = Order::getByTradeNo($distribution_channel_id, $param['order_sn']);
                        if (isset($order->pay_merchant_id) && $order->pay_merchant_id == $pay_merchant_id) {
                            \Log::info('action_call_ycsd_old_order_continue:' . $param['order_sn']);
                        } else {
                            \Log::info('action_call_ycsd_has_change_pay_return:' . $distribution_channel_id);
                            return '';
                        }
                    } else {
                        \Log::info('action_call_ycsd_has_change_pay_return:' . $distribution_channel_id);
                        return '';
                    }
                }

                \Log::info('action_call_ycsd:' . $distribution_channel_id);
            }

            $data = [];
            $data['send_time'] = date("Y-m-d H:i:s");
            $data['action_type'] = $action_type;
            if ($action_type == 'Register') {
                $data['openid'] =  $param['openid'];
                $data['uid'] = $param['uid'];
            } elseif ($action_type == 'CreateOrder') {
                $data['orderSn'] =  $param['order_sn'];
                $data['amount'] = $param['amount'];
                $data['openid'] =  $param['openid'];
                $data['uid'] = $param['uid'];
            } elseif ($action_type == 'CallBackOrder') {
                $data['orderSn'] =  $param['order_sn'];
                $data['openid'] =  $param['openid'];
            }

            $send_data = array(
                'send_time' => date("Y-m-d H:i:s"),
                'data' => $data
            );
            \Log::info('PushUserActionToQueue_openid:' . $data['openid'] . ' action_type:' . $action_type);
            \Log::info('$send_data');
            \Log::info($send_data);

            $delay = 0;

            $job = (new ActionTrigger($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('action_trigger_list');
            dispatch($job);
        } catch (\Exception $e) {
            \Log::info('ept:' . $e->getMessage());
        }
    }

    public static function isCpcUser($uid)
    {
        //openid下所有强关超过三天的uid都无充值，对强关后的uid进行曝光
        //openid下有一个强关超过三天的uid,都无充值，对强关后的uid进行曝光
        $sql_format = "SELECT u.id,f.subscribe_time,(SELECT id from orders where uid = u.id and `status` = 'PAID' LIMIT 1)as oid  FROM users u
JOIN force_subscribe_users f on u.id = f.uid and f.is_subscribed= 1
WHERE u.openid in (SELECT openid from users WHERE  id = %s)";
        $result = DB::select(sprintf($sql_format, $uid));
        if (!$result) return false;

        $is_has_force_subscribe_three_days = false;
        foreach ($result as $item) {
            //有充值
            if ($item->oid) return false;
            //强关没超过超过三天
            //if(time()-strtotime($item->subscribe_time) < 86400*3) return false;
            if (time() - strtotime($item->subscribe_time) > 86400 * 3) $is_has_force_subscribe_three_days = true;
        }
        return $is_has_force_subscribe_three_days;
    }

    public static function recordUA($ua, $uid)
    {
        return UserEnv::recordUA($ua, $uid);
    }

    public static function transfer(int $from, int $to, int $distribution_channel_id)
    {
        $transfer_record = DB::table('crm_transfer')->where('from_uid', $from)->first();
        if ($transfer_record) {
            return;
        }
        $from_user = self::getById($from);
        $to_user = self::getById($to);
        if (!$from_user) return;
        if (!$to_user) return;
        //阅读记录迁移***************************************
        $record = Redis::hgetall('book_read:' . $from);
        $not_uid_key = ['last_read', 'sign_counts', 'sign_info', 'sign_day'];
        $data = [];
        foreach ($record as $k => $item) {
            if (is_numeric($k) || in_array($k, $not_uid_key)) {
                $data[$k] = $item;
            }
        }
        //\Log::info('read record is');
        //\Log::info($data);
        if ($data) Redis::hmset('book_read:' . $to, $data);
        //签到记录
        /*$user_sign_model = new UserSign();
        $user_sign_model->setCurrentTable(date('Ym'));
        $sign_record = $user_sign_model->where('uid',$from)->select('price','sign_time','day','created_at')->orderBy('sign_time','desc')->get();
        $temp = [];
        if($sign_record){
            foreach ($sign_record as $item){
                $temp[] = [
                    'uid'=>$to,
                    'price'=>$item->price,
                    'day'=>$item->day,
                    'sign_time'=>$item->sign_time,
                    'created_at'=>$item->created_at,
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
            }
            //\Log::info('user_sign  is');
            //\Log::info($temp);
            DB::table('user_sign'.date('Ym'))->insert($temp);
        }*/
        //订阅记录（按本）
        $book_order = BookOrder::where('uid', $from)->where('bid', '>', 0)->get();
        if ($book_order) {
            $temp = [];
            foreach ($book_order as $book) {
                $temp[] = [
                    'distribution_channel_id' => $distribution_channel_id,
                    'bid' => $book->bid,
                    'book_name' => $book->book_name,
                    'uid' => $to,
                    'u' => $book->u,
                    'fee' => 0,
                    'created_at' => $book->created_at,
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
            }
            //\Log::info('book_order  is');
            //\Log::info($temp);
            DB::table('book_orders')->insert($temp);
        }
        //订阅记录（按章）
        $chapter_order_record = ChapterOrderService::getRecordByUid($from, '', '', true);
        if ($chapter_order_record) {
            $temp = [];
            $i = 1;
            $chapter_model = new ChapterOrder();
            $chapter_model->setCurrentTable($to);

            foreach ($chapter_order_record as $chapter_order) {
                $temp[] = [
                    'distribution_channel_id' => $distribution_channel_id,
                    'bid' => $chapter_order->bid,
                    'cid' => $chapter_order->cid,
                    'chapter_name' => $chapter_order->chapter_name,
                    'book_name' => $chapter_order->book_name,
                    'uid' => $to,
                    'send_order_id' => 0,
                    'fee' => 0,
                    'created_at' => $chapter_order->created_at,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                if ($i % 100 == 0) {
                    $chapter_model->insert($temp);
                    $temp = [];
                }
                $i++;
            }
            //\Log::info('chapter order  is');
            //\Log::info($temp);
            $chapter_model->insert($temp);
        }
        //打赏记录
        $gift_result = BookGiftsSend::where('uid', $from)->get();
        if ($gift_result) {
            $tmp = [];
            foreach ($gift_result as $g) {
                $tmp[] =  [
                    'uid' => $to,
                    'gift_id' => $g->gift_id,
                    'bid' => $g->bid,
                    'icon' => $g->icon,
                    'name_desc' => $g->name_desc,
                    'cost' => 0,
                    'cost_reward' => $g->cost_reward,
                    'cost_recharge' => $g->cost_recharge,
                    'created_at' => $g->created_at,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
            //\Log::info('book gift   is');
            //\Log::info($temp);
            DB::table('book_gifts_send')->insert($tmp);
        }
        //书架
        $result = UserShelfBooks::where('uid', $from)->get();
        if ($result) {
            $tmp = [];
            foreach ($result as $s) {
                $tmp[] = [
                    'uid' => $to,
                    'distribution_channel_id' => $distribution_channel_id,
                    'bid' => $s->bid,
                    'created_at' => $s->created_at,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
            //\Log::info('user book shelf  is');
            //\Log::info($temp);
            DB::table('user_shelf_books')->insert($tmp);
        }
        //包年
        $result = DB::table('year_orders')->where('uid', $from)->where('end_time', '>=', date('Y-m-d H:i:s'))->first();
        if ($result) {
            DB::table('year_orders')->insert([
                'uid' => $to,
                'begin_time' => $result->begin_time,
                'end_time' => $result->end_time,
                'distribution_channel_id' => $distribution_channel_id,
                'send_order_id' => $result->send_order_id,
                'fee' => $result->fee,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => $result->updated_at,
            ]);
            //\Log::info('year_orders  is');
            //print_r($result);
        }

        //书币

        $to_user->balance += $from_user->balance;
        $to_user->reward_balance +=   $from_user->balance;
        $to_user->nickname = $from_user->nickname;
        $to_user->sex = $from_user->sex;
        $to_user->head_img = $from_user->head_img;
        $to_user->country = $from_user->country;
        $to_user->city = $from_user->city;
        $to_user->province = $from_user->province;
        $to_user->save();
        DB::table('crm_transfer')->insert([
            'from_uid' => $from,
            'to_uid' => $to,
            'is_enable' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }

    public static function getUserByOpenid($openid)
    {
        return User::where('openid', $openid)->get();
    }
}
