<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\DistAdminDistributor;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ApiController extends Controller
{
    /**
     * dist 分销商
     */
    public function dist(Request $request)
    {
        $q = $request->get('q');
        if ($q != null) {
            // 模糊搜索
            $obj = new DistAdminDistributor();
            return $obj->model()->where('client_code', 'like', "%$q%")->paginate(null, ['id', 'client_code as text']);
        } else {
            // 获取最新的N个
            $selectOptionsNew =  DistAdminDistributor::selectOptionsNew();
            return $this->changeOptions($selectOptionsNew);
        }
    }


    /*
 * 把数据转换成select需要的格式
 */
    private function changeOptions($data) {
        // 初始化结果数组
        $result = [];
        // 遍历原始数据并转换格式
        foreach ($data as $id => $text) {
            $result[] = [
                'id' => (int)$id,  // 将字符串转换为整数
                'text' => $text
            ];
        }
        return $result;
    }


}
