<?php

namespace App\Distributor\Repositories;

use App\Models\DistMessage as DistMessageModel;
use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\Repository;
use Illuminate\Pagination\LengthAwarePaginator;

class DistCustomMessage extends Repository
{
    protected $eloquentClass = DistMessageModel::class;

    /**
     * 定义主键字段名称
     *
     * @return string
     */
    public function getPrimaryKeyColumn()
    {
        return 'id';
    }


    /**
     * 重写 get 方法
     *
     * @param Grid\Model $model
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection|array
     */
    public function get(Grid\Model $model)
    {
        // 当前页数
        $currentPage = $model->getCurrentPage();
        // 每页显示行数
        $perPage = $model->getPerPage();

        // 获取排序字段
        [$orderColumn, $orderType] = $model->getSort();

        // 获取当前登录用户的 ID
        $userId = getDistributorId();

        // 使用 getMessagesForUser 方法获取消息列表
        $messages = $this->getMessagesForUser($userId);

        // 获取总记录数
        $total = $messages->count();

        // 分页数据
        $data = $messages->slice(($currentPage - 1) * $perPage, $perPage)->values();


        foreach ($data as $value) {


            $value['created_at']=$value['created_at']->toDateTimeString();

            $data_out[]=$value;
        }


        return $model->makePaginator(
            $total, // 传入总记录数
            $data_out
        );
    }

    /**
     * 获取最近 N 条消息
     *
     * @param int $limit
     * @return \Illuminate\Support\Collection
     */
    public function getRecentMessages($limit = 10)
    {
        // 获取当前登录用户的 ID
        $userId = getDistributorId();

        // 使用 getMessagesForUser 方法获取消息列表
        $messages = $this->getMessagesForUser($userId);

        // 获取最近 N 条消息
        $recentMessages = $messages->take($limit);

        return $recentMessages;
    }


    public function getMessagesForUser($userId)
    {

        //$userId=str($userId);

        return DistMessageModel::where('target_type', 'all')
            ->orWhere(function ($query) use ($userId) {
                $query->where('target_type', 'users')
                    ->whereJsonContains('target_ids', str($userId));
            })
            ->with(['readStatuses' => function ($query) use ($userId) {
                $query->where('user_id', $userId);
            }])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($message) use ($userId) {
                $isRead = $message->readStatuses->isNotEmpty() && $message->readStatuses->first()->is_read;
                if(!$isRead)
                {
                    $isRead=0;
                }
                return [
                    'id' => $message->id,
                    'title' => $message->title,
                    'content' => $message->content,
                    'sender_id' => $message->sender_id,
                    'created_at' => $message->created_at,
                    'is_read' => $isRead,
                ];
            });
    }

    /**
     * 判断用户是否有权限查看指定 ID 的消息
     *
     * @param int $messageId
     * @return bool
     */
    public static function canViewMessage($messageId)
    {

        // 获取当前登录用户的 ID
        $userId = getDistributorId();

        // 检查消息是否存在且属于当前用户
        $message = DistMessageModel::where('id', $messageId)
            ->where(function ($query) use ($userId) {
                $query->where('target_type', 'all')
                    ->orWhere(function ($query) use ($userId) {
                        $query->where('target_type', 'users')
                            ->whereJsonContains('target_ids', str($userId));
                    });
            })
            ->first();



        return $message !== null;
    }

}
