<?php
/**
 *  人数统计
 *  @author  system
 *  @version    1.0
 *  @date 2018-06-06 01:48:31
 *
 */
namespace App\Http\Controllers\Admin\Student;
use App\Http\Controllers\Admin\Controller;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Student\Criteria\MultiWhere;
use App\Repositories\Student\CountRepository;
use Maatwebsite\Excel\Facades\Excel;

class CountController extends Controller
{
    private $repository;

    public function __construct(CountRepository $repository) {
        if(!$this->repository) $this->repository = $repository;
    }

    function index(Request $request) {
        $search['keyword'] = $request->input('keyword');
        $query = $this->repository->pushCriteria(new MultiWhere($search));

        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
        $query = $query->pushCriteria(new OrderBy($request['sort_field'],$request['sort_field_by']));
        }else{
            $query = $query->pushCriteria(new OrderBy('total','asc'));
        }
        $list = $query->paginate(10);
        return view('admin.student.count.index',compact('list'));
    }


    function check(Request $request) {
        $request = $request->all();
        $search['keyword'] = $request->input('keyword');
        $orderby = array();
        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $orderby[$request['sort_field']] = $request['sort_field_by'];
        }
        $list = $this->repository->search($search,$orderby);
        return view('admin.student.count.check',compact('list'));
    }


    /**
     * 添加
     * 
     */
    public function create(Request $request)
    {
        if($request->method() == 'POST') {
            return $this->_createSave();
        }
        return view('admin.student.count.edit');
    }

    /**
     * 保存修改
     */
    private function _createSave(){
        $data = (array) request('data');
        $id = $this->repository->create($data);
        if($id) {
            $url[] = array('url'=>U( 'Student/Count/index'),'title'=>'返回列表');
            $url[] = array('url'=>U( 'Student/Count/create'),'title'=>'继续添加');
            $this->showMessage('添加成功',$url);
        }else{
            $url[] = array('url'=>U( 'Student/Count/index'),'title'=>'返回列表');
            return $this->showWarning('添加失败',$url);
        }
    }
    
    /**
     * 
     * 修改
     * 
     * 
     */
    public function update(Request $request) {
        if($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $data = $this->repository->find($request->get('id'));
        return view('admin.student.count.edit',compact('data'));
    }

    /**
     * 保存修改
     */
    private function _updateSave() {
        $data = (array) request('data');
        $ok = $this->repository->update(request('id'),$data);
        if($ok) {
            $url[] = array('url'=>U( 'Student/Count/index'),'title'=>'返回列表');
            return $this->showMessage('操作成功',urldecode(request('_referer')));
        }else{
            $url[] = array('url'=>U( 'Student/Count/index'),'title'=>'返回列表');
            return $this->showWarning('操作失败',$url);
        }
    }

    public function view(Request $request) {
        $data = $this->repository->find(request('id'));
        return view('admin.student.count.view',compact('data'));
    }


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request) {
        $ok = $this->repository->updateStatus(request('id'),request('status'));
        if($ok) {
            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }
    
    /**
     * 删除
     */
    public function destroy(Request $request) {
        $bool = $this->repository->destroy($request->get('id'));
        if($bool) {
            return  $this->showMessage('操作成功');
        }else{
            return  $this->showWarning("操作失败");
        }
    }

    /***
     * 导入excel表格
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function import(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('kid_import');
        } else {
            $tmp_file = $_FILES['test'] ['name'];
            $file_types = explode(".", $tmp_file);
            $file_type = $file_types [count($file_types) - 1];
            if (strtolower($file_type) == "xls" || strtolower($file_type) == "xlsx") {
                $file = $request->file('test');
                $path = 'upload/excel_import';
                $filename = $tmp_file;
                $file->move($path, $filename);
                $filePath = $path . '/' . $filename;
                Excel::load($filePath, function ($reader) {
                    $data = $reader->toArray();
                    $a = [];
                    if (empty($data)) {
                        die('<script>alert("信息填写不完整,请检查后导入数据");history.back();</script>');
                    } else {
                        foreach ($data as $k1 => $v1) {

                            foreach ($v1 as $k2 => $v2) {
                                $a[$k1]['year'] = $v2['年份']?$v2['年份']:'';
                                $a[$k1]['class'] = $v2['科类']?$v2['科类']:'';
                                $a[$k1]['grade'] = $v2['分数']?$v2['分数']:'';
                                $a[$k1]['sum'] = $v2['人数']?$v2['人数']:'';
                                $a[$k1]['total'] = $v2['累计']?$v2['累计']:'';


                                $a[$k1]['created_at'] = date('Y-m-d H:i:s', time());
                                $a[$k1]['updated_at'] = date('Y-m-d H:i:s', time());

                                $res = $this->repository->create($a[$k1]);
                            }

                        }
                    }

                    if (!$res) {
                        die('<script>alert("导入人数统计信息失败");history.back();</script>');
                    }
                });
//                读取.xls文件后删除文件
                unlink($filePath);
                return back()->with('success', '导入人数统计信息成功');
            } else {
                return back()->with('error', '不是Excel .xls或者.xlsx文件，请重新上传');
            }
        }
    }
}