<?php

namespace App\Services;

use App\Inc\CacheInc;
use App\Models\ValidateCarTest;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

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

    public function __construct()
    {
        $this->modelMain = new ValidateCarTest();
    }

    /**
     * @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 search($param, $columns = array('*'), $page = 1, $pageSize = 20)
    {
        $apiUser = LoginUserService::getUser();
        if (empty($apiUser)) {
            return false;
        }
        $shopID = $apiUser->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 ValidateCarTest::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 ValidateCarTest::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'];
        $data['vacm_remark'] = $request['vacm_remark'];
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarTest::insert($data);
    }

    // 编辑
    public static function edit($request) {
        $data['vacm_unusual_name'] = $request['vacm_unusual_name'];
        $data['vacm_remark'] = $request['vacm_remark'];
        $data['vacm_update_time'] = date('Y-m-d H:i:s');
        return ValidateCarTest::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 ValidateCarTest::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 ValidateCarTest::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 ValidateCarTest::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 = ValidateCarTest::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 = ValidateCarTest::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 ValidateCarTest())
            ->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;
    }
}
