<?php

namespace App\Http\Controllers;

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

class CustomerTagController extends Controller
{
    public function index()
    {
        $tags = CustomerTag::query()->orderByDesc("id")->get();
        return view("customer.customer.tag.index",compact("tags"));
    }

    public function save(Request $request)
    {
        if(!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")){
            CustomerTag::query()->where("id",$request->input("id"))->update([
                "name"=>$request->input("name"),
                "explanation"=>$request->input("explanation")
            ]);
            LogService::log(__METHOD__,"录入客户标签",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
            return ["success"=>true];
        }
        $model = CustomerTag::query()->create([
            "name"=>$request->input("name"),
            "explanation"=>$request->input("explanation")
        ]);
        LogService::log(__METHOD__,"录入客户标签",$model->toJson());
        return ["success"=>true,"data"=>$model];
    }

    public function destroy($id)
    {
        if(!Gate::allows('客户-客户标签-删除')){ return ["success"=>false,"data"=>"无权操作！"];  }
        CustomerTag::destroy($id);
        LogService::log(__METHOD__,"删除客户标签",$id);
        return ["success"=>true];
    }

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

    public function get()
    {
        return ["success"=>true,"data"=>CustomerTag::query()->get(["id","name"])];
    }
}
