<?php

namespace Modules\WechatPlatform\Http\Controllers;

use App\Jobs\WechatPlatform\GZHSendKFMessage;
use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\WechatPlatform\Models\WechatKfMessageModel;
use Modules\WechatPlatform\Services\WechatPlatformConstService;

class KFMessageController extends CatchController
{
    use ValidatesRequests;
    /**
     * 客服消息列表
     * @param Request $request
     */
    public function list(Request $request) {
        $name = $request->input('name');
        $messageType = $request->input('message_type');
        $status = $request->input('status');
        $sendAtStart = $request->input('send_at_start');
        $sendAtEnd = $request->input('send_at_end');
        $gzhid = $request->input('gzh_id');
        $result = DB::table('wechat_kf_messages')
            ->where([
                ['is_enabled' , '=', 1],
                ['user_id', '=', $this->getLoginUserId()]
            ])->when($name, function ($query, $name){
                return $query->where('name', 'like', '%'. $name. '%');
            })->when($messageType, function ($query, $messageType){
                return $query->where('message_type', $messageType);
            })->when($status, function ($query, $status){
                return $query->where('status', $status);
            })->when($sendAtStart, function ($query, $sendAtStart){
                return $query->where('send_at', '>=', $sendAtStart);
            })->when($sendAtEnd, function ($query, $sendAtEnd){
                return $query->where('send_at', '<=', $sendAtEnd . ' 23:59:59');
            })->when($gzhid, function ($query, $gzhid){
                return $query->where('gzh_ids', 'like', '%#'. $gzhid . '#%');
            })->orderBy('id', 'desc')
            ->paginate($request->input('limit', 20));
        $gzhIds = $gzhs = $ugs =  collect();
        $result->pluck('gzh_ids')->every(function ($item) use ($gzhIds){
            $gzhIds->merge(explode('#', trim($item, '#')));
        });

        if($gzhIds->isNotEmpty()) {
            $gzhs = DB::table('wechat_authorization_infos')
                ->whereIn('id', $gzhIds)
                ->select('id', 'nick_name')
                ->get()->keyBy('id');
        }

        $ugIds = $result->pluck('ug_id')->diff([0]);
        if($ugIds->isNotEmpty()) {
            $ugs = DB::table('user_groups')->whereIn('id', $ugIds)
                ->select('id', 'name')->get()->keyBy('id');
        }

        foreach ($result as $item) {
            $item->gzh_names = $this->strGzhId($item->gzh_ids, $gzhs);
            $item->status_str = WechatPlatformConstService::KF_MESSAGE_STATUS_MAPPER[$item->status] ?? '';
            $item->message_content_arr = \json_decode($item->message_content, true);
            $item->message_type_str = WechatPlatformConstService::KF_MESSAGE_TYPE_MAPPER[$item->message_type] ?? '';
            $item->ug_str = $ugs->get($item->ug_id)->name ?? '';
        }

        return $result;
    }

    private function strGzhId($gzh_ids, $gzhs) {
        if(!$gzh_ids){
            return '';
        }
        $gzh_names = collect();
        foreach (explode('#', trim($gzh_ids, '#')) as $gzh_id) {
            $gzh_names->push($gzhs->get($gzh_id)->nick_name ?? 'ID:'. $gzh_id);
        }

        return $gzh_names->unique()->join(', ');
    }

    /**
     * 新增
     * @param Request $request
     */
    public function add(Request $request) {
        $this->validate($request, [
            'name' => 'required', 'message_type' => 'required|in:1', 'message_content' => 'required|array',
            'u_type' => 'required|in:1,2', 'ug_id' => 'required_if:u_type,2', 'send_at' => 'required|date_format:Y-m-d H:i:s',
        ]);
        $now = date('Y-m-d H:i:s');
        DB::table('wechat_kf_messages')
            ->insert([
                'name' => $request->input('name'),
                'message_type' => $request->input('message_type'),
                'message_content' => \json_encode($request->input('message_content'), JSON_UNESCAPED_UNICODE),
                'u_type' => $request->input('u_type', 1),
                'ug_id' => $request->input('ug_id', 0),
                'send_at' => $request->input('send_at'),
                'status' => WechatPlatformConstService::KF_MESSAGE_STATUS_PRE_SEND,
                'user_id' => $this->getLoginUserId(),
                'created_at' => $now,
                'updated_at' => $now,
            ]);

        return 'ok';
    }

    /**
     * 修改客服消息内容
     * @param Request $request
     */
    public function updateContent(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'name' => 'required', 'message_type' => 'required|in:1', 'message_content' => 'required|array',
            'u_type' => 'required|in:1,2', 'ug_id' => 'required_if:u_type,2', 'send_at' => 'required|date_format:Y-m-d H:i:s',
        ]);
        $now = date('Y-m-d H:i:s');
        DB::table('wechat_kf_messages')
            ->where([
                ['id', '=', $request->input('id')],
                ['user_id', '=', $this->getLoginUserId()],
                ['status', '=', WechatPlatformConstService::KF_MESSAGE_STATUS_PRE_SEND],
                ['is_enabled', '=', 1],
            ])->update([
                'name' => $request->input('name'),
                'message_type' => $request->input('message_type'),
                'message_content' =>  \json_encode($request->input('message_content'), JSON_UNESCAPED_UNICODE),
                'u_type' => $request->input('u_type', '1'),
                'ug_id' => $request->input('ug_id', 0),
                'send_at' => $request->input('send_at'),
                'updated_at' => $now,
            ]);

        return 'ok';
    }

    /**
     * 修改配置的公众号
     * @param Request $request
     */
    public function updateGZH(Request $request){
        $this->validate($request, [
            'id' => 'required',
            'gzh_ids' => 'required|array'
        ]);

        $message  = WechatKfMessageModel::where([
            ['id', '=', $request->input('id')],
            ['user_id', '=', $this->getLoginUserId()],
            ['status', '=', WechatPlatformConstService::KF_MESSAGE_STATUS_PRE_SEND],
            ['is_enabled', '=', 1],
        ])->first();
        if(!$message) {
            $allGzhIds = $request->input('gzh_ids');
            if(2 == $message->u_type) {
                $configGzhIds = DB::table('gzh_ug_maps')
                    ->where([
                        ['is_enabled', '=', 1],
                        ['ug_id', '=', $message->id]
                    ])->select('gzh_id')->get()->pluck('gzh_id');

                if(collect($allGzhIds)->diff($configGzhIds)->isNotEmpty()) {
                    $gzhNames = DB::table('wechat_authorization_infos')
                        ->whereIn('id', collect($allGzhIds)->diff($configGzhIds)->unique())
                        ->select( 'nick_name')
                        ->get()->pluck('nick_name')->join(', ');
                    CommonBusinessException::throwError([
                        Errors::OPENPLATFORM_UG_MAP_GZH_NOT_EXIST[0], $gzhNames. ' 等公众号没有配置对应用户分群'
                    ]);
                }
            }
            $message->gzh_ids = sprintf('#%s#', join('#', array_unique($request->input('gzh_ids'))));
            $message->save();
        }

        return 'ok';
    }

    /**
     * 停止发送
     * @param Request $request
     */
    public function stop(Request $request) {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $now = date('Y-m-d H:i:s');
        DB::table('wechat_kf_messages')
            ->where([
                ['id', '=', $request->input('id')],
                ['user_id', '=', $this->getLoginUserId()],
                ['status', '=', WechatPlatformConstService::KF_MESSAGE_STATUS_PRE_SEND],
                ['is_enabled', '=', 1],
            ])->update([
                'status' => WechatPlatformConstService::KF_MESSAGE_STATUS_STOP,
                'updated_at' => $now,
            ]);

        return 'ok';
    }

    /**
     * 删除
     * @param Request $request
     */
    public function delete(Request $request){
        $this->validate($request, [
            'id' => 'required'
        ]);
        $now = date('Y-m-d H:i:s');
        DB::table('wechat_kf_messages')
            ->where([
                ['id', '=', $request->input('id')],
                ['user_id', '=', $this->getLoginUserId()],
                ['status', '<>', WechatPlatformConstService::KF_MESSAGE_STATUS_SENDING],
                ['is_enabled', '=', 1],
            ])->update([
                'is_enabled' => 0,
                'updated_at' => $now,
            ]);
        DB::table('wechat_kf_message_send_records')
            ->where([
                ['message_id', '=', $request->input('id')],
                ['is_enabled', '=', 1]
            ])->update([
                'is_enabled' => 0,
                'updated_at' => $now,
            ]);
        return 'ok';
    }

    /**
     * 测试发送
     * @param Request $request
     */
    public function testSend(Request $request) {
        $this->validate($request, [
            'gzh_id' => 'required', 'message_id' => 'required', 'openid' => 'required'
        ]);

        GZHSendKFMessage::dispatch([
            'gzhId' => $request->input('gzh_id'),
            'messageId' => $request->input('message_id'),
            'openid' => $request->input('openid'),
            'isTest' => true,
            'traceInfo' => getTraceContext()->getTraceInfo(),
        ])->onQueue('{duanju_manage}.wechatPlatform.sendKFMessage')
            ->onConnection('queue-redis');

        return 'ok';
    }
}