<?php

namespace App\Domains\Virtual\Repositories;

use App\Core\Repository;
use App\Models\Virtual\CompanyAccount as Model;

class CompanyAccountRepository extends Repository
{
    /**
     * 是否关闭缓存
     *
     * @var boolean
     */
    protected $cacheSkip = false;

    /**
     * 是否开启数据转化
     *
     * @var bool
     */
    protected $needTransform = false;

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'id'         => '=',
        'created_at' => 'like',
    ];

    public function model()
    {
        return Model::class;
    }

    /**
     * 数据格式化
     *
     * @param mixed $result
     *
     * @return mixed
     */
    public function transform($model)
    {
        return $model->toArray();
    }

    /**
     * 查询条件
     *
     * @return void
     */
    public function withConditions(array $conditions = [])
    {
        if (isset($conditions['id'])) {
            $conditions['id'] = array_wrap($conditions['id']);
            $this->model = $this->model->whereIn('id', $conditions['id']);
        }

        if (isset($conditions['company_id'])) {
            $this->model = $this->model->where('company_id', $conditions['company_id']);
        }

        return $this;
    }

    /**
     * 获取数据
     *
     * @param string|int $key
     * @return void
     */
    public function fetch($key)
    {
        if (empty($key)) {
            return null;
        }

        $column = 'username';

        $map = [
            'mobile' => validate_china_phone_number($key),
            'username' => validate_username($key),
            'id' => is_numeric($key),
        ];

        foreach ($map as $field => $value) {
            if ($value) {
                $column = $field;
            }
        }

        return $this->model->where($column, $key)->first();
    }
}
