<?php
namespace App\Service;

use Maatwebsite\Excel\Facades\Excel;

class StrategyService
{
    //验证上传的excel
    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];
                        }
                        //验证excel表头格式
                        $title = array_shift($data);
                        if ($title != ['姓名','*手机号码','值班日期']){//匹配excel表头
                            return ['msg'=>'导入失败，excel表头不一致', 'code'=>401];
                        }                        
                        return $data;
                }
            }
        }
        return ['msg'=>'excel处理失败', 'code'=>401];
    }
    //判断excel数据问题,$day_type//外呼日期类型 0每天 1日期前一天和当天   1需要验证值班日期必填
    public function validExcelData($data,$day_type){
        $failData = [['姓名','*手机号码','值班日期','失败原因']];
        foreach ($data as $k=>$v){
            if (strlen($v[0]) > 20){ //姓名最大20个字符，中文处理，放入失败数据中
                $failData[] = array_push($v, "姓名过长");                
            }
            if ($v[1]){//手机号格式验证，不能为空
                $failData[] = array_push($v, "手机号格式不正确");   
            }
            if ($day_type == 1){//验证必填且为日期格式
                /* if (empty($v[2])){
                    $failData[] = array_push($v, "值班日期必填"); 
                }elseif (){
                    $failData[] = array_push($v, "值班日期格式错误");
                } */
            }
        }
        
    }
}

