<?php

namespace App\Http\Controllers\strategy;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Tool;
use Maatwebsite\Excel\Facades\Excel;
//use App\Http\Requests\StrategySetCreateRequest;

class StrategySetController extends Controller
{
    use ValidatesRequests;
    use Tool;
    
    public function index(){
        dd('策略列表');
    }
    
    public function store(Request $request){
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:30',
            'user_sn' => 'required',
            'call_number' => 'required',
            'day_type' => 'required',
            'frequency_type' => 'required',
            'call_time_set' => 'required',
            'project_sn' => 'required',
            'upload' => 'size:'//上传文件限制不超过8M
        ]);
        
        /* if ($validator->fails()) {
            return $this->errorWithInfo('表单验证失败', 401);
        } */
        
        $excelReturn = $this->validUploadExcel($request,'upload',8388608); //限制最大上传文件8M
        if (isset($excelReturn['code']) && $excelReturn['code'] == '401'){
            return $this->errorWithInfo($excelReturn['msg'], 401);
        }
        dd($excelReturn);
        dd('策略添加');
    }
    
    
    public function validUploadExcel($request,$inputName,$maxUploadSize=''){
        $path = storage_path()."/import/";
        $path = str_replace('\\','/',$path);
        
        $extension = $request->file($inputName)->getClientOriginalExtension(); 
        if($extension != 'xlsx' && $extension != 'xls' ){
            return ['msg'=>'非xls及xlsx格式文件', 'code'=>401];
        }
        if (!empty($maxUploadSize)){//限制最大上传文件（字节）
            $size = $request->file($inputName)->getClientSize();
            if ($size > $maxUploadSize){
                return ['msg'=>'上传文件过大', 'code'=>401];
            }
        }        
        
        $fileName = date('YmdHis',time()).'.xlsx';
        
        if($request->hasFile($inputName)){
            if($request->file($inputName)->isValid()){
                $upr = $request->file($inputName)->move($path,$fileName);
                if (!$upr){
                    return ['msg'=>'文件上传失败', 'code'=>401];
                }else{
                    $res = [];         
                    Excel::load($path.'/'.$fileName,function($reader) use( &$res ){
                        $reader = $reader->getSheet(0);
                        $res = $reader->toArray();
                    });
                    $data = array_filter($res);  
                    if (count($data) > 1001){
                        return ['msg'=>'条数超过1000条', 'code'=>401];
                    }
                    return $data;
                }
            }            
        }
        return ['msg'=>'excel处理失败', 'code'=>401];
    }
}
