<?php

namespace Modules\WechatPlatform\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
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('messageType');
        $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('start_at', '>=', $sendAtStart);
            })->when($sendAtEnd, function ($query, $sendAtEnd){
                return $query->where('start_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 = 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');
        }

        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 = WechatPlatformConstService::KF_MESSAGE_TYPE_MAPPER[$item->message_type] ?? '';
            // todo:完善
            $item->uc_str = '';
        }

        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', 'uc_unique_key' => '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'),
                'uc_unique_key' => $request->input('uc_unique_key', ''),
                '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',
        ]);
        $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'),
                'uc_unique_key' => $request->input('uc_unique_key', ''),
                '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'
        ]);
        $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([
                'gzh_ids' => sprintf('#%s#', join('#', array_unique($request->input('gzh_ids')))),
                'updated_at' => $now,
            ]);

        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';
    }

}
