<?php
/**
 *------------------------------------------------------
 * Model层基类
 *------------------------------------------------------
 *
 * @author    qqiu@qq.com
 * @date      2016/05/26 09:22
 * @version   V1.0
 *
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BaseModel extends Model
{
    /**
     * 维护数据表中 created_at 和 updated_at 字段
     */
    public $timestamps = true;

    protected $guarded = [];

    protected $statusOptions = [
        ['id' => 1, 'name' => '未激活', 'color' => 'gray'],
        ['id' => 2, 'name' => '激活', 'color' => 'blue'],
        ['id' => 3, 'name' => '禁用', 'color' => 'red']
    ];

    /**
     * 多个Where
     * @param Object $query
     * @param array $arr ['status' => 1, 'type' => 2]
     * @return Object $query
     */
    public function multiwhere($query, $arr)
    {
        if ( !is_array($arr) ) {
            return $query;
        }
        foreach ($arr as $key => $value) {
            $query = $query->where($key, $value);
        }
        return $query;
    }
    public function getValidator(Request $request, $type)
    {
        $validator = Validator::make($request->input('data'), [
            'name' => 'required'
        ], [
            'name.required' => '名称必填'
        ]);
        return $validator;
    }

    public static function getOptions()
    {
        return self::where('id', '>', 0)->orderBy('sort')->get()->toArray();
    }

    public function getStatusOptions()
    {
        return $this->statusOptions;
    }

    /*
     * type: name|label
     */
    public function getStatus($type = 'name') {
        $options = $this->statusOptions;
        $option = $options[0];
        foreach($options as $item) {
            if($item['id'] == $this['status']) {
                $option = $item;
                break;
            }
        }
        if($type == 'name') return $option['name'];
        else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
    }

    /**
     * @param $column
     * @param string $type(name|label)
     * @return string
     */
    public function getNameOrLabel($column, $type = 'name')
    {
        $option = Option::get($this->getTable(), $column, $this[$column], null);
        if(!$option)
        {
            return '';
        }
        if($type == 'name')
        {
            return '<div class="layui-badge">' . $option->name . '</div>';
        } else
        {
            return '<div class="layui-badge layui-bg-' . $option->label_type . '">' . $option->name . '</div>';
        }
    }

    public function transMoney($money) {
        return round($money * 100);
    }
}