<?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\DB;

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

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

    /**
     * @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[] = ['grpr_shop_id', '=', $shopID];

        if (!empty($param['keywords'])) {
            $where[] = ['grpr_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('grpr_id', 'ASC')
                ->offset($offset)
                ->limit($pageSize)
                ->get();
        } else {
            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('grpr_id', 'ASC')
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    /**
     * 检查是不是存在同名内容
     * @param string $name 待检测名称
     * @param int $id 排除这个id
     *
     * @return mixed
     */
    public static function nameExists($name, $id = 0) {
        $shopID = LoginUserService::getUserShopID();
        if ($id == 0) {
            return TechnicalTitle::where('grpr_name', $name)
                ->where('grpr_shop_id', $shopID)
                ->exists();
        } else {
            return TechnicalTitle::where('grpr_shop_id', $shopID)
                ->where('grpr_id', '<>', $id)
                ->where('grpr_name', $name)
                ->exists();
        }
    }

    /**
     * 开启关闭某职称
     * @param int $id       职称ID值
     * @param int $enable   开关状态值
     *
     * @return bool
     */
    public static function setEnable(int $id, $enable = 1)
    {
        $shopID = LoginUserService::getUserShopID();
        return TechnicalTitle::where('grpr_shop_id', $shopID)
            ->where('grpr_id', $id)
            ->update(['grpr_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    需要的字段
     *
     * @return mixed
     */
    public static function getFieldsById($ID, $fields = '*'){
        $shopID = LoginUserService::getUserShopID();
        $entity = TechnicalTitle::where('grpr_id', $ID)
            ->where('grpr_shop_id', $shopID)
            ->select($fields)
            ->first();

        return $entity;
    }

    /**
     * 查询门店内职称
     * @param string $name        查询关键字
     * @param int $shopID         所属门店ID
     *
     * @return mixed
     */
    public static function searchTitle($name, $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        return TechnicalTitle::select('grpr_id', 'grpr_name', 'grpr_remark', 'grpr_state', 'grpr_delete')
            ->where('grpr_shop_id', '=', $shopID)
            ->name($name)
            ->with(array('levels:grle_id,grle_name,grle_grpr_id'))
            ->get();
    }

    /**
     * 查询门店内所有职称
     *
     * @param int $shopID         所属门店ID
     *
     * @return mixed
     */
    public static function getShopData($shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }

        return (new TechnicalTitle())
            ->select('grpr_id','grpr_name', 'grpr_remark')
            ->where('grpr_shop_id', $shopID)
            ->where('grpr_state', 1)
            ->with('levels')
            ->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_title_'.$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['grpr_id'], $ids)) {
                    $data[$val['grpr_id']] = $val;
                }
                $itemList[$val['grpr_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME+rand(0, 10)); //防止缓存雪崩
        }

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

    /**
     * 获取某个职称
     *
     * @param int $ID       获取ID值
     * @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_title_'.$shopID;
        $data = [];
        if ($refresh == 1) {
            goto NOCACHE;
        }
        $cacheExist = Cache::has($cacheKey);
        if ($cacheExist) { //防止缓存穿透
            $itemList = Cache::get($cacheKey);
            foreach ($itemList as $key=>$val) {
                if ($val['grpr_id'] == $ID) {
                    return $val;
                }
            }
        } else {
            NOCACHE:
            $itemList = [];
            $itemData =  static::getShopData($shopID);
            foreach ($itemData as $key=>$val) {
                if ($val['grpr_id'] == $ID) {
                    $data = $val;
                }
                $itemList[$val['grpr_id']] = $val;
            }
            Cache::set($cacheKey, $itemList, CacheInc::CACHE_TIME + rand(0, 10)); //防止缓存雪崩
        }

        return $data;
    }
}
