<?php


namespace App\Services;

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


/**
 * 用户角色
 */
class RoleUserService extends BaseService
{
    public static string $MODEL = RoleUser::class;
    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return RoleUser::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['user_id']) && !empty($search['user_id'])) {
            $where[] = ['user_id', '=', $search['user_id']];
        }
       
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?RoleUser
    {
        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($user_id, $roles)
    {
        $result = false;

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

        // 计算新增的角色
        $toInsert = array_diff($roles, $existRoleIds);

        // 计算需要删除的角色
        $toDelete = array_diff($existRoleIds, $roles);

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

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

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

        return $result;
    }
}