<?php

namespace App\Http\Controllers\Admin;

use App\Imports\ProjectImport;
use App\Models\AdminRoleModel;
use App\Models\Department;
use App\Models\Notification;
use App\Models\Order;
use App\Models\Project;
use App\Models\ProjectUser;
use App\Models\Road;
use App\Models\Role;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;


class ProjectController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '项目';

    protected $pre_uri = '/admin/Project/';

    protected $view_path = 'admin.projects.';

    protected $redirect_index = '/admin/Project/index';

    public function __construct()
    {
        parent::__construct();
        $this->model = new Project();
    }

    public function index()
    {
        $manager_user_id = ProjectUser::getProjectManagerUser();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri','manager_user_id'));
    }

    public function applyIndex()
    {

        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'apply-index', compact('model', 'model_name','pre_uri'));
    }

    public function get(Request $request)
    {
        if ($request->input('index')=='index')
        {
            $items = $this->model->where('id','!=','1')->where('active',1)->orderBy('id', 'desc')->orderBy('created_at', 'desc');
        }else if ($request->input('index')== 'apply-index')
        {
            $items = $this->model->where('id','!=','1')->where('active','!=',1)->orderBy('id', 'desc')->orderBy('created_at', 'desc');
        }else
        {
            $items = $this->model->where('id','!=','1')->orderBy('id', 'desc')->orderBy('created_at', 'desc');
        }
        $tmp_items = collect(['name']);
        foreach($tmp_items as $tmp_item) {
            if($request->has($tmp_item) && !empty($request->input($tmp_item))) {
                $items = $items->where($tmp_item, 'like', '%' . $request->input($tmp_item) . '%');
            }
        }

        $select_items = collect([]);
        foreach($select_items as $select_item) {
            if($request->has($select_item) && !empty($request->input($select_item))) {
                $items = $items->where($select_item, '=', $request->input($select_item));
            }
        }

        if ($request->input('project_id'))
        {
            $items->where('id','=',request('project_id'));
        }

        if($request->input('type') == 'apply') {
            $items = $items->whereNotNull('user_id');
        }
        $manager_user_id = request('manager_user_id',0);
        if(empty($manager_user_id)){
            $manager_user_id = 0;
        }
        if($manager_user_id){
            $items->whereHas('project_user',function ($query){
                $query->where('project_role_id','=','4');
                $query->whereHas('user',function ($query){
                    $query->where('id','=',request('manager_user_id'));
                });
            });
        }
        if ($request->input('project_name'))
        {
            $items->where('name','like','%'.request('project_name').'%');
        }
        $items = $items->paginate();

        foreach($items as $item) {
            $item->active_label = $item->getNameOrLabel('active', 'label');
            $item->manager = $item->getManager();
            $item->manager_name = $item->manager ? $item->manager->name : '';
            $item->manager_phone = $item->manager ? $item->manager->phone : '';
            $item->user_name = $item->user ? $item->user->name : '';
            $item->user_avatar = $item->user ? $item->user->getAvatar() : '';
            $item->user_phone = $item->user ? $item->user->phone : '';
        }

        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
    }

    public function create()
    {
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri'));
    }

    public function store(Request $request)
    {
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'store');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        $res = $this->model->create($data);
        if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
        return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
    }

    public function edit(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item'));
    }

    public function update(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'update');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        $res = $this->model->where('id', $request->input('id'))->update($data);
        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败！']);
        return back()->with(['sg_success_info' => '编辑成功']);
    }

    public function delete(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return response()->json(['status' => 'fail', 'info' => '找不到要删除的数据']);
        $res = $item->delete();
        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

    public function change(Request $request)
    {
        $this->model->where('id', $request->input('id'))->update(['active' => $request->input('active')]);
        Notification::sendProjectInfo($request->input('id'));
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

    public function active(Request $request)
    {
        $this->model->where('id', $request->input('id'))->update(['active' => 1]);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

    public function getStat(Request $request)
    {
        $projects = $this->model->where('id','!=',1)->get();
        $names = $this->limitName($projects->pluck('name'));
        $data = [[], []];
        $max = [0, 0];
        $dates = $this->getDates($request);
        $search_items = [
            ['created_at', '>=', $dates['start_at']],
            ['created_at', '<', $dates['end_at']]
        ];
        foreach($projects as $project) {
            $total = Order::where('project_id', $project->id)->where($search_items)->count();
            $total_money = Order::where('project_id', $project->id)->where($search_items)->sum('money') / 100;
            array_push($data[0], $total);
            array_push($data[1], $total_money);
            $max[0] = max($max[0], $total);
            $max[1] = max($max[1], $total_money);
        }
        return response()->json(['status' => 'success', 'data' => compact('data', 'names', 'max')]);
    }

    public function getDates(Request $request)
    {
        if($request->input('month')) {
            $start_at = Carbon::createFromDate($request->input('year'), $request->input('month'), 1)->toDateTimeString();
            $end_at = Carbon::createFromDate($request->input('year'), $request->input('month'), 1)->addMonth()->toDateTimeString();
        } else {
            $start_at = Carbon::createFromDate($request->input('year'), 1, 1)->toDateTimeString();
            $end_at = Carbon::createFromDate($request->input('year'), $request->input('month'), 1)->addYear()->toDateTimeString();
        }
        return compact('start_at', 'end_at');
    }
    public function exportTemplate(Request $request)
    {
        return response()->download(public_path() . '/项目导入模板.xlsx', '项目导入模板.xlsx', [
            'Content-Type: application/vnd.ms-excel'
        ]);
    }
    public function import(Request $request)
    {
        if(!$request->hasFile('file')) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $file = $request->file('file');
        try {
            Excel::import(new ProjectImport(), $file);
        } catch (ImportError $e) {
            return response()->json(['status' => 'error', 'info' => $e->getMessage()]);
        }
        return response()->json(['status' => 'success', 'info' => '上传成功']);
    }
}
