<?php

namespace App\Modules\User\Services;

use App\Modules\Channel\Models\Channel;
use App\Modules\Subscribe\Models\BookOrder;
use App\Modules\Subscribe\Models\YearOrder;
use App\Modules\User\Models\User;
use DB;

/**
 * 站点用户
 */
class SiteUser
{
    private $users;
    private $openid;
    private $channel_id;
    private $user;

    public function  __construct($openid)
    {
        $this->openid = $openid;
        $this->users = [];
    }

    /**
     * 获取user
     */
    public function getChannelUser()
    {
        $funcs = [
            'getUserFromLinkData', 'getUsersOnlyChannel',
            'getUserFromYearOrder', 'getUserFromChapterOrderBeforeThreeDays',
            'getUserFromChapterOrderLastThreeDays', 'getUserFromLast'
        ];
        foreach ($funcs as $func) {
            if (!$this->channel_id) {
                $this->$func();
            }
        }
        if ($this->channel_id) {
            return $this->user;
        } else {
            return [0, 0];
        }
    }

    /**
     * 已绑定关系
     */
    private function getUserFromLinkData()
    {
        $friend_link_uid_bind = DB::table('friend_link_uid_bind')->where('openid', $this->openid)->orderBy('id', 'desc')->first();
        if ($friend_link_uid_bind) {
            $user = User::where('id', $friend_link_uid_bind->uid)->select('id', 'distribution_channel_id')->first();
            if ($user) {
                $this->channel_id = $user->distribution_channel_id;
                $this->user = [$user->id, $this->channel_id];
            }
        }
    }

    /**
     * 唯一渠道
     */
    private function getUsersOnlyChannel()
    {
        $users = User::where('openid', $this->openid)->select('id', 'distribution_channel_id')->get()->all();
        $inner_channels = Channel::join('channel_users', 'channel_users.id', '=', 'distribution_channels.channel_user_id')
            ->select('distribution_channels.id')
            ->whereIn('channel_users.id', explode(',', redisEnv('PROMOTION_GROUP_CHANNEL_USER_ID')))
            ->get()
            ->pluck('id')
            ->toArray();
        foreach ($users as $user) {
            if (in_array($user->distribution_channel_id, $inner_channels)) {
                $this->users[] = $user;
            }
        }
        if (!$this->users) {
            $this->users = $users ?? [];
        }
        if (count($this->users) == 1) {
            $this->setUserLink($this->users[0]->id);
            $this->channel_id = $this->users[0]->distribution_channel_id;
        }
    }

    /**
     * 有包年的，按最新的包年记录渠道
     */
    private function getUserFromYearOrder()
    {
        $users = $this->users;
        $year_order = YearOrder::whereIn('uid', collect($users)->pluck('id')->all())->orderBy('end_time', 'desc')->first();
        if ($year_order) {
            //筛选包年结束时间最后的UID
            foreach ($users as $item) {
                if ($item->id == $year_order->uid) {
                    $this->setUserLink($item->id);
                    $this->channel_id = $item->distribution_channel_id;
                }
            }
        }
    }

    /**
     * 有订阅记录的3天的历史纪录，按最多的订阅渠道
     */
    private function getUserFromChapterOrderBeforeThreeDays()
    {
        $users_select = ['id' => 0, 'count' => 0, 'user' => null, 'create_time' => 0];
        foreach ($this->users as $user) {
            $table_prefix = ($user->id) % 512;
            $chapter_count = DB::connection('chapter_order_mysql')
                ->table('chapter_orders' . $table_prefix)
                ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-3 day')))
                ->where('uid', $user->id)
                ->count('id');
            $book_order = BookOrder::where('uid', $user->id)
                ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-3 day')))
                ->first();
            if ($book_order) {
                $chapter_count += 30;
            }
            if ($chapter_count > $users_select['count']) {
                $users_select['id'] = $user->id;
                $users_select['count'] = $chapter_count;
                $users_select['user'] = $user;
            }
        }
        if ($users_select['id'] > 0) {
            $this->setUserLink($users_select['id']);
            $this->channel_id = $users_select['user']->distribution_channel_id;
        }
    }

    /**
     * 有订阅记录的最近3天，按最新的订阅渠道
     */
    private function getUserFromChapterOrderLastThreeDays()
    {
        $users_select = ['id' => 0, 'count' => 0, 'user' => null, 'create_time' => 0];
        foreach ($this->users as $user) {
            $table_prefix = ($user->id) % 512;
            $chapter_order = DB::connection('chapter_order_mysql')
                ->table('chapter_orders' . $table_prefix)
                ->where('uid', $user->id)
                ->orderBy('created_at', 'desc')
                ->first();
            $book_order = BookOrder::where('uid', $user->id)
                ->first();
            if ($chapter_order) {
                if (strtotime($chapter_order->created_at) > $users_select['create_time']) {
                    $users_select['id'] = $user->id;
                    $users_select['create_time'] = strtotime($chapter_order->created_at);
                    $users_select['user'] = $user;
                }
            }
            if ($book_order) {
                if (strtotime($book_order->created_at) > $users_select['create_time']) {
                    $users_select['id'] = $user->id;
                    $users_select['create_time'] = strtotime($book_order->created_at);
                    $users_select['user'] = $user;
                }
            }
        }
        if ($users_select['id'] > 0) {
            $this->setUserLink($users_select['id']);
            $this->channel_id = $users_select['user']->distribution_channel_id;
        }
    }

    /**
     * 最后选择默认第一个渠道
     */
    private function getUserFromLast()
    {
        if ($this->users) {
            $this->setUserLink($this->users[0]->id);
            $this->channel_id = $this->users[0]->distribution_channel_id;
        }
    }

    private function setUserLink($uid)
    {
        $friend_link_uid_bind = ['uid' => $uid, 'openid' => $this->openid, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
        DB::table('friend_link_uid_bind')->insert($friend_link_uid_bind);
        $this->user = [$uid, $this->channel_id];
    }
}
