<?php
/**
 * ${CARET}
 * @file:NoitceService.php
 * @Created by gnitif
 * @Date: 2023/3/27
 * @Time: 11:54
 */


namespace Modules\System\Services\Notice;

use Catch\Exceptions\FailedException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Permissions\Models\Roles;
use Modules\System\Models\Notices;
use Modules\System\Models\UserNotice;
use Modules\User\Models\User;

class NoticesService
{

    protected static function getModel()
    {
        return new Notices();
    }

    /**
     *  添加通知
     * name: addNotice
     * @param array $param
     *  $param = [
     *      'title' => '测试', // 通知标题
     *      'notice_type_id' =>  2, // 通知分类id
     *      'type' => '2', // 通知人群 1全部 2，指定人,3指定角色
     *      'notice_obj' => [['id' =>  1,'name' => "超管"]] , // 通知对象
     *      'is_popup' => '1', // 是否是弹窗 1弹窗  0 普通
     *       'content' => '312312', // 通知内容
     * ];
     *
     * date 2023/03/29 14:25
     */
    public static function addNotice(array $param)
    {

        if ($param['type'] != 1 && (!isset($param['notice_obj']) || empty($param['notice_obj']))) {
            throw new FailedException('通知对象不能为空！');
        }

        if ($param['type'] == 3) {
            $roleIds = array_column($param['notice_obj'], 'id');
            $userIds = DB::table('user_has_roles')->whereIn('role_id', $roleIds)->pluck('user_id')->toArray();
        } else if ($param['type'] == 2) {
            $userIds = array_column($param['notice_obj'], 'id');
        } else {
            $userIds = User::pluck('id')->toArray();
            $param['notice_obj'] = [];
        }
        $param['user_ids'] = $userIds;
        return self::getModel()->storeBy($param);
    }

    public static function delete($id)
    {
        return self::getModel()->updateBy($id, ['is_deleted' => 1, 'deleted_at' => get_date()]);
    }

    /**
     *  获取通知详情
     * name: getDetail
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|Notices[]
     * date 2023/03/29 15:12
     */
    public static function getDetail($id)
    {
        $info = Notices::leftJoin('notice_types', 'notice_types.id', 'notices.notice_type_id')
            ->select('notices.*', 'notice_types.name as notice_type_name')->where('notices.id', $id)->first();
        return $info;
    }

    /**
     *  更新
     * name: update
     * @param $id
     * @param array $param
     * date 2023/03/29 18:32
     */
    public static function update($id, array $param)
    {
       return  self::getModel()->updateBy($id, $param);
    }

    /**
     *  管理员操作通知列表
     * name: list
     * @return mixed
     * date 2023/03/29 22:49
     */
    public static function  list()
    {
        $list = self::getModel()->setBeforeGetList(function ($query) {
            return $query->where('is_deleted', 0)->orderBy('created_at','desc');
        })->getList();
        if (!$list->isEmpty()) {
            $cate = NoitceTypeService::list([], true);
            if ($cate->isEmpty()) {
                $cate = [];
            } else {
                $cate = array_column($cate->toArray(), null, 'id');
            }

            foreach ($list as $value) {
                $value->notice_type_txt = $cate[$value->notice_type_id]['name'] ?? "";
                $value->type_txt = $value->type == 1 ? "全部" : ($value->type == 2 ? "指定用户" : "指定角色");
            }
        }
        return $list;
    }

    /**
     * 我的通知
     * name: myNoticesList
     * date 2023/03/29 22:49
     */
    public static function myNoticesList($param = [])
    {
        $type = $param['type'] ?? "";
        $noticeTypeId = $param['notice_type_id'] ?? 0;
        $title = $param['title'] ?? "";
        $pageSize = $param['limit'] ?? 0;
        $pageSize = $pageSize < 1 ? 15 : $pageSize;
        $userId = Auth::guard(getGuardName())->id();
        $where = [
            ['user_notice.is_deleted', '=', 0],
            ['user_notice.user_id', '=', $userId],
            ['notices.is_deleted', '=', 0],
            ['user_notice.is_deleted', '=', 0],
        ];
        if ($type) {
            $where[] = ['notices.type', '=', $type];
        }
        if ($noticeTypeId) {
            $where[] = ['notices.notice_type_id', '=', $noticeTypeId];
        }
        if ($title) {
            $where[] = ['notices.title', 'like', "%" . $title . "%"];
        }

        $list = UserNotice::leftJoin('notices', 'notices.id', "user_notice.notice_id")->where($where)->select('notices.id', 'notices.title', 'notices.is_popup', "user_notice.is_read", 'notices.created_at')
            ->orderBy('notices.created_at', 'desc')->orderBy('sort', 'desc')->paginate($pageSize);
        if (!$list->isEmpty()) {
            foreach ($list as $val) {
                $val->is_read_txt = $val->is_read == 1 ? "已读" : "未读";
            }
        }
        return $list;
    }

    /**
     *  设置已读
     * name: setRead
     * @param $id
     * date 2023/03/29 23:51
     */
    public static function setRead($id)
    {
        $userId = Auth::guard(getGuardName())->id();
        return UserNotice::where('user_id', $userId)->where('notice_id', $id)->update(['is_read' => 1, 'read_at' => get_date()]);
    }

    /**
     *  用户删除
     * name: userDel
     * @param $id
     * date 2023/03/29 23:55
     */
    public static function userDel($id)
    {
        $userId = Auth::guard(getGuardName())->id();
        return UserNotice::where('user_id', $userId)->where('notice_id', $id)->update(['is_deleted' => 1, 'deleted_at' => get_date()]);
    }

    /**
     *  阅读详情
     * name: detail
     * @param $id
     * @return Notices
     * date 2023/03/30 00:09
     */
    public static function detail($id)
    {
        return Notices::where('id', $id)->where('is_deleted', 0)->select('title', 'id', 'is_popup', 'content')->first();
    }

    /**
     *  获取指定对象选择项
     * name: objOption
     * @param $type
     * @param string $name
     * @return array
     * date 2023/03/30 10:23
     */
    public static function objOption($type, $name = ""): mixed
    {
        if ($type == 'user') {
            if ($name) {
                return  User::where("username", 'like', "%" . $name . "%")->without(['roles','jobs'])->select('id','username as name')->get();
            }
            return User::select('id','username as name')->without(['roles','jobs'])->get();
        } else if ($type == "role") {
            if ($name) {
                return Roles::where("role_name", 'like', "%" . $name . "%")->select('id','role_name as name')->get();
            }
            return Roles::select('id','role_name as name')->get();
        }
        return [];
    }

    /**
     *  一条获取弹窗信息
     * name: getPopup
     * @return Model|UserNotice|object|null
     * date 2023/03/30 16:45
     */
    public static function getPopup()
    {
        $where = [
            ['user_notice.is_deleted', '=', 0],
            ['user_notice.user_id', '=',  Auth::guard(getGuardName())->id()],
            ['notices.is_deleted', '=', 0],
            ['notices.is_popup', '=', 1],
            ['user_notice.is_read', '=', 0],
        ];

         $info =  UserNotice::leftJoin('notices', 'notices.id', "user_notice.notice_id")->where($where)->select('notices.id', 'notices.title', 'notices.content')
             ->orderBy('notices.created_at', 'desc')->orderBy('sort', 'desc')->first();
         if (empty($info)){
             return  [];
         }
         return  $info;
    }


}
