<?php

namespace App\Console\Commands\Upgrade;

use App\Models\Deed\EachLikeModel;
use App\Models\Deed\FriendsLogModel;
use App\Models\Deed\InvitationCardModel;
use App\Models\Fpdx\RoomModel;
use App\Models\Friends\FriendApplyModel;
use App\Models\Friends\FriendModel;
use App\Models\Goodnight\RoomMemberModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class V2173 extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'upgrade:V2173 {task} {--d}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '好友列表优化批量处理数据脚本:提取旧的数据[晚安匹配|72h匹配|开黑匹配|好友申请|相互心动|取消心动]的数据按照新的数据格式存储';

    protected $take = 50000;

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $deamon = $this->option('d');
        $task = $this->argument('task');
        switch ($task) {
            case "oldInvite":
                $this->oldInvite($deamon);
                break;
            case 'newInvite':
                $this->newInvite($deamon);
                break;
            case 'agree':
                $this->agree($deamon);
                break;
            case 'pair':
                $this->pair($deamon);
                break;
            case 'gteam':
                $this->gteam($deamon);
                break;
            case 'goodnight':
                $this->goodnight($deamon);
                break;
            case 'eachlike':
                $this->eachlike($deamon);
                break;
            case 'uneachlike':
                $this->unEachlike($deamon);
                break;
            case 'hidefriend':
                $this->hidefriend($deamon);
                break;
        }
    }

    // 相互心动
    public function eachlike($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "eachlike") ?? 0;
            $bar = $this->output->createProgressBar(EachLikeModel::where('id', '>', $last_id)->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "eachlike") ?? 0;
            $eachlikes = EachLikeModel::where('id', '>', $last_id)->take($this->take)->get();
            foreach ($eachlikes as $eachlike) {
                /** @var EachLikeModel $eachlike */
                DB::table('kdgx_fpdx_friends_log_tmp')->insert([
                    'uid' => $eachlike->uid,
                    'tuid' => $eachlike->tuid,
                    'created_at' => $eachlike->created_at,
                    'do' => 0,
                    'attach' => ""
                ]);
                Redis::hset("v2173", "eachlike", $eachlike->id);
            }
            if (!$deamon) {
                $bar->advance($this->take);
            }
        } while ($eachlikes->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 取消心动
    public function unEachlike($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "uneachlike") ?? 0;
            $bar = $this->output->createProgressBar(FriendsLogModel::whereDo(1)->where('id', '>', $last_id)->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "uneachlike") ?? 0;
            $eachlikes = FriendsLogModel::whereDo(1)->where('id', '>', $last_id)->take($this->take)->get();
            foreach ($eachlikes as $eachlike) {
                /** @var EachLikeModel $eachlike */
                DB::table('kdgx_fpdx_friends_log_v2_17_3')->insert([
                    'uid' => $eachlike->uid,
                    'tuid' => $eachlike->tuid,
                    'created_at' => $eachlike->created_at->timestamp,
                    'do' => 1,
                    'attach' => ""
                ]);
                Redis::hset("v2173", "uneachlike", $eachlike->id);
                if (!$deamon) {
                    $bar->advance(1);
                }
            }
        } while ($eachlikes->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 旧的好友申请
    public function oldInvite($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "old_invite") ?? 0;
            $bar = $this->output->createProgressBar(InvitationCardModel::where([
                ['uid', '!=', 0],
                ['invite_uid', '!=', 0]
            ])->where('id', '>', $last_id)->whereNull('kk')->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "old_invite") ?? 0;
            $invitations = InvitationCardModel::where([
                ['uid', '!=', 0],
                ['invite_uid', '!=', 0]
            ])->where('id', '>', $last_id)->whereNull('kk')->orderBy('id', 'asc')->take($this->take)->get();
            foreach ($invitations as $invitation) {
                /** @var InvitationCardModel $invitation */
                DB::table('kdgx_fpdx_friends_log_v2_17_3')->insert([
                    'uid' => $invitation->uid,
                    'tuid' => $invitation->invite_uid,
                    'created_at' => $invitation->created_at->timestamp,
                    'do' => 3,
                    'attach' => json_encode([
                        [
                            'type' => -1,
                            'question' => 0,
                            'answer' => []
                        ]
                    ])
                ]);

                /** @var FriendApplyModel $send */
                $send = FriendApplyModel::firstOrNew([
                    'uid' => $invitation->uid,
                    'apply_uid' => $invitation->invite_uid
                ], [
                    'uid' => $invitation->uid,
                    'apply_uid' => $invitation->invite_uid
                ]);
                $send->last_at = $invitation->created_at->timestamp;
                $send->is_apply = 1;
                $send->last_msg = "向ta发出了好友申请";

                /** @var FriendApplyModel $apply */
                $apply = FriendApplyModel::firstOrNew([
                    'uid' => $invitation->invite_uid,
                    'apply_uid' => $invitation->uid
                ], [
                    'uid' => $invitation->invite_uid,
                    'apply_uid' => $invitation->uid
                ]);
                $apply->last_at = $invitation->created_at->timestamp;
                $apply->is_receive = 1;
                $apply->last_msg = "收到ta发出的好友申请";

                $send->save() && $apply->save();

                Redis::hset("v2173", "old_invite", $invitation->id);
                if (!$deamon) {
                    $bar->advance(1);
                }
            }
        } while ($invitations->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 新的好友申请
    public function newInvite($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "new_invite") ?? 0;
            $bar = $this->output->createProgressBar(InvitationCardModel::where([
                ['uid', '!=', 0],
                ['invite_uid', '!=', 0]
            ])->where('id', '>', $last_id)->whereNotNull('kk')->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "new_invite") ?? 0;
            $invitations = InvitationCardModel::where([
                ['uid', '!=', 0],
                ['invite_uid', '!=', 0]
            ])->where('id', '>', $last_id)->whereNotNull('kk')->orderBy('id', 'asc')->take($this->take)->get();
            foreach ($invitations as $invitation) {
                /** @var InvitationCardModel $invitation */
                try {
                    $question = array();
                    $uid = $invitation->uid;
                    $tuid = $invitation->invite_uid;
                    $time = $invitation->created_at->timestamp;
                    $tmp = array(
                        'type' => $invitation->question_type,
                        'question' => 0 != $invitation->question_type ? $invitation->question_id : 0,
                        'answer' => [
                            'type' => 'text',
                            'value' => ""
                        ]
                    );
                    switch ($invitation->question_type) {
                        case 0:
                            $tmp['answer']['type'] = "text";
                            $tmp['answer']['value'] = $invitation->say_hello;
                            break;
                        case 2:
                        case 3:
                            if (strpos('oss.pocketuniversity.cn', $invitation->question_answer)) {
                                $tmp['answer']['type'] = "url";
                                $tmp['answer']['value'] = $invitation->question_answer;
                            } else {
                                $imp = explode(":", $invitation->question_answer);
                                $tmp['answer']['type'] = $imp[0];
                                $tmp['answer']['value'] = $imp[1];
                            }
                            break;
                        default:
                            break;
                    }
                    array_push($question, $tmp);
                    DB::table('kdgx_fpdx_friends_log_tmp')->insert([
                        'uid' => $uid,
                        'tuid' => $tuid,
                        'created_at' => $time,
                        'do' => 3,
                        'attach' => json_encode($question)
                    ]);

                    /** @var FriendApplyModel $send */
                    $send = FriendApplyModel::firstOrNew(
                        array('uid' => $uid, 'apply_uid' => $tuid),
                        ['uid' => $uid, 'apply_uid' => $tuid]
                    );
                    $send->last_at = $time;
                    $send->is_apply = 1;
                    $send->last_msg = "向ta发出了好友申请";

                    /** @var FriendApplyModel $apply */
                    $apply = FriendApplyModel::firstOrNew(
                        array('uid' => $tuid, 'apply_uid' => $uid),
                        ['uid' => $tuid, 'apply_uid' => $uid]
                    );
                    $apply->last_at = $time;
                    $apply->is_receive = 1;
                    $apply->last_msg = "收到ta发出的好友申请";

                    $send->save() && $apply->save();
                } catch (\Exception $exception) {
                }

                Redis::hset("v2173", "new_invite", $invitation->id);
            }

            if (!$deamon) {
                $bar->advance($this->take);
            }
        } while ($invitations->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 同意申请
    public function agree($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "agree") ?? 0;
            $bar = $this->output->createProgressBar(InvitationCardModel::where('id', '>', $last_id)
                ->where('receive_at', '>', 0)->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "agree") ?? 0;
            $applys = InvitationCardModel::where('id', '>', $last_id)
                ->where('receive_at', '>', 0)
                ->take($this->take)
                ->get();
            foreach ($applys as $apply) {
                if (!$deamon) {
                    $bar->advance(1);
                }
                /** @var InvitationCardModel $apply */
                if (
                    DB::table('kdgx_fpdx_friends_log_v2_17_3')->where([
                    ['uid', $apply->invite_uid],
                    ['tuid', $apply->uid],
                    ['do', 4]
                    ])->exists()
                ) {
                    continue;
                }
                DB::table('kdgx_fpdx_friends_log_v2_17_3')->insert([
                    'uid' => $apply->invite_uid,
                    'tuid' => $apply->uid,
                    'created_at' => $apply->receive_at,
                    'do' => 4
                ]);
                Redis::hset("v2173", "agree", $apply->id);
            }
        } while ($applys->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 72h匹配
    public function pair($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "pair") ?? 0;
            $bar = $this->output->createProgressBar(RoomModel::where('room_id', '>', $last_id)
                ->where('type', 1)->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "pair") ?? 0;
            $rooms = RoomModel::where('room_id', '>', $last_id)->where('type', 1)->take($this->take)
                ->get(['room_id', 'stage_id', 'member', 'create_time']);
            foreach ($rooms as $room) {
                /** @var RoomModel $room */
                DB::table('kdgx_fpdx_friends_log_tmp')->insert([
                    'uid' => $room->member[0],
                    'tuid' => $room->member[1],
                    'created_at' => $room->create_time,
                    'do' => 2,
                    'attach' => json_encode([
                        'room_id' => $room->room_id,
                        'stage_id' => $room->stage_id,
                        'created_at' => $room->create_time
                    ])
                ]);
                Redis::hset("v2173", "pair", $room->room_id);
                if (!$deamon) {
                    $bar->advance(1);
                }
            }
        } while ($rooms->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 晚安匹配
    public function goodnight($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "goodnight") ?? 0;
            $bar = $this->output->createProgressBar(\App\Models\Goodnight\RoomModel::where(
                'id',
                '>',
                $last_id
            )->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "goodnight") ?? 0;
            $rooms = \App\Models\Goodnight\RoomModel::where('id', '>', $last_id)->take($this->take)->get([
                'id',
                'created_at'
            ]);
            foreach ($rooms as $room) {
                /** @var \App\Models\Goodnight\RoomModel $room */
                $members = RoomMemberModel::where('room_id', $room->id)->get(['uid'])->toArray();
                $uid = $members[0]['uid'];
                $tuid = $members[1]['uid'];
                DB::table('kdgx_fpdx_friends_log_tmp')->insert([
                    'uid' => $uid,
                    'tuid' => $tuid,
                    'created_at' => $room->created_at->timestamp,
                    'do' => 7,
                    'attach' => json_encode([
                        'id' => $room->id,
                        'created_at' => $room->created_at->timestamp
                    ])
                ]);
                Redis::hset("v2173", "goodnight", $room->id);
            }
            if (!$deamon) {
                $bar->advance($this->take);
            }
        } while ($rooms->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    // 开黑
    public function gteam($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "gteam") ?? 0;
            $bar = $this->output->createProgressBar(\App\Models\Gteam\RoomModel::where('id', '>', $last_id)->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "gteam") ?? 0;
            $rooms = \App\Models\Gteam\RoomModel::where('id', '>', $last_id)->take($this->take)->get([
                'id',
                'created_at',
                'type'
            ]);
            foreach ($rooms as $room) {
                /** @var \App\Models\Gteam\RoomModel $room */
                $members = \App\Models\Gteam\RoomMemberModel::where('room_id', $room->id)->get(['uid'])->toArray();
                $uid = $members[0]['uid'];
                $tuid = $members[1]['uid'];
                if (in_array($room->type, ['cj_wx', 'cj_qq'])) {
                    $do = 6;
                } else {
                    $do = 5;
                }
                DB::table('kdgx_fpdx_friends_log_tmp')->insert([
                    'uid' => $uid,
                    'tuid' => $tuid,
                    'created_at' => $room->created_at->timestamp,
                    'do' => $do,
                    'attach' => json_encode([
                        'id' => $room->id,
                        'type' => $room->type,
                        'created_at' => $room->created_at->timestamp
                    ])
                ]);
                Redis::hset("v2173", "gteam", $room->id);
            }
            if (!$deamon) {
                $bar->advance($this->take);
            }
        } while ($rooms->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }

    public function hidefriend($deamon = false)
    {
        $bar = null;
        if (!$deamon) {
            $last_id = Redis::hget("v2173", "hidefriend") ?? 0;
            $bar = $this->output->createProgressBar(FriendModel::where('is_hide', 1)->where(
                'id',
                '>',
                $last_id
            )->count());
            $bar->start();
        }
        do {
            $last_id = Redis::hget("v2173", "hidefriend") ?? 0;
            $friends = FriendModel::where('is_hide', 1)->where('id', '>', $last_id)->take($this->take)->get();
            foreach ($friends as $friend) {
                /** @var FriendModel $friend */

                /** @var FriendModel $other */
                $other = FriendModel::where([
                    ['uid', $friend->friend_uid],
                    ['friend_uid', $friend->uid]
                ])->first();
                $friend->is_friend = 0;
                $other->is_friend = 0;

                $friend->save();
                $other->save();

                Redis::hset("v2173", "hidefriend", $friend->id);
            }
            if (!$deamon) {
                $bar->advance($this->take);
            }
        } while ($friends->isNotEmpty());
        if (!$deamon) {
            $bar->finish();
        }
    }
}
