<?php

namespace App\Console\Commands\Upgrade;

use App\Managers\IMManager;
use App\Models\Friends\LogModel;
use App\Models\IM\UserLatestMessage;
use App\Models\User\LikeInviteQuestionModel;
use App\Models\User\UserModel;
use App\Utils\ImUtil;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class IMFriend extends Command
{
    protected $signature = "upgrade:im-friend {func?}";

    protected $description = "版本升级:APP-v1.1.3 IM";

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $func = $this->argument('func');
        switch ($func) {
            case 'registerim':
                $this->userRegisterIm();
                return;
            default:
                break;
        }
        return;
        // $this->updateChargeUserTable();
        $this->userRegisterIm();
        $this->updateFriendTable();
        $this->updateFriendApplyTable();
        $this->oldFriendMappingNewFriend();

        $this->createUserLatestMessageTable();
        $this->createUserMessageTable();
        $this->oldMessage2NewMessage();
    }

    public function updateFriendTable()
    {
        $sql1 = "alter table kdgx_fpdx_friends add list_unread_msg_cnt int(10) default 0 not null comment '列表未读数量' after last_msg;";
        DB::statement($sql1);
        $sql2 = "alter table kdgx_fpdx_friends add friend_level tinyint(4) default 0 not null comment '亲密度等级0陌生人1普通联系人2好友联系人' after friend_uid;";
        DB::statement($sql2);
        $sql3 = "alter table kdgx_fpdx_friends add is_blacklist tinyint(4) default 0 not null comment '是否拉黑0否1是' after friend_level;";
        DB::statement($sql3);
        $sql4 = "alter table kdgx_fpdx_friends add note char(16) comment '备注';";
        DB::statement($sql4);
    }

    public function updateFriendApplyTable()
    {
        $sql4 = "alter table kdgx_fpdx_friend_apply add handle tinyint(4) default 0 not null comment '是否处理-1忽略;0未处理;1同意' after apply_uid;";
        DB::statement($sql4);
        $sql5 = "alter table kdgx_fpdx_friend_apply add send_unread tinyint(4) default 0 not null comment '发送者是否已读0未读1已读';";
        DB::statement($sql5);
        $sql6 = "alter table kdgx_fpdx_friend_apply add receive_unread tinyint(4) default 1 not null comment '接收者者是否已读0未读1已读';";
        DB::statement($sql6);
    }

    public function updateChargeUserTable()
    {
        $sql5 = "alter table kdgx_partner_charge_user add im_account char(128) null comment 'ImAccount', add im_sig char(128) null comment 'ImSig'";
        DB::statement($sql5);
        $sql6 = "ALTER TABLE `kdgx_partner_charge_user` ADD  unique key `im_account`(`im_account`);";
        DB::statement($sql6);
    }

    public function createPairApplyTable()
    {
        $sql6 = "create table pair_contact_applies (
                                     `id` int(10) not null auto_increment comment '主键',
                                     `created_at` int(10) not null comment '发出时间',
                                     `send_uid` int(10) not null comment '用户',
                                     `receive_uid` int(10) not null comment '邀请用户',
                                     `activity_id` int(10) not null comment '活动id',
                                     `handle` tinyint(4) default 0 not null comment '是否处理-1忽略;0未处理;1同意',
                                     primary key (`id`),
                                     index idx_uid(`send_uid`),
                                     index idx_apply_uid(`receive_uid`))comment '分配对象CP申请表';";
        DB::statement($sql6);
    }

    public function createPairApplyListShareLog()
    {
        $sql = "create table pair_apply_list_share_help_log(
                        `id` int(10) not null auto_increment comment '主键',
                        `created_at` int(10) not null,
                        `share_uid` int(10) not null comment '分享用户',
                        `help_uid` int(10) not null comment '助力用户',
                        `lock_uid` int(10) not null comment '解锁用户',
                        `stage_id` int(10) not null comment '期数',
                        primary key (`id`)
                )comment '可发起CP申请的用户列表分享助力记录'";
        DB::statement($sql);
    }

    public function oldFriendMappingNewFriend()
    {
        DB::transaction(function () {
            $table = "kdgx_fpdx_friends";
            $tableTmp = "{$table}_tmp";
            DB::update('create table ' . $tableTmp . ' like ' . $table);
            $sql = "insert {$tableTmp}(id, created_at, uid, friend_uid, friend_level, is_blacklist, last_at, star_at, unread_cnt, last_msg, list_unread_msg_cnt, each_like, goodnight, is_hide, friend_type, friend_type_data)
select id,created_at, uid, friend_uid, IF(1 = is_friend, 2, IF(1 = each_like, 1, 0)), is_blacklist, last_at, star_at, unread_cnt, last_msg, list_unread_msg_cnt, each_like, goodnight, is_hide, friend_type, friend_type_data from {$table};";
            DB::update($sql);
            $sql = "delete from {$tableTmp} using {$tableTmp},
(select uid,friend_uid from {$tableTmp} where is_hide=1) as h
where ({$tableTmp}.uid=h.uid and {$tableTmp}.friend_uid=h.friend_uid)
    or ({$tableTmp}.uid=h.friend_uid and {$tableTmp}.friend_uid=h.uid)";
            DB::update($sql);
            $sql = "alter table {$tableTmp} 
                drop column friend_type,
                drop column friend_type_data,
                drop column is_hide,
                drop column is_friend,
                drop column unfriend_at,
                drop column gteam";
            DB::update($sql);
            $sql = "rename table {$table} to {$table}_copy;rename table {$tableTmp} to {$table};";
            DB::update($sql);
        });
    }

    // 用户批量注册IM
    public function userRegisterIm()
    {
        $imUtil = new ImUtil();
        UserModel::whereNull('im_account')->each(function (/** @var UserModel $item */$item) use ($imUtil) {
            $item->im_account = md5(config('app.env') . $item->uid);
            $imSig = $imUtil->registerUser($item->im_account, $item->nickname, $item->headimgurl, $item->sex, 0);
            $item->im_sig = $imSig;
            $item->save();
        });
    }

    public function createUserLatestMessageTable()
    {
        $sql = "create table user_latest_messages(
                              `uid` bigint(20) not null,
                              `from_uid` bigint(20) not null,
                              `to_uid` bigint(10) not null,
                              `seq` bigint(20) null,
                              `msg_random` int(10) not null,
                              `msg_time_stamp` int(10) not null,
                              `read` boolean not null,
                              `content` longtext null,
                              key `idx_uid_from_to` (`uid`, `from_uid`, `to_uid`)
                )comment '用户消息表'";
        DB::connection('mysql_fenpeiduixiang')->update($sql);
    }

    public function createUserMessageTable()
    {
        $sql = "create table user_messages(
                              `uid` bigint(20) not null,
                              `from_uid` bigint(20) not null,
                              `to_uid` bigint(10) not null,
                              `seq` bigint(20) null,
                              `msg_random` int(10) not null,
                              `msg_time_stamp` int(10) not null,
                              `read` boolean not null,
                              `content` longtext null,
                              key `idx_uid_from_to` (`uid`, `from_uid`, `to_uid`)
                )comment '用户消息日志表'";
        DB::connection('mysql_fenpeiduixiang')->update($sql);
    }

    public function oldMessage2NewMessage()
    {
        $lastId = Redis::hget("upgrade", "im-oldmsg2newmsg") ?? 0;
        $imManager = new IMManager();
        LogModel::where('do', 3)->where('id', '>', $lastId)->orderBy('id')->each(function ($item) use ($imManager) {
            Redis::hset("upgrade", "im-oldmsg2newmsg", $item->id);
            try {
                $fromUser = UserModel::whereUid($item->uid)->first('im_account');
                $toUser = UserModel::whereUid($item->uid)->first('im_account');
                $fromAccount = $fromUser->im_account;
                $toAccount = $toUser->im_account;
                $msgTime = $item->created_at;
                switch ($item->attach['type']) {
                    case 2:
                        // 心动问答
                        $question = LikeInviteQuestionModel::withTrashed()->find($item->attach['question']);
                        $question->question = json_decode($question->question, true);
                        $msgData = [
                            'MsgType' => 'LikeQA',
                            'Content' => [
                                'question' => [
                                    'title' => Arr::get($question->question, 'question'),
                                    'id' => Arr::get($question->question, 'id')
                                ],
                                'answer' => [
                                    'type' => Arr::get($item->attach, 'type'),
                                    'value' => Arr::get($item->attach, 'value')
                                ]
                            ]
                        ];
                        break;
                    case 3:
                        // 唱首歌
                        $question = LikeInviteQuestionModel::withTrashed()->find($item->attach['question']);
                        $question->question = json_decode($question->question, true);
                        $msgData = [
                            'MsgType' => 'LikeSing',
                            'Content' => [
                                'song' => [
                                    'name' => Arr::get($question->question, 'question.name'),
                                    'singer' => Arr::get($question->question, 'question.author'),
                                ],
                                'answer' => [
                                    'type' => Arr::get($item->attach, 'type'),
                                    'value' => Arr::get($item->attach, 'value')
                                ]
                            ]
                        ];
                        break;
                    case 4:
                        // 走心一画
                        $msgData = [
                            'MsgType' => 'LikeDraw',
                            'Content' => [
                                'paint' => [
                                    'id' => Arr::get($item->attach, 'value.paint_id'),
                                    'name' => Arr::get($item->attach, 'value.name'),
                                    'url' => Arr::get($item->attach, 'value.pic_url'),
                                ]
                            ]
                        ];
                        break;
                    default:
                        return;
                }
                $data = array(
                    'MsgBody' => [
                        [
                            'MsgType' => 'TIMCustomElem',
                            'MsgContent' => [
                                'Data' => $msgData,
                                'Desc' => null,
                                'Ext' => null,
                                'Sound' => null
                            ]
                        ]
                    ],
                    "CallbackCommand" => "C2C.CallbackAfterSendMsg",
                    'From_Account' => $fromAccount,
                    'To_Account' => $toAccount,
                    'MsgRandom' => rand(1, 500000000),
                    'MsgSeq' => rand(0, 7000),
                    'MsgTime' => $msgTime,
                    'ClientIP' => '183.129.21.216',
                    'OptPlatform' => 'Android',
                    'RequestId' => '4144894721-144115214975491767-1572409801-500726985',
                    "SdkAppid" => "1400263610",
                    "contenttype" => "json"
                );
                $fromAccount = $data['From_Account'];
                $toAccount = $data['To_Account'];
                $msgTime = $data['MsgTime'];
                $msgRandom = $data['MsgRandom'];
                $msgSeq = $data['MsgSeq'];
                $imManager->createUserLatestMessageByAccount(
                    $fromAccount,
                    $fromAccount,
                    $toAccount,
                    $msgTime,
                    $msgRandom,
                    $msgSeq,
                    $data,
                    true
                );
                $imManager->createUserLatestMessageByAccount(
                    $toAccount,
                    $fromAccount,
                    $toAccount,
                    $msgTime,
                    $msgRandom,
                    $msgSeq,
                    $data,
                    true
                );
            } catch (\Exception $exception) {
                return;
            } catch (\Throwable $exception) {
                return;
            } finally {
                return;
            }
        });
    }
}
