<?php


namespace App\Services;

use App\Services\BaseService;
use App\Models\RoleMenu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;


/**
 * 角色菜单
 */
class RoleMenuService extends BaseService
{
    public static string $MODEL = RoleMenu::class;
    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return RoleMenu::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
       
        if (isset($search['role_id']) && !empty($search['role_id'])) {
            $where[] = ['role_id', '=', $search['role_id']];
        }
        if (isset($search['menu_id']) && !empty($search['menu_id'])) {
            $where[] = ['menu_id', '=', $search['menu_id']];
        }
       
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?RoleMenu
    {
        return self::model()::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return self::model()::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $paginator = self::model()::where(self::getWhere($search))
            // ->orderBy("sort", 'asc')
            ->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description: 
     * @param {*} $params
     * @return {*}
     */    
    public static function submit($role_id, $menus)
    {
        $result = false;

        // 获取数据库中已存在的菜单列表（提取 menu_id）
        $list = self::findAll(['role_id' => $role_id]);
        $existIds = $list->pluck('menu_id')->toArray();

        // 计算新增的菜单
        $toInsert = array_diff($menus, $existIds);

        // 计算需要删除的菜单
        $toDelete = array_diff($existIds, $menus);

       
        // 开始数据库事务（假设有 DB 支持事务操作）
        // DB::beginTransaction();
        // try {
            if(empty($menus)){
                self::model()::where('role_id',$role_id)->delete();
            }else{
                // 批量插入新增菜单
                if (!empty($toInsert)) {
                    $insertData = [];
                    foreach ($toInsert as $menu_id) {
                        $insertData[] = [
                            'menu_id' => $menu_id,
                            'role_id' => $role_id,
                        ];
                    }
                    self::model()::insert($insertData);
                }

                // 删除多余的菜单
                if (!empty($toDelete)) {
                    self::model()::where('role_id', $role_id)
                        ->whereIn('menu_id', $toDelete)
                        ->delete();
                }

            }
            
            // DB::commit();
            $result = true;
        // } catch (\Exception $e) {
        //     DB::rollBack();
        //     // 记录错误日志或抛出异常
        // }

        return $result;
    }
}