<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\Team;
use App\Http\Requests\TeamRequest;

class TeamController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $teams = Team::with('users')->get();
        $teams = $teams->map(function ($team) {
            $team->manager_name = null;

            if (!$team->users->isEmpty()) {
                foreach ($team->users as $key => $value) {
                    if ($value->is_manager == 1) {
                        $team->manager_name = $value->name;
                    }
                }
            }

            return $team;
        });

        return view('admin.team.team', compact('teams'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $users = User::where('team_id', 0)->where('is_team', 1)->get()->pluck('name', 'id' )->all();

        return view('admin.team.team_create', compact('users'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param TeamRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(TeamRequest $request)
    {
        if ($request->input('user_id') && User::where('is_team', 1)->where('id', $request->input('user_id'))->where('team_id', '<>', 0)->exists()) {
            return back()->withInput()->with('error', '该用户已经归属别的团队，请重新选择');
        }

        $result = Team::create($request->except('user_id'));

        if ($result) {
            if ($request->get('user_id')) User::where('is_team', 1)->where('id', $request->input('user_id'))->update(['is_manager' => 1, 'team_id' => $result->id]);

            return redirect('admin/team')->with('success', '团队添加成功');
        }

        return back()->withInput()->with('error', '团队添加失败');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $team = Team::with('users')->find($id);
        $users = User::where('is_team', 1)->whereIn('team_id', [0, $id])->get();
        $managerId = null;

        foreach ($users as $key => $value) {
            if ($value->is_manager == 1) $managerId = $value->id;
        }

        $users = $users->pluck('name', 'id' )->all();

        return view('admin.team.team_edit', compact('team', 'users', 'managerId'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param TeamRequest $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(TeamRequest $request, $id)
    {
        $userId = $request->input('user_id');
        $team = Team::with('users')->find($id);
        $result = $team->fill($request->except('user_id'))->save();

        if ($result) {
            $manager = $team->users->where('is_manager', 1)->first();

            if ($manager) {
                User::where('is_team', 1)->where('id', $manager->id)->update(['is_manager' => 0]);
            }

            if ($userId) {
                User::where('is_team', 1)->where('id', $userId)->update(['is_manager' => 1, 'team_id' => $id]);
            }

            return redirect('admin/team')->with('success', '团队修改成功');
        }

        return back()->withInput()->with('error', '团队修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (User::where('is_team', 1)->where('team_id', $id)->count() > 0) {
            return response()->json(['status' => 'error', 'message' => '请先删除该团队下的人员！']);
        }
        $ids    = array_str($id);

        $result = Team::whereIn('id', $ids)->delete();

        return response()->json($result ? ['status' => 'success', 'message' => '团队删除成功！'] : ['status' => 'error', 'message' => '团队删除失败！']);
    }
}
