<?php

namespace App\Http\Controllers;

use App\CustomerLogStatus;
use App\Services\LogService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;


class CustomerLogStatusController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        if(!Gate::allows('客户-客户状态-查询')){ return redirect(url('denied'));  }
        $customerLogStatuses = CustomerLogStatus::query()->paginate();
        return view('customer.customerLogStatus.index', compact('customerLogStatuses'));
    }

    public function get()
    {
        return ["success"=>true,"data"=>app("CustomerLogStatusService")->getSelection()];
    }

    public function save(Request $request)
    {
        if(!Gate::allows('客户-客户状态-录入') || !Gate::allows('客户-客户状态-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        $errors = $this->validator($request->input(),$request->input("id"))->errors();
        if (count($errors) > 0)return ["success"=>true,"data"=>["errors"=>$errors]];
        if ($request->input("id")){
            app("CustomerLogStatusService")->update(["id"=>$request->input("id")],
                ["name"=>$request->input("name"),"description"=>$request->input("description")]);
            LogService::log(__METHOD__,"修改客户状态",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
            return ["success"=>true];
        }
        /** @var CustomerLogStatus $model */
        $model = app("CustomerLogStatusService")->create(["name"=>$request->input("name"),"description"=>$request->input("description")]);
        LogService::log(__METHOD__,"录入客户状态",$model->toJson());
        return ["success"=>true,"data"=>$model];
    }

    private function validator($params, $id)
    {
        return Validator::make($params,[
            "name" => ['max:50','required',$id?"unique:customer_log_statuses,name,$id":'unique:customer_log_statuses,name']
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 最大为50个字符',
            'unique'=>':attribute 已存在',
        ],[
            "name" => "名称"
        ]);
    }

    public function destroy(Request $request)
    {
        if(!Gate::allows('客户-客户状态-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $id = $request->input("id");
        if (!$id) return ["success"=>false,"data"=>"非法参数!"];
        app("CustomerLogStatusService")->destroy($request->input("id"));
        LogService::log(__METHOD__,"删除客户状态",$id);
        return ["success"=>true];
    }
}
