<?php

namespace App\Http\Controllers;

use App\CustomerLog;
use App\CustomerTag;
use App\Owner;
use App\Services\LogService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class CustomerBaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        if(!Gate::allows("客户-查询"))return view("exception.authority");
        $customers = app('CustomerService')->paginate($request->input(),["owners.contracts.files","tags:id,name","customerLogs"=>function($query){
            /** @var Builder $query */
            $query->with(["status:id,name,created_at","user:id,name"])->orderByDesc('id');
        }]);
        $owners = app("OwnerService")->getIntersectPermitting(['id','name','customer_id']);
        $tags = CustomerTag::query()->orderByDesc('count')->get(["id","name"]);
        $params = $request->input();
        return response()->view('customer.customer.index',compact("customers","owners","tags","params"));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!Gate::allows('客户-录入')){ return redirect('denied');  }
        return response()->view('customer.customer.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     * @throws
     */
    public function store(Request $request)
    {
        if(!Gate::allows('客户-录入')){ return redirect('denied');  }
        $this->validator($request->input())->validate();
        app('CustomerService')->create([
            "code"=>$request->input("code"),
            "name"=>$request->input("name"),
            "company_name"=>$request->input("company_name"),
            "invoice_address"=>$request->input("invoice_address"),
            "contact_man"=>$request->input("contact_man"),
            "phone"=>$request->input("phone"),
            "remark"=>$request->input("remark"),
        ]);
        LogService::log(__METHOD__,"录入客户",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("customer/customer")->with("successTip","成功创建客户“".$request->input("name")."”");
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if(!Gate::allows('客户-编辑')){ return redirect('denied');  }
        $customer = app('CustomerService')->find($id);
        return response()->view('customer.customer.create',compact("customer"));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     * @throws
     */
    public function update(Request $request, $id)
    {
        if(!Gate::allows('客户-编辑')){ return redirect('denied');  }
        $this->validator($request->input(),$id)->validate();
        $result = app('CustomerService')->update(["id"=>$id],[
            "code"=>$request->input("code"),
            "name"=>$request->input("name"),
            "company_name"=>$request->input("company_name"),
            "invoice_address"=>$request->input("invoice_address"),
            "contact_man"=>$request->input("contact_man"),
            "phone"=>$request->input("phone"),
            "remark"=>$request->input("remark"),
        ]);
        if ($result == 1){
            LogService::log(__METHOD__,"修改客户",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
            return response()->redirectTo("customer/customer")->with("successTip","成功修改客户“".$request->input("name")."”的信息");
        }
        return response()->view("exception.default",["code"=>"509"]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return array
     */
    public function destroy($id)
    {
        if(!Gate::allows('客户-删除')){ return ["success"=>false,"data"=>"无权操作！"];  }
        $result = app('CustomerService')->destroy($id);
        if ($result == 1){
            LogService::log(__METHOD__,"删除客户",$id);
            return ["success"=>true];
        }
        return ["success"=>false,"data"=>"删除了“".$result."”行"];
    }

    private function validator(array $params, $id = null)
    {
        return Validator::make($params,[
            'code'=>['required',$id?"unique:customers,code,$id":'unique:customers,code','max:20'],
            'name'=>['required','max:20'],
            'company_name'=>['required'],
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 字符过多或输入值过大',
            'unique'=>':attribute 已存在',
        ],[
            'code'=>'客户代码',
            'name'=>'客户名称',
            'company_name'=>'公司名称',
        ]);
    }

    public function relatedOwner(Request $request)
    {
        $ids = $request->input("ids") ?? [];
        $id = $request->input("customer_id");
        $row = Owner::query()->whereIn("id",$ids)->update(["customer_id"=>$id]);
        if ($row==count($ids))return ["success"=>true];
        return ["success"=>false,"data"=>"修改错误，影响了“".$row."”个项目"];
    }

    public function addTag(Request $request)
    {
        $tag = $request->input("tag");
        $id = $request->input("id");
        DB::transaction(function ()use ($id,$tag){
            DB::insert(DB::raw("INSERT INTO customer_tag_customer VALUES (?,?)"),[$id,$tag]);
            CustomerTag::query()->where("id",$tag)->increment("count");
            DB::commit();
        });
        return ["success"=>true];
    }

    public function delTag(Request $request)
    {
        $tag = $request->input("tag");
        $id = $request->input("id");
        DB::delete(DB::raw("DELETE FROM customer_tag_customer WHERE customer_id = ? AND customer_tag_id = ?"),[$id,$tag]);
        return ["success"=>true];
    }

    public function destroyLog(Request $request)
    {
        CustomerLog::destroy($request->input("id"));
        return ["success"=>true];
    }
}
