<?php

namespace Modules\System\Models;


class Notices extends BaseModel
{
    protected $table = 'notices';

    protected $fillable = [
        'id', 'title', 'content', 'notice_type_id', "sort", 'type', 'notice_obj', 'is_popup', 'is_deleted', 'created_at', 'updated_at', 'deleted_at',
    ];

    /**
     * @var array
     */
    protected array $fields = ['id', 'title', 'content', "sort", 'notice_type_id', 'type', 'notice_obj', 'is_popup', 'created_at', 'updated_at'];

    /**
     * @var array
     */
    protected array $form = ['title', 'content', 'notice_type_id',"sort", 'type', 'notice_obj', 'is_popup'];


    protected $casts = ['notice_obj' => 'array'];

    public array $searchable = [
        'title' => 'like',
        'notice_type_id' => '=',
        'type' => '=',

    ];

    protected string $sortField = 'sort';



    /**
     *  添加通知
     * @param array $data
     * @return bool
     * @throws \ReflectionException
     */
    public function storeBy(array $data): mixed
    {
        $result = '';
        $this->beginTransaction();
        try {
            $result = $this->create($this->filterData($data));
            if (isset($data['user_ids']) && !empty($data['user_ids'])) {
                $this->addUserNotice($data['user_ids'], $result->id);
            }
            $this->commit();
        } catch (\Exception $exception) {
            $this->rollback();
        }
        return $result->id ?? 0;
    }

    private function addUserNotice(mixed $userIds, mixed $id)
    {
        $list = [];
        foreach ($userIds as $val) {
            $list[] = ['user_id' => $val, 'notice_id' => $id];
        }
        if (!empty($list)) {
            UserNotice::insert($list);
        }
        return true;
    }


}