<?php

namespace App\Http\Controllers\H5;

use App\Facades\CommentService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\CommentType;
use App\Models\DmaProcess;
use App\Models\DmaProcessLog;
use App\Models\Group;
use App\Models\Order;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceUser;
use App\Models\User;
use App\Services\ChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CommentController extends Controller
{

    public function orderComments(Request $request)
    {
        $chat_id = $request->input('chat_id');
        $service_user_id = $request->input('service_user_id');
        if ($chat_id) {
            if($service_user_id){
                $group = Group::with('order')->where('im_chat_id', $chat_id)->first();
            }else{
                $group = Group::with('order')->where('chat_id', $chat_id)->first();
            }
            $order = $group->order;
        }else {
            $order = Order::where('pay_status', 'PAID')->orderByDesc('id')->first();
        }
//        $comments = CommentService::orderComments($order);
        $comments = Comment::with(['role','user'])->where('commentable_id',$order->id)->orderByDesc('id')->paginate();
        if($comments){
            foreach ($comments as $k => $v){
                $comments[$k]->images = json_decode($v->images,true);
            }

        }

        if($service_user_id){
            $user = User::whereHas('serviceUser', function($sql) use($service_user_id) {
                $sql->where('user_id', $service_user_id);
            })->first();
        }else{
            //清除红点
            $work_user = session('work_wechat_user');
            if ($work_user) {
                $work_id = $work_user['raw']['userid'];
            }else{
                $work_id = $request->input('work_id');
            }
            $user = User::whereHas('serviceUser', function($sql) use($work_id) {
                $sql->where('work_user_id', $work_id);
            })->first();
        }
        if($user){
            $key = 'red_event_'.$chat_id.'_'.$user->id;
            Redis::del($key);
        }

        return $this->success('ok', $comments);
    }

    public function commentOrder(Request $request)
    {
        $chat_id = $request->input('chat_id');
        if (empty($chat_id)) throw new \Exception("缺少企业微信群id");
        $service_user_id = $request->input('service_user_id');
        if($service_user_id){
            $group = Group::with('order')->where('im_chat_id', $chat_id)->first();
        }else{
            $group = Group::with('order')->where('chat_id', $chat_id)->first();
        }

        $order = $group->order;
        $content = $request->input('comment');
        $images = $request->input('images');
        $type_id = $request->input('type_id', 3);
        if(is_array($images)){
            $images = json_encode($images);
        }
        if (empty($content) && empty($images)) return $this->failure("请输入备注内容");
        if($service_user_id){
            $user = User::whereHas('serviceUser', function($sql) use($service_user_id) {
                $sql->where('user_id', $service_user_id);
            })->first();
        }else{
            $work_user = session('work_wechat_user');
            if ($work_user) {
                if(config('app.env') == 'production'){
                    $work_id = $work_user['raw']['userid'];
                }else{
                    $work_id = "hankin";
                }
            }else{
                $work_id = $request->get('work_id');
            }
            $user = User::whereHas('serviceUser', function($sql) use($work_id) {
                $sql->where('work_user_id', $work_id);
            })->first();
        }
//        CommentService::commentOrder($order, $content, $user);
//        if($user && $images){
//            $latestRecord = Comment::where('user_id',$user->id)->latest()->first();
//            if($latestRecord){
//                $latestRecord->update(['images'=>$images]);
//            }
//        }
        $comment_type = CommentType::where('id',$type_id)->first();
        Comment::create([
            'commentable_type'=>get_class(),
            'commentable_id'=>$order->id,
            'comment'=>$content,
            'images'=>$images,
            'type_id' => $type_id,
            'type_name' => $comment_type->name,
            'user_id'=>$user->id??null
        ]);

        //查看这个订单是有哪些服务人员，增加红点提示
        if($user){
            $service_user_ids = ServiceRoleOrder::where('order_id',$order->id)
                ->where('user_id','<>',$user->id)
                ->pluck('user_id')->unique();

            //取和当前用户不同身份的角色发送
            $service_user_role = ServiceRoleOrder::where('order_id',$order->id)
                ->where('user_id',$user->id)->value('role_id');
            // 计算两个数组的差集
            $difference = array_diff([ServiceRole::MAIN_COACH,ServiceRole::COACH,ServiceRole::CUSTOMER], [$service_user_role]);
            //发送网易云通知
            $chatService = new ChatService();
            $chatService->sendImMsgUserToUser($order->id,'系统通知','用户【'.$order->name.'】的群，内部沟通有留言，请查阅。','https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png','yfheal://app/push/RemarksManagement',$difference);
            //不是网易云信群再发送备注信息
            foreach ($service_user_ids as $user_id){
                $key = 'red_event_'.$chat_id.'_'.$user_id;
                Redis::incr($key);

                //发送企业微信通知
                $message = "【{$group->name}】有一个新备注，请注意查看";
                $work_user_id = ServiceUser::where('user_id',$user_id)->value('work_user_id');
                if($work_user_id && config('app.env') == 'production' && !$service_user_id){
                    WechatService::sendWorkMessage($work_user_id,'text',['content'=>$message]);
                }
            }
        }
        DmaProcessLog::addUserProcessLog($order->user_id??0,$order->id??0,1,"submit_comment","提交了备注信息",$service_user_id??0);
        DmaProcessLog::addUserProcessLog($order->user_id??0,$order->id??0,1,"send_comment_msg","系统发送备注通知",$service_user_id??0);
        return $this->success('ok');
    }

    public function deleteComment(Comment $comment)
    {
        $comment->delete();
        return $this->success('ok');
    }

    public function updateOrderComment(Request $request, Comment $comment)
    {
        $content = $request->input('comment');
        $comment->comment = $content;
        $images = $request->input('images');
        $type_id = $request->input('type_id', 1);
        $comment_type = CommentType::find($type_id);
        if(!empty($images)){
            $images = json_encode($images);
        }
        $comment->images = $images;
        $comment->type_id = $type_id;
        $comment->type_name = $comment_type->name;
        $comment->save();
        return $this->success('ok');
    }

    public function orderComment(Request $request, Comment $comment)
    {
        if($comment){
            $comment->images = json_decode($comment->images);
        }
        return $this->success('ok', $comment);
    }

    public function getCommentType(){
        try {
            $list = CommentType::get();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            return $this->failure('file:'.$e->getFile().'|line:'.$e->getLine().'|message:'.$e->getMessage());
        }
    }
}
