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

use App\Core\Controller;
use Illuminate\Http\Request;
use App\Exceptions\NotAllowedException;
use App\Domains\Virtual\Services\CompanyAddressService;

class AddressController extends Controller
{
    protected $request;
    protected $companyAddressService;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request, CompanyAddressService $companyAddressService)
    {
        $this->request = $request;
        $this->companyAddressService = $companyAddressService;
        $this->account = $request->user('company');
    }

    /**
     * 获取收货地址列表
     */
    public function list()
    {
        $res = $this->companyAddressService->getCompanyAddress($this->account->company_id);
        return res($res, '收货地址', 201);
    }

    /**
     * 添加收货地址
     *
     * @return void
     */
    public function create()
    {
        $attributes = $this->request->all();
        $attributes['company_id'] = $this->account->company_id;

        $res = $this->companyAddressService->store($attributes);

        return res($res, '添加成功');
    }

    /**
     * 修改收货地址
     *
     * @param int $id
     * @return void
     */
    public function update($id)
    {
        $attributes = $this->request->all();
        $attributes['id'] = $id;
        $attributes['company_id'] = $this->account->company_id;

        $res = $this->companyAddressService->store($attributes);

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

    public function destroy()
    {
        $ids = $this->request->ids();

        $res = $this->companyAddressService->getCompanyAddress($this->account->company_id)->pluck('id')->toArray();

        foreach ($ids as $id) {
            if (!in_array($id, $res)) {
                throw new NotAllowedException('非法操作');
            }
        }

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

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

    public function default($id)
    {
        $node = $this->companyAddressService->setDefault($id);
        return res($node, '设置成功');
    }
}
