<?php
namespace App\Domains\Virtual\Services;

use Carbon\Carbon;
use App\Core\Service;
use App\Models\Virtual\Agent;
use Illuminate\Validation\Rule;
use App\Exceptions\NotExistException;
use Illuminate\Support\Facades\Validator;
use App\Domains\Virtual\Services\CommonService;
use App\Domains\Virtual\Repositories\AgentRepository;
use App\Domains\Virtual\Repositories\CompanyRepository;

class AgentService extends Service
{
    protected $agentServiceRepository;

    protected static $agents;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct(AgentRepository $agentServiceRepository)
    {
        $this->agentServiceRepository = $agentServiceRepository;
    }

    /**
     * 机构列表
     *
     * @param array $conditions
     * @return mixed
     */
    public function index(array $conditions = [])
    {
        $limit = $conditions['limit'] ?? 20;

        $agents = $this->agentServiceRepository->withConditions($conditions)
            ->applyConditions()->paginate($limit);

        $agents->map(function ($item) {
            $item->status = $item->deleted_at ? 2 : $item->status;
            $item->created_at = Carbon::parse($item->created_at)->format('Y-m-d');
            $item->updated_at = Carbon::parse($item->updated_at)->format('Y-m-d');
        });

        return $agents;
    }

    /**
     * 存储机构
     *
     * @param array $attributes
     * @param Agent $parent
     * @return Agent
     */
    public function store(array $attributes = [])
    {
        $attributes = array_only($attributes, array_merge(app(Agent::class)->getFillable()));

        $rule = [
            'company_id' => ['required', Rule::exists(app(CompanyRepository::class)->getTable(), 'id')->whereNUll('deleted_at')->where('status', 0)],
            'name' => ['required', 'between:2,32', Rule::unique($this->agentServiceRepository->getTable(), 'name')->ignore($attributes['id'])->whereNUll('deleted_at')],
            'contacts' => ['string', 'between:2,32'],
            'mobile' => ['string', 'cn_phone'],
            'address' => ['string'],
            'extends' => ['array'],
        ];

        $message = [
            'company_id.required' => '请输入企业ID',
            'company_id.exists' => '企业不存在或已删除',
            'name.required' => '请输入机构名称',
            'name.between' => '机构名称长度不合法',
            'name.unique' => '机构名称已经被其他用户所使用',
            'contacts.between' => '联系人长度不合法',
            'mobile.cn_phone' => '手机号不合法',
        ];

        Validator::validate($attributes, $rule, $message);

        if (!$attributes['id']) {
            $maxId = Agent::withTrashed()->max('id');
            $attributes['id'] = $maxId ? $maxId + 1 : 1;

            $maxSn = Agent::withTrashed()->max('sn');
            $maxSn = intval(str_replace('No', '', $maxSn));
            $attributes['sn'] = CommonService::stringifyCompanyId($maxSn + 1);

            $node = $this->agentServiceRepository->create($attributes);
        }

        if ($attributes['id']) {
            $node = $this->agentServiceRepository->find($attributes['id']);

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

            $this->agentServiceRepository->setModel($node)->update($attributes);
        }

        return $node;
    }

    /**
     * 删除
     *
     * @return bool
     */
    public function destroy($ids)
    {
        $ids = is_array($ids) ? $ids : [$ids];

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

        return true;
    }

    public static function listGroupByCompanyId()
    {
        if (!self::$agents) {
            self::$agents = app(AgentRepository::class)->select(['id', 'company_id', 'name', 'status'])->withTrashed()->get()->groupBy('company_id')->toArray();
        }

        return self::$agents;
    }
}
