<?php

namespace App\Http\Controllers\Mounting\BasicManage;

use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\BasicManagement\MeritPayService;
use App\Services\BasicManagement\GradeProfessionalService;
use App\Services\BasicManagement\GradeLevelService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Services\AutoPartsService;

// 绩效管理
class MeritPayController extends Controller
{
    public function __construct()
    {
        $this->dataService = $service = new MeritPayService();
        $this->dataServiceGrade = $serviceGrade = new GradeProfessionalService();
        $this->contentService = new GradeLevelService();
        $this->bootWithService($service);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->indexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 查询字段
        $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'];
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->searchPage($user_info, $request->all(), $request['show_count'], $field_columns);
        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button]);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        
        $exist = MeritPayService::nameExists($user_info, $request->all(), $request['pema_type'], 0);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }
        $res = MeritPayService::add($user_info, $request->all());
        if ($res) {
            $hint = $this->typeHint($request['pema_type']);
            OperationLog::addLog($user_info, getRealIp($request), '绩效管理', '新增', '新增'.$hint.':'.$request['pema_name'].'成功');
            return $this->success('新增成功');
        } else {
            return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $return_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_id', $request['pema_id'])
                ->select('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')
                ->first();
            return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
        }
        $exist = MeritPayService::nameExists($user_info, $request->all(), $request['pema_type'], $request['pema_id']);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }

        $res = MeritPayService::edit($request->all());
        if ($res) {
            $hint = $this->typeHint($request['pema_type']);
            OperationLog::addLog($user_info, getRealIp($request), '绩效管理', '编辑', '编辑'.$hint.':'.$request['pema_name'].'成功');
            return $this->success('编辑成功');
        } else {
            return $this->error('编辑失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->startValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $res = MeritPayService::editState($request['pema_id'], 1);
        if ($res) {
            // 获取启用的名称
            $field_columns = ['pema_name'];
            $find_pema = MeritPayService::getFieldsByIdAll($user_info, $request['pema_id'], $field_columns);
            $pema_name = array_column($find_pema, 'pema_name');

            $hint = $this->typeHint($request['pema_type']);
            OperationLog::addLog($user_info, getRealIp($request), '绩效管理', '启用', $hint.'：（'.implode(',', $pema_name).'）启用成功');
            return $this->success('启用成功');
        } else {
            return $this->error('启用失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->startValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $res = MeritPayService::editState($request['pema_id'], 2);
        if ($res) {
            // 获取停用的名称
            $field_columns = ['pema_name'];
            $find_pema = MeritPayService::getFieldsByIdAll($user_info, $request['pema_id'], $field_columns);
            $pema_name = array_column($find_pema, 'pema_name');

            $hint = $this->typeHint($request['pema_type']);
            OperationLog::addLog($user_info, getRealIp($request), '绩效管理', '停用', $hint.'：（'.implode(',', $pema_name).'）停用成功');
            return $this->success('停用成功');
        } else {
            return $this->error('停用失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 类型提示信息
    private function typeHint($type)
    {
        if ($type == 1) {
            $hint = '绩效管理-按施工部位';
        } elseif ($type == 2) {
            $hint = '绩效管理-按整车';
        } else {
            $hint = '绩效管理-其他';
        }
        return $hint;  
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function getGradeProfessional(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getGradeProfessionalValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        if (in_array($request['type'], [1])) {
            // 职称管理列表
            $search_data = $this->dataServiceGrade->searchPage($user_info, $request->all(), 10);
        } else {
            // 级别管理列表
            $search_data = $this->contentService->searchPage($user_info, $request->all(), 10);
        }

        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
        }
    }

    /**
     * 绩效设置获取部位金额
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-25
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getParts(Request $request) {
        if (empty($request['grpr_id']) || empty($request['grle_id']) || empty($request['sepr_id'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
        }
        $data = DB::table('auto_parts')
            ->where(function ($query) use ($request) {
                if (!empty($request['title'])) {
                    $query->where('title', 'like', '%' . $request['title'] . '%');
                }
            })
            ->select('id', 'title')
            ->get();
        foreach ($data as $key => $value) {
            $find_price = DB::table('wash_performance_manage')
                ->where('pema_grpr_id', $request['grpr_id'])
                ->where('pema_grle_id', $request['grle_id'])
                ->where('pema_service_type_id', $request['sepr_id'])
                ->where('pema_name', $value->title)
                ->select('pema_standard', 'pema_state', 'pema_id', 'pema_remark')
                ->first();
            if ($find_price) {
                $data[$key]->pema_standard = $find_price->pema_standard;
                $data[$key]->pema_state = $find_price->pema_state;
                $data[$key]->pema_id = $find_price->pema_id;
                $data[$key]->pema_remark = $find_price->pema_remark;
            } else {
                $data[$key]->pema_standard = 0;
                $data[$key]->pema_state = 0;
                $data[$key]->pema_id = 0;
                $data[$key]->pema_remark = '';
            }
        }

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 编辑
    public function newEdit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $res = MeritPayService::newEdit($user_info,$request->all());
        if ($res) {
            $hint = $this->typeHint($request['pema_type']);
            OperationLog::addLog($user_info, getRealIp($request), '绩效管理', '设置', '设置'.$hint.':'.$request['pema_name'].'成功');
            return $this->success('设置成功');
        } else {
            return $this->error('设置失败', ErrorInc::MYSQL_FAILED);
        }
    }
}