<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use DB;
use Redis;

class ActiveUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'au';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $appids = $this->getAppids();
        if(!$appids) return ;
        foreach ($appids as $appid) {
            $this->getUser($appid);
        }
    }

    //获取appid
    private function getAppids():array
    {
        //return ['wxb9fe767d99513216'];
        $data = [];
        $appids = DB::table('media_push_gzhs')->where('is_enabled',1)->select('appid')->get();
        if(!$appids) return $data;
        foreach ($appids as $appid_info){
            $data[] = $appid_info->appid;
        }
        return $data;
    }

    private function getUser($appid)
    {
        $count = DB::table('force_subscribe_users')->where('appid', $appid)->where('is_subscribed', 1)->count();
        //echo '$count is:' . $count . PHP_EOL;
        //echo ' ceil($count/1000) is:' . ceil($count / 1000) . PHP_EOL;
        for ($i = 0, $c = ceil($count / 1000); $i < $c; $i++) {
            //echo 'now is the ' . $i . 'times' . PHP_EOL;
            $result = DB::table('force_subscribe_users')
                ->select('uid', 'distribution_channel_id', 'appid', 'openid', 'subscribe_time', 'last_interactive_time')
                ->orderBy('created_at', 'desc')
                ->offset($i * 1000)->limit(1000)->get();
            if (!$result)
                break;
            //echo 'foreach start' . PHP_EOL;
            foreach ($result as $v) {
                $temp_time = 0;
                //签到时间
                $sign = DB::table('smart_push_user_sign')->where('uid', $v->uid)->where('day', Carbon::yesterday()->format('Y-m-d'))->select('sign_time')->first();
                if ($sign) $temp_time = $sign->sign_time;
                //阅读时间
                $read_record = Redis::hget('book_read:' . $v->uid, 'last_read');
                if ($read_record) {
                    $arr = explode('_', $read_record);
                    $read_time = isset($arr[2]) ? $arr[2] : 0;
                    $temp_time = $read_time > $temp_time ? $read_time : $temp_time;
                }
                //交互时间
                $last_interactive_time = Carbon::createFromFormat('Y-m-d H:i:s', $v->last_interactive_time)->timestamp;
                if ($last_interactive_time > Carbon::yesterday()->timestamp) {
                    $temp_time = $last_interactive_time > $temp_time ? $last_interactive_time : $temp_time;
                }

                if (!$temp_time || $temp_time < Carbon::yesterday()->timestamp) continue;
                $hour = Carbon::createFromTimestamp($temp_time)->hour;
                if ($hour >= 22 || $hour <= 6) {
                    $hour = 10;
                }
                $result = $this->updateOrCreateMediaPushUser($v->uid, $v->openid, $v->distribution_channel_id, $v->appid, $hour, $v->subscribe_time);
                $pay_info = DB::table('orders')->where('uid', $v->uid)->where('status', 'PAID')->orderBy('id')->first();
                $now = Carbon::now();
                $days_num_in_month = $now->daysInMonth;
                //这个月剩余天数
                $last_days = $days_num_in_month - $now->day + 1;
                if (Carbon::createFromFormat('Y-m-d H:i:s', $v->subscribe_time)->format('Y-m-d') == Carbon::yesterday()->format('Y-m-d')) {
                    //关注
                    if ($pay_info) {
                        //echo 'paid $uid is: ' . $v->uid . '----------------------------------------' . PHP_EOL;
                        //已经付费
                        $o = DB::table('media_push_user_details')->where('media_push_user_id', $result[0])->where('created_at', '>=', date('Y-m-d 00:00:00'))->count();
                        //echo '$o is ' . $o . ',----------------' . PHP_EOL;
                        if (!$o) {
                            $days = $this->selectDay($last_days, 4, Carbon::createFromFormat('Y-m-d H:i:s', $v->last_interactive_time)->addDay(2));
                            $this->updateOrCreateMediaPushUserDetail($v->uid, $result[0], $days);
                        }
                    } else {
                        //echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' . PHP_EOL;
                        //echo 'no pay $uid is: ' . $v->uid . '----------------------------------------' . PHP_EOL;
                        //未付费
                        if ($last_days > 8) {
                            $num = ceil($last_days / 2);
                        } else {
                            $num = $last_days;
                        }
                        $o = DB::table('media_push_user_details')->where('media_push_user_id', $result[0])->where('created_at', '>=', date('Y-m-d 00:00:00'))->count();
                        if (!$o) {
                            $days = $this->selectDay($num, 4, Carbon::createFromFormat('Y-m-d H:i:s', $v->last_interactive_time)->addDay(2));

                            $this->updateOrCreateMediaPushUserDetail($v->uid, $result[0], $days);
                        }
                    }
                } else {
                    //非当日强关
                    if ($pay_info && date('Y-m-d', strtotime($pay_info->created_at)) == date('Y-m-d', time() - 86400)) {
                        //echo 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,$uid is :' . $v->uid . PHP_EOL;
                        //充值了
                        $old = DB::table('media_push_user_details')->where('uid', $v->uid)->where('created_at', '>=', date('Y-m-d 00:00:00'))->count();
                        $all = DB::table('media_push_user_details')->where('uid', $v->uid)->where('created_at', '>=', date('Y-m-01 00:00:00'))->count();
                        $one = DB::table('media_push_user_details')->where('uid', $v->uid)->where('created_at', '>=', date('Y-m-01 00:00:00'))->first();
                        //echo sprintf('$old is: %s,$all is: %s,%s',$old,$all,PHP_EOL);
                        //print_r($one);
                        if ($all && $old) {
                            $days = $this->selectDay($last_days, $old, $now);
                            foreach ($days as $k => $vd) {
                                DB::table('media_push_user_details')
                                    ->where('media_push_user_id', $one->media_push_user_id)
                                    ->where('sort_no', $all - $old + $k + 1)
                                    ->update(['updated_at' => date('Y-m-d H:i:s'), 'send_time' => $vd]);
                            }
                        }
                    } else {
                        if ($last_days > 8) {
                            $num = ceil($last_days / 2);
                        } else {
                            $num = $last_days;
                        }
                        //echo 'ddddddddddddddddddddddddddddddddddddddd' . PHP_EOL;
                        $days = $this->selectDay($num, 4, $now);
                        $this->updateOrCreateMediaPushUserDetail($v->uid, $result[0], $days, 'old');
                    }

                }
            }
        }
    }

    private function updateOrCreateMediaPushUser($uid, $openid, $distribution_channel_id, $appid, $active_hour, $sub_time)
    {
        $old = DB::table('media_push_users')->where('uid', $uid)->where('openid', $openid)->select('id')->first();
        $updated_at = Carbon::now()->format('Y-m-d H:i:s');
        $created_at = $updated_at;
        if ($old) {
            $id = $old->id;
            $type = 'update';
            DB::table('media_push_users')->where('id', $old->id)->update(compact('active_hour', 'updated_at'));
        } else {
            $id = DB::table('media_push_users')->insertGetId(
                compact('uid', 'openid', 'distribution_channel_id', 'appid', 'active_hour', 'sub_time', 'created_at', 'updated_at')
            );
            $type = 'create';
        }
        return [$id, $type];
    }

    private function updateOrCreateMediaPushUserDetail($uid, $media_push_user_id, $days, $type = 'new')
    {
        if (!$days) return;

        $data = [];
        if ($type == 'new') {
            foreach ($days as $k => $d) {
                $data[] = ['media_push_user_id' => $media_push_user_id, 'uid' => $uid, 'is_send' => 0, 'sort_no' => $k + 1, 'send_time' => $d, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()];
            }
            DB::table('media_push_user_details')->insert($data);
        }
        if ($type == 'old') {
            $o = DB::table('media_push_user_details')->where('uid', $uid)->where('created_at', '>=', date('Y-m-01 00:00:00'))->count();
            if (!$o) {
                foreach ($days as $k => $d) {
                    $data[] = ['media_push_user_id' => $media_push_user_id, 'uid' => $uid, 'is_send' => 0, 'sort_no' => $k + 1, 'send_time' => $d, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()];
                }
                DB::table('media_push_user_details')->insert($data);
            }
        }

        if ($type == 'update') {

        }
    }

    /**
     * @param int $uid
     * @param bool $is_charge 是否充值
     * @return array
     */
    private function getFourDate(int $uid, bool $is_charge, int $count = 4)
    {
        $now = Carbon::now();
        $days_num_in_month = $now->daysInMonth;
        //这个月剩余天数
        $last_days = $days_num_in_month - $now->day + 1;

        $num = 10;
        return $this->selectDay($num, $count, $now);
    }

    private function selectDay(int $alldays, int $selectCount = 4, $start_day):array
    {
        $start_day = $start_day->format('Y-m-d');
        //echo '$alldays is :' . $alldays . '--$selectCount is :' . $selectCount . '--$start_day is: ' . $start_day . PHP_EOL;
        $days = [];
        $month = Carbon::now()->month;
        for ($i = 0; $i < $alldays; $i++) {
            $temp_timestamp = strtotime($start_day) + $i * 86400;
            $temp = date('Y-m-d', $temp_timestamp);
            if (date('n', $temp_timestamp) != $month) {
                break;
            }
            $days[] = $temp;
        }

        if (empty($days) || count($days) <= $selectCount) return $days;
        $result = [];
        $c = 0;
        $saturdays = [];
        foreach ($days as $key => $v) {
            if (date('N', strtotime($v)) == 6) {
                $saturdays[] = $key;
                array_push($result, $v);
                if (++$c == $selectCount) return $result;
            }
        }
        $rate = (count($days) - 1) / $selectCount;
        $temp_count = 0;
        $temp_count2 = 0;
        for ($k = 0, $d = count($days); $k < $d; $k++) {
            $temp_count2++;
            $temp = $k + $rate * ($k);
            $key = round($temp);
            $key = $key < 0 ? 0 : $key;
            if (!isset($days[$key]) || count($result) >= $selectCount) {
                break;
            }
            if (isset($saturdays[$temp_count])) {
                if (abs($saturdays[$temp_count] - $temp) >= $rate * 0.8) {
                    $result[] = $days[$key];
                    if ($key >= $saturdays[$temp_count]) {
                        $temp_count++;
                    }
                } else {
                    continue;
                }
            } else {
                $result[] = $days[$key];
                if (isset($saturdays[$temp_count]) && $key >= $saturdays[$temp_count]) {
                    $temp_count++;
                }
            }
        }
        usort($result, function ($a, $b) {
            return strtotime($a) >= strtotime($b);
        });
        $result_count = count($result);
        if ($result_count < $selectCount) {
            $start = $days[0];
            $end = $days[count($days) - 1];
            $last = [];
            for ($i = 0; $i <= $result_count; $i++) {
                if ($i == 0) {
                    $last[] = strtotime($result[$i]) - strtotime($start);
                    continue;
                }
                if ($i == $result_count) {
                    $last[] = strtotime($end) - strtotime($result[$i - 1]);
                    continue;
                }

                $last[] = strtotime($result[$i]) - strtotime($result[$i - 1]);
            }
            if ($last) {
                $max = max($last);
                $max_key = [];
                foreach ($last as $lk => $l) {
                    if ($max == $l) {
                        $max_key[] = $lk;
                    }
                }
                $other_key = array_random($max_key);
                if ($other_key > $result_count) {
                    array_push($result, date('Y-m-d', strtotime($result[$result_count - 1]) + $max / 2));
                } else if ($other_key == 0) {
                    array_push($result, date('Y-m-d', strtotime($start) + $max / 2));
                } else {
                    array_push($result, date('Y-m-d', strtotime($result[$other_key - 1]) + $max / 2));
                }
            }
            usort($result, function ($a, $b) {
                return strtotime($a) >= strtotime($b);
            });
        }
        return $result;
    }

    private function test()
    {
        $result = $this->selectDay(4, 4, Carbon::now());
        echo "---------------------------------------------------\r\n";
        if ($result) {
            foreach ($result as $v) {
                echo $v . PHP_EOL;
            }
        }
    }
}
