<?php

namespace App\Services\BasicManagement;

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

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

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

    /**
     * @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 = ['pema_id', 'pema_name', 'pema_grpr_id', 'pema_grle_id', 'pema_standard', 'pema_remark', 'grle_name', 'grpr_name', 'pema_state', 'pema_service_type_id', 'pema_service_type_name', 'pema_weixiu', 'pema_huanjian'];
        }
        // 绩效管理表
        $list_data = DB::table('wash_performance_manage as w')
            ->leftJoin('wash_grade_level as wgl', 'w.pema_grle_id', '=', 'wgl.grle_id')
            ->leftJoin('wash_grade_professional as wgp', 'w.pema_grpr_id', '=', 'wgp.grpr_id')
            ->where('pema_cid', $user_info->adm_cid)
            ->where('pema_shop_id', $user_info->adm_shop_id)
            ->where('pema_delete', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_name'])) {
                    $query->where('pema_name', 'like', '%' . $search_data['pema_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_state'])) {
                    $query->where('pema_state', $search_data['pema_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_type'])) {
                    $query->where('pema_type', $search_data['pema_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_grpr_id'])) {
                    $query->where('pema_grpr_id', $search_data['pema_grpr_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_grle_id'])) {
                    $query->where('pema_grle_id', $search_data['pema_grle_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pema_service_type_id'])) {
                    $query->where('pema_service_type_id', $search_data['pema_service_type_id']);
                }
            })
            ->select($field_columns)
            ->orderBy('pema_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, $request, $type, $id = 0)
    {
        if ($id == 0) {
            return MeritPay::where('pema_name', $request['pema_name'])
                ->where('pema_shop_id', $user_info->adm_shop_id)
                ->where('pema_type', $type)
                ->where('pema_service_type_id', $request['pema_service_type_id'])
                ->where(function ($query) use ($type, $request) { //职级职称
                    if ($type == 1) {
                        $query->where('pema_grpr_id', $request['pema_grpr_id'])
                        ->where('pema_grle_id', $request['pema_grle_id']);
                        // $query->where('chun_adm_id', $search_data['chun_adm_id'])
                        //     ->where('ord_type', 2);
                    }
                })
                ->where('pema_delete', 1)
                ->exists();
        } else {
            return MeritPay::where('pema_name', $request['pema_name'])
                ->where('pema_type', '=', $type)
                ->where('pema_service_type_id', $request['pema_service_type_id'])
                ->where(function ($query) use ($type, $request) { //职级职称
                    if ($type == 1) {
                        $query->where('pema_grpr_id', $request['pema_grpr_id'])
                        ->where('pema_grle_id', $request['pema_grle_id']);
                        // $query->where('chun_adm_id', $search_data['chun_adm_id'])
                        //     ->where('ord_type', 2);
                    }
                })
                ->where('pema_shop_id', $user_info->adm_shop_id)
                ->where('pema_delete', 1)
                ->where('pema_id', '<>', $id)
                ->exists();
        }
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['pema_cid'] = $user_info->adm_cid;
        $data['pema_superior_shop_id'] = $user_info->adm_shop_id;
        $data['pema_shop_id'] = $user_info->adm_shop_id;
        $data['pema_service_type_id'] = $request['pema_service_type_id']; //考核项服务类型id
        $data['pema_service_type_name'] = $request['pema_service_type_name']; //考核项服务类型名称
        $data['pema_name'] = $request['pema_name']; //考核项名称
        if ($request['pema_type'] == 1) {
            $data['pema_grpr_id'] = $request['pema_grpr_id']; //职位id
            $data['pema_grle_id'] = $request['pema_grle_id']; //级别id
        }
        $data['pema_standard'] = $request['pema_standard'] * 100; //标准金额(单位分) 取件
        $data['pema_weixiu'] = $request['pema_weixiu'] * 100; //标准金额(单位分) 维修
        $data['pema_huanjian'] = $request['pema_huanjian'] * 100; //标准金额(单位分) 还件
        $data['pema_type'] = $request['pema_type']; //类型1施工部位2整车3其他
        $data['pema_remark'] = empty($request['pema_remark']) ? '':$request['pema_remark'];
        $data['pema_update_time'] = date('Y-m-d H:i:s');
        return MeritPay::insert($data);
    }

    // 编辑
    public static function edit($request)
    {
        $data['pema_name'] = $request['pema_name']; //考核项名称
        $data['pema_service_type_id'] = $request['pema_service_type_id']; //考核项服务类型id
        $data['pema_service_type_name'] = $request['pema_service_type_name']; //考核项服务类型名称
        if ($request['pema_type'] == 1) {
            $data['pema_grpr_id'] = $request['pema_grpr_id']; //职位id
            $data['pema_grle_id'] = $request['pema_grle_id']; //级别id
        }
        $data['pema_standard'] = $request['pema_standard']*100; //标准金额(单位分)
        $data['pema_weixiu'] = $request['pema_weixiu'] * 100; //标准金额(单位分) 维修
        $data['pema_huanjian'] = $request['pema_huanjian'] * 100; //标准金额(单位分) 还件
        $data['pema_remark'] = empty($request['pema_remark']) ? '':$request['pema_remark'];
        $data['pema_update_time'] = date('Y-m-d H:i:s');
        return MeritPay::where('pema_id', $request['pema_id'])
            ->update($data);
    }

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


    /**
     * 获取全部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;
    }

    /**
     * [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 = MeritPay::where('pema_id', $ids)
            ->where('pema_shop_id', $user_info->adm_shop_id)
            ->where('pema_delete', 1)
            ->select($fields)
            ->get()->toArray();
        return $entity;
    }

    /**
     * 获取某个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;
    }

    public static function newEdit($user_info, $request) {
        $pema_id = DB::table('wash_performance_manage')
            ->where('pema_grpr_id', $request['pema_grpr_id'])
            ->where('pema_grle_id', $request['pema_grle_id'])
            ->where('pema_service_type_id', $request['pema_service_type_id'])
            ->where('pema_name', $request['pema_name'])
            ->value('pema_id');
        if ($pema_id) {
            $data['pema_name'] = $request['pema_name']; //考核项名称
            $data['pema_service_type_id'] = $request['pema_service_type_id']; //考核项服务类型id
            $data['pema_service_type_name'] = $request['pema_service_type_name']; //考核项服务类型名称
            if ($request['pema_type'] == 1) {
                $data['pema_grpr_id'] = $request['pema_grpr_id']; //职位id
                $data['pema_grle_id'] = $request['pema_grle_id']; //级别id
            }
            $data['pema_standard'] = $request['pema_standard']*100; //标准金额(单位分)
            $data['pema_remark'] = empty($request['pema_remark']) ? '':$request['pema_remark'];
            $data['pema_update_time'] = date('Y-m-d H:i:s');
            return MeritPay::where('pema_id', $pema_id)
                ->update($data);
        } else {
            $data['pema_cid'] = $user_info->adm_cid;
            $data['pema_superior_shop_id'] = $user_info->adm_shop_id;
            $data['pema_shop_id'] = $user_info->adm_shop_id;
            $data['pema_service_type_id'] = $request['pema_service_type_id']; //考核项服务类型id
            $data['pema_service_type_name'] = $request['pema_service_type_name']; //考核项服务类型名称
            $data['pema_name'] = $request['pema_name']; //考核项名称
            if ($request['pema_type'] == 1) {
                $data['pema_grpr_id'] = $request['pema_grpr_id']; //职位id
                $data['pema_grle_id'] = $request['pema_grle_id']; //级别id
            }
            $data['pema_standard'] = $request['pema_standard'] * 100; //标准金额(单位分)
            $data['pema_type'] = $request['pema_type']; //类型1施工部位2整车3其他
            $data['pema_remark'] = empty($request['pema_remark']) ? '':$request['pema_remark'];
            $data['pema_update_time'] = date('Y-m-d H:i:s');
            return MeritPay::insert($data);
        }
    }
}
