<?php

namespace App\Services\BasicManagement;

use Illuminate\Database\Eloquent\Model;
use App\Models\BasicManagement\QualityTesting;
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\QualityTestingValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Request;
use App\Services\LoginUserService;

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

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

    /**
     * @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 = ['qurp_id', 'qurp_name', 'qurp_type', 'qurp_standard', 'qurp_standard_type', 'qurp_remark', 'qurp_create_time', 'qurp_state'];
        }
        // if (isset($search_data['qurp_repu_type'])) {
        //     if ($search_data['qurp_repu_type'] == 1) {
        //         $search_data['qurp_type'] = [2];
        //     } elseif ($search_data['qurp_repu_type'] == 2) {
        //         $search_data['qurp_type'] = [3];
        //     }
        // }
        // 质检奖惩管理
        $list_data = DB::table('wash_quality_reward_punishment as w')
            ->where('qurp_cid', $user_info->adm_cid)
            ->where('qurp_shop_id', $user_info->adm_shop_id)
            ->where('qurp_delete', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['qurp_name'])) {
                    $query->where('qurp_name', 'like', '%'.$search_data['qurp_name'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['qurp_state'])) {
                    $query->where('qurp_state', $search_data['qurp_state']);
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['qurp_type'])) {
                    $query->whereIn('qurp_type', $search_data['qurp_type']);
                }
            })
            // ->select('qurp_id', 'qurp_name', 'qurp_type', 'qurp_standard', 'qurp_standard_type', 'qurp_remark', 'qurp_create_time', 'qurp_state')
            ->select($field_columns)
            ->orderBy('qurp_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 $name 考核项名称
     * @param $type 类型：1施工部位2整车3其他
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $name, $type, $id = 0) {
        if ($id == 0) {
            return QualityTesting::where('qurp_name', $name)
                ->where('qurp_shop_id', $user_info->adm_shop_id)
                ->where('qurp_type', '=', $type)
                ->where('qurp_delete', '=', 1)
                ->exists();
        } else {
            return QualityTesting::where('qurp_name', $name)
                ->where('qurp_type', '=', $type)
                ->where('qurp_shop_id', $user_info->adm_shop_id)
                ->where('qurp_delete', '=', 1)
                ->where('qurp_id', '<>', $id)
                ->exists();
        }
    }

    // 新增
    public static function add($user_info, $request) {
        $data['qurp_cid'] = $user_info->adm_cid;
        $data['qurp_superior_shop_id'] = $user_info->adm_shop_id;
        $data['qurp_shop_id'] = $user_info->adm_shop_id;
        $data['qurp_name'] = $request['qurp_name'];//考核项名称
        // if ($request['qurp_standard_type'] == 2) {
        //     $data['qurp_standard'] = $request['qurp_standard']*100;//标准金额(单位分)
        // } else {
        //     $data['qurp_standard'] = $request['qurp_standard'];//分数
        // }
        if ($request['qurp_type'] == 1) {
            $request['qurp_standard_type'] = 1;
            $data['qurp_standard'] = $request['qurp_standard'];//分数
        } elseif ($request['qurp_type'] == 2 || $request['qurp_type'] == 3) {
            $request['qurp_standard_type'] = 2;
            if ($request['qurp_type'] == 2) {
                $data['qurp_standard'] = abs($request['qurp_standard']*100);//标准金额(单位分)
            } elseif ($request['qurp_type'] == 3) {//惩罚项 强制负值
                $data['qurp_standard'] = -abs($request['qurp_standard']*100);
            }
        }
        $data['qurp_standard_type'] = $request['qurp_standard_type'];//标准类型1分数2金额
        $data['qurp_type'] = $request['qurp_type'];//类型1质检标准2奖励项3惩罚项
        $data['qurp_remark'] = empty($request['qurp_remark']) ? '' : $request['qurp_remark'];//备注
        $data['qurp_update_time'] = date('Y-m-d H:i:s');
        return QualityTesting::insert($data);
    }

    // 编辑
    public static function edit($request) {
        $data['qurp_name'] = $request['qurp_name'];//考核项名称
        // if ($request['qurp_standard_type'] == 2) {
        //     $data['qurp_standard'] = $request['qurp_standard']*100;//标准金额(单位分)
        // } else {
        //     $data['qurp_standard'] = $request['qurp_standard'];//分数
        // }
        if ($request['qurp_type'] == 1) {
            $request['qurp_standard_type'] = 1;
            $data['qurp_standard'] = $request['qurp_standard'];//分数
        } elseif ($request['qurp_type'] == 2 || $request['qurp_type'] == 3) {
            $request['qurp_standard_type'] = 2;
            if ($request['qurp_type'] == 2) {
                $data['qurp_standard'] = abs($request['qurp_standard']*100);//标准金额(单位分)
            } elseif ($request['qurp_type'] == 3) {//惩罚项 强制负值
                $data['qurp_standard'] = -abs($request['qurp_standard']*100);
            }
        }
        $data['qurp_standard_type'] = $request['qurp_standard_type'];//标准类型1分数2金额
        $data['qurp_type'] = $request['qurp_type'];//类型1质检标准2奖励项3惩罚项
        $data['qurp_remark'] = empty($request['qurp_remark']) ? '' : $request['qurp_remark'];//备注
        $data['qurp_update_time'] = date('Y-m-d H:i:s');
        return QualityTesting::where('qurp_id', $request['qurp_id'])
                ->update($data);
    }

    // 更改状态
    public static function editState($ids, $state) {
        $data['qurp_state'] = $state;
        $data['qurp_update_time'] = date('Y-m-d H:i:s');
        return QualityTesting::where('qurp_id', $ids)
                ->update($data);
    }

    // 更改删除状态
    public static function editDelete($ids, $state) {
        $data['qurp_delete'] = $state;
        $data['qurp_update_time'] = date('Y-m-d H:i:s');
        return QualityTesting::where('qurp_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 = QualityTesting::where('qurp_id', $id)
            ->where('qurp_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 = QualityTesting::whereIn('qurp_id', $ids)
            ->where('qurp_shop_id', $user_info->adm_shop_id)
            ->where('qurp_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;
    }
}
