<?php

/**
 * 演示服务
 *
 * @author lixiaolin
 * @Date: 2021/8/17
 * @Time: 下午17:33
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

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

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

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

    /**
     * @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)
    {
        $shopID = LoginUserService::getUserShopID();
        $where = [];
        $where[] = ['grle_shop_id', '=', $shopID];
        if (!empty($param['grpr_id'])) {
            $where[] = ['grle_grpr_id', '=', $param['grpr_id']];
        }
        if (!empty($param['keywords'])) {
            $where[] = ['grle_name', 'like', '%' .$param['keywords'] . '%'];
        }

        $count = $this->modelMain
            ->where($where)
            ->count();
        $totalPage = ceil($count / $pageSize);
        if ($pageSize > 0) {
            $offset = ($page - 1) * $pageSize;

            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('grle_id', 'ASC')
                ->offset($offset)
                ->limit($pageSize)
                ->with(array('title:grpr_id,grpr_name'))
                ->get();
        } else {
            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('grle_id', 'ASC')
                ->with(array('title:grpr_id,grpr_name'))
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    /**
     * 检查是不是存在同名内容
     * @param string $name 待检测名称
     * @param int $titleID 职能ID
     * @param int $id 排除这个id
     *
     * @return mixed
     */
    public static function nameExists($name, $titleID, $id = 0) {
        $shopID = LoginUserService::getUserShopID();
        if ($id == 0) {
            return TechnicalLevel::where('grle_name', $name)
                ->where('grle_shop_id', $shopID)
                ->where('grle_grpr_id', '=', $titleID)
                ->exists();
        } else {
            return TechnicalLevel::where('grle_name', $name)
                ->where('grle_grpr_id', '=', $titleID)
                ->where('grle_shop_id', $shopID)
                ->where('grle_id', '<>', $id)
                ->exists();
        }
    }
    /**
     * 开启关闭某级别
     * @param int $id       级别ID值
     * @param int $enable   开关状态值
     *
     * @return bool
     */
    public static function setEnable(int $id, $enable = 1)
    {
//        $shopID = LoginUserService::getUserShopID(); 查询判断了shopID，所以更新不必要做条件限制
        return TechnicalLevel::where('grle_id', $id)
//            ->where('grle_shop_id', $shopID)
            ->update(['grle_state' => $enable]);
    }
    /**
     * 删除门店内级别
     *
     * @param int $ID   删除ID值
     *
     * @return mixed
     */
    public function delete($ID)
    {
        $shopID = LoginUserService::getUserShopID();
        return TechnicalTitle::where('grpr_id', $ID)
            ->where('grpr_shop_id', $shopID)
            ->update(['grpr_delete' => 2]);
    }

    /**
     * 查询门店内级别
     *
     * @param int $id           获取ID值
     * @param string $fields    需要的字段
     * @param int $shopID       门店ID
     *
     * @return mixed
     */
    public static function getFieldsById($id, $fields = '*', $shopID = 0){
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
    	$entity = TechnicalLevel::where('grle_id', $id)
            ->where('grle_shop_id', $shopID)
            ->select($fields)
            ->first();

    	return $entity;
    }

    /**
     * 查询门店内级别
     * @param string $name 查询关键字
     * @param int $titleID  职称id
     * @param int $shopID 所属门店ID
     *
     * @return mixed
     */
    public static function searchLevel($name, $titleID = 0, $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        if ($titleID > 0) {
            return TechnicalLevel::select('grle_id', 'grle_grpr_id', 'grle_name', 'grle_remark')
                ->where('grle_shop_id', $shopID)
                ->where('grle_grpr_id', $titleID)
                ->where('grle_state', 1)
                ->name($name)
                ->get();
        }
        return TechnicalLevel::select('grle_id', 'grle_grpr_id', 'grle_name', 'grle_remark')
            ->where('grle_shop_id', $shopID)
            ->where('grle_state', 1)
            ->name($name)
            ->get();
    }
    /**
     * 查询门店内所有级别
     *
     * @param int $shopID         所属门店ID
     *
     * @return mixed
     */
    public static function getShopData($shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
//        $shop_superior_id = $apiUser['shop_superior_id'];
//        $adm_cid = $apiUser['adm_cid'];
        return (new TechnicalLevel())
            ->select('grle_id','grle_name', 'grle_grpr_id')
            ->where('grle_shop_id', $shopID)
            ->where('grle_state', 1)
            ->get()
            ->toArray();
    }

    /**
     * 获取全部level
     * @param array $ids 从id数组中找
     * @param int $shopID 所属门店ID
     * @param int $refresh 强制读数据库并更新redis缓存
     *
     * @return mixed
     */
    public static function getAll($ids = [], $shopID = 0, $refresh = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        $cacheKey = 'technical_level_'.$shopID;
        $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($shopID);
            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 levelID
     * @param int $shopID 门店ID
     *
     * @param int $refresh
     * @return mixed
     */
    public static function getByID(int $ID, $shopID = 0, $refresh = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        $cacheKey = 'technical_level_'.$shopID;
        $data = [];
        if ($refresh == 1) {
            goto NOCACHE;
        }
        $cacheExist = Cache::has($cacheKey);
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            foreach ($itemList as $key=>$val) {
                if ($val['grle_id'] == $ID) {
                    return $val;
                }
            }
        } else {
            NOCACHE:
            $itemList = [];
            $itemData =  static::getShopData($shopID);
            foreach ($itemData as $key=>$val) {
                if ($val['grle_id'] == $ID) {
                    $data = $val;
                }
                $itemList[$val['grle_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME + rand(0, 10)); //防止缓存雪崩
        }

        return $data;
    }
}
