<?php
namespace App\Domains\Virtual\Http\Controllers;

use App\Core\Controller;
use Illuminate\Http\Request;
use App\Exceptions\NotExistException;
use App\Domains\Virtual\Services\AgentService;
use App\Domains\Virtual\Repositories\AgentRepository;

class AgentController extends Controller
{
    protected $request;
    protected $agentService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, AgentService $agentService)
    {
        $this->request = $request;
        $this->agentService = $agentService;
    }

    /**
     * 列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $conditions = $this->request->all();
        $conditions['limit'] = $this->request->get('limit', 20);

        $agents = $this->agentService->index($conditions);

        $agents->load(['company:id,name']);

        return res($agents, '机构列表', 201);
    }

    /**
     * 机构详情.
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $node = app(AgentRepository::class)->find($id);

        if (!$node) {
            throw new NotExistException('机构不存在或已删除');
        }

        $node->load(['company:id,name']);

        return res($node, '机构详情', 201);
    }


    /**
      * 创建.
      *
      * @return \Illuminate\Http\Response
      */
    public function create()
    {
        $attributes = $this->request->all();

        $account = $this->agentService->store($attributes);

        return res($account, '创建成功');
    }

    /**
     * 编辑.
     *
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        $attributes = $this->request->all();
        $attributes['id'] = $id;

        $account = $this->agentService->store($attributes);

        return res($account, '修改成功');
    }

    /**
     * 删除.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy()
    {
        $ids = $this->request->ids();

        $this->agentService->destroy($ids);

        return res(true, '删除成功');
    }
}
