<?php

namespace App\Services\BasicManagement;

use Illuminate\Database\Eloquent\Model;
use App\Models\BasicManagement\ValidateCarManage;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\BasicManagement\ValidateCarManageValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Request;

class ValidateCarManageService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new ValidateCarManage();
        $this->mainValidator = new ValidateCarManageValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($user_info, $search_data, $show_count = 10, $field_columns = [])
    {
        // 判断是否传入查询字段
        if (empty($field_columns)) {
            $field_columns = ['vacm_id', 'vacm_unusual_name', 'vacm_type', 'vacm_remark'];
        }

        // 验车管理搜索
        $list_data = DB::table('wash_validate_car_manage')
            ->where('vacm_shop_id', $user_info->adm_shop_id)
            ->where('vacm_type', $search_data['vacm_type'])
            ->where('vacm_delete', 1) //是否删除：1正常2已删除
            // ->where('vacm_state', 1) //状态1启用2停用
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vacm_unusual_name'])) {
                    $query->where('vacm_unusual_name', 'like', '%' . $search_data['vacm_unusual_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {//状态1启用2停用
                if (!empty($search_data['vacm_state'])) {
                    $query->where('vacm_state', $search_data['vacm_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['remark'])) {
                    $query->where('vacm_remark', 'like', '%' . $search_data['remark'] . '%');
                }
            })
            ->select($field_columns)
            ->orderBy('vacm_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();

        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function search($param, $columns = array('*'), $page = 1, $pageSize = 20)
    {
        // $shopID = $user_info->adm_shop_id;
        $where = [];
        // $where[] = ['vacm_shop_id', '=', $shopID];
        $where[] = ['vacm_delete', '=', 1];
        if (!empty($param['type'])) {
            $where[] = ['vacm_type', '=', $param['type']];
        }
        if (!empty($param['vacm_state'])) {
            $where[] = ['vacm_state', '=', $param['vacm_state']];
        }
        if (!empty($param['keywords'])) {
            $where[] = ['vacm_unusual_name', 'like', '%' .$param['keywords'] . '%'];
        }
        $count = 0;
        $totalPage = 0;
        if ($pageSize > 0) {
            $count = $this->modelMain
                ->where($where)
                ->count();
            $totalPage = ceil($count / $pageSize);
            $offset = ($page - 1) * $pageSize;

            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('vacm_id', 'ASC')
                ->offset($offset)
                ->limit($pageSize)
                ->get()->toArray();
        } else {
            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('vacm_id', 'ASC')
                ->get()->toArray();
        }
        $result = [];
        // $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result = ['last_page' => $totalPage, 'total' => $count, 'current_page' => $page, 'current_number' => $pageSize];
        $result['data'] = $list;

        return $result;
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 待检测名称
     * @param $type 类型：1车内异常管理2外观异常管理
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $name, $type, $id = 0) {
        if ($id == 0) {
            return ValidateCarManage::where('vacm_unusual_name', $name)
                ->where('vacm_shop_id', $user_info->adm_shop_id)
                ->where('vacm_type', '=', $type)
                ->where('vacm_delete', '=', 1)
                ->exists();
        } else {
            return ValidateCarManage::where('vacm_unusual_name', $name)
                ->where('vacm_type', '=', $type)
                ->where('vacm_shop_id', $user_info->adm_shop_id)
                ->where('vacm_delete', '=', 1)
                ->where('vacm_id', '<>', $id)
                ->exists();
        }
    }

    // 新增
    public static function add($user_info, $request) {
        $data['vacm_cid'] = $user_info->adm_cid;
        $data['vacm_superior_shop_id'] = $user_info->adm_shop_id;
        $data['vacm_shop_id'] = $user_info->adm_shop_id;
        $data['vacm_unusual_name'] = $request['vacm_unusual_name'];
        $data['vacm_type'] = $request['vacm_type'];
        if (Request::input('vacm_remark', '')) {
            $data['vacm_remark'] = Request::input('vacm_remark', '');
        } else {
            $data['vacm_remark'] = '';
        }
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarManage::insert($data);
    }

    // 编辑
    public static function edit($request) {
        $data['vacm_unusual_name'] = $request['vacm_unusual_name'];
        if (Request::input('vacm_remark', '')) {
            $data['vacm_remark'] = Request::input('vacm_remark', '');
        } else {
            $data['vacm_remark'] = '';
        }
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarManage::where('vacm_id', $request['vacm_id'])
                ->update($data);
    }

    // 更改状态
    public static function editState($ids, $state) {
        $data['vacm_state'] = $state;
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarManage::whereIn('vacm_id', $ids)
                ->update($data);
    }

    // 更改删除状态
    public static function editDelete($ids, $state) {
        $data['vacm_delete'] = $state;
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarManage::whereIn('vacm_id', $ids)
                ->update($data);
    }
    
    /**
     * @param int $id
     *
     * @param int $enable
     * @return mixed
     */
    public static function setEnable(int $id, $enable = 1)
    {
        $apiUser = LoginUserService::getUser();
        if (empty($apiUser)) {
            return false;
        }
        $shopID = $apiUser->adm_shop_id;
        return ValidateCarManage::where('vacm_shop_id', $shopID)
            ->where('vacm_id', $id)
            ->update(['vacm_state' => $enable]);
    }

    public static function getFieldsById($id, $fields = '*'){
        $apiUser = LoginUserService::getUser();
        if (empty($apiUser)) {
            return false;
        }
        $shopID = $apiUser->adm_shop_id;
    	$entity = ValidateCarManage::where('vacm_id', $id)
            ->where('vacm_shop_id', $shopID)
            ->select($fields)
            ->first();

    	return $entity;
    }

    /**
     * [getFieldsByIdAll 根据id查询数据]
     * @param  [object] $user_info [用户信息]
     * @param  [array] $ids       [数组，id]
     * @param  array $fields    [数组，查询字段]
     * @return [type]            [description]
     */
    public static function getFieldsByIdAll($user_info, $ids = [], $fields = '*') {
    	$entity = ValidateCarManage::whereIn('vacm_id', $ids)
            ->where('vacm_shop_id', $user_info->adm_shop_id)
            ->where('vacm_delete', 1)
            ->select($fields)
            ->get()->toArray();
        return $entity;
    }

    public static function getShopData() {
        $apiUser = LoginUserService::getUser();
        if (empty($apiUser)) {
            return false;
        }
        $shopID = $apiUser->adm_shop_id;
        // $shop_superior_id = $apiUser->shop_superior_id;
        // $adm_cid = $apiUser->adm_cid;
        return (new ValidateCarManage())
            ->select('vacm_id','vacm_unusual_name')
            ->where('vacm_shop_id', $shopID)
            ->get()
            ->toArray();
    }

    /**
     * 获取全部level
     * @param array $ids 从id数组中找
     * @param int $refresh 强制读数据库并更新redis缓存
     *
     * @return mixed
     */
    public static function getAll($ids = [], $refresh = 0) {
        $cacheKey = 'technical_level';
        $data = [];
        if ($refresh == 1) {
            goto NOCACHE;
        }
        $cacheExist = Cache::has($cacheKey);
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            if (!empty($ids)) {
                foreach ($ids as $val) {
                    $data[$val] = $itemList[$val];
                }
            }
        } else {
            NOCACHE:
            $itemList = [];
            $itemData = static::getShopData();
            foreach ($itemData as $k=>$val) {
                if ($ids && in_array($val['grle_id'], $ids)) {
                    $data[$val['grle_id']] = $val;
                }
                $itemList[$val['grle_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME+rand(0, 10)); //防止缓存雪崩
        }

        return !empty($ids) ? $data : $itemList;
    }

    /**
     * 获取某个level
     *
     * @param int $ID
     *
     * @return mixed
     */
    public static function getByID(int $ID) {
        $cacheKey = 'technical_level';
        $cacheExist = Cache::has($cacheKey);
        $data = [];
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            foreach ($itemList as $key=>$val) {
                if ($val['vacm_id'] = $ID) {
                    return $val;
                }
            }
        } else {
            $itemList = [];
            $itemData =  static::getShopData();
            foreach ($itemData as $key=>$val) {
                if ($val['vacm_id'] = $ID) {
                    $data = $val;
                }
                $itemList[$val['vacm_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME + rand(0, 10)); //防止缓存雪崩
        }

        return $data;
    }
}
