<?php
namespace App\Service;

use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;
use App\models\StrategyExcel;

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($successData,$day_type){
        $failData = [];
        foreach ($successData as $k=>$v){
            $dataLab = 1;
            if (strlen($v[0]) > 20){ //姓名最大20个字符，中文处理，放入失败数据中
                array_push($v, "姓名过长");  
                $failData[] = $v;
                $dataLab = 0;
            }
            if ($dataLab == 1 && !preg_match('/^1[3-8]{1}[0-9]{9}$/', $v[1])){//手机号格式验证（手机号码验证以13、14、15、16、17、18开头的11位数字），不能为空
                array_push($v, "手机号格式不正确"); 
                $failData[] = $v;
                $dataLab = 0;
            }
            if ($dataLab == 1 && $day_type == 1){//验证必填且为日期格式
                if (empty($v[2])){
                    array_push($v, "值班日期必填"); 
                    $failData[] = $v;
                    $dataLab = 0;
                }else{
                    $unixTime = strtotime($v[2]);
                    if (!$unixTime || (date('Y/n/j', $unixTime) != $v[2] && date('n/j/Y', $unixTime) != $v[2])) { //月日不带0（2020/5/3或者 5/3/2020）
                        array_push($v, "值班日期格式错误");
                        $failData[] = $v;
                        $dataLab = 0;
                    }else{
                        $v[2] = date('Y-m-d',$unixTime); //处理存储db的日期格式（2020-05-13）
                        $successData[$k] = $v;
                    }
                    
                }
            }
            if ($dataLab == 0){
                unset($successData[$k]);
            }
        }
        
        $failTotal = count($failData);
        $successTotal = count($successData);
        $failDataFile = '';
        if ($failTotal > 0){//把导出错误数据存入excel表格中供下载
            $failDataTitle = ['姓名','*手机号码','值班日期','失败原因'];
            array_unshift($failData, $failDataTitle);
            $failExcelName = "导入失败数据_".date('YmdHis');
            //dump($failExcelName);
            $failFile = $this->storeExcelStyle($failExcelName, $failData,'','import');
            
            if ($failFile){
                $failDataFile = storage_path('export').'\\'.$failExcelName.'.xlsx';
            }else{ //失败数据写入失败
                Log::channel('api')->error('错误文件excel写入失败');
            }
        }
        return compact('successData','failData','failTotal','successTotal','failDataFile');
    }
    
    
    
    //保存内容到excel文件并下载
    public function storeExcelStyle($excelName,$datas,$endLen='',$path=''){
        try{
            $arr = range('A','Z');
            if (!empty($endLen)){
                $endLen = $endLen - 1;
                if(isset($arr[$endLen])){
                    $arr = range('A',$arr[$endLen]);
                }
            }
            
            $e = Excel::create(iconv('UTF-8', 'GBK', $excelName),function($excel) use ($datas,$arr){
                $excel->sheet('score', function($sheet) use ($datas,$arr){
                    $col =array();
                    $sheet->rows($datas);
                    foreach($arr as $v){
                        $col[$v]=12;
                    }
                    $sheet->setWidth($col);                    
                    foreach ($arr as $k=> $v){
                        $objRichText = new \PHPExcel_RichText();
                        if(!empty($datas[0][$k])){
                            if (strpos($datas[0][$k], '*') === 0){
                                $objPayable = $objRichText->createTextRun('*');
                                $objPayable->getFont()->setColor( new \PHPExcel_Style_Color( \PHPExcel_Style_Color::COLOR_RED ) );//设置颜色
                            }
                            $objRichText->createText(ltrim($datas[0][$k],'*'));
                            $sheet->setCellValue($arr[$k].'1',$objRichText);
                        }
                        
                    }
                    
                });
            });
            
            if (empty($path)){//默认路径storage/exports
                $e->store('xlsx');
            }else{//自定义路径 storage/$path
                $e->store('xlsx', storage_path($path));
            }
            return true;
        }catch(\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return false;
        }
    }
    
    //添加策略处理excel数据入库
    public function insertStrategyExcel($strategySn,$data){
        if (count($data) > 0){
            $insertData = [];
            $now = date('Y-m-d H:i:s');
            foreach ($data as $k=>$v){
                $insertTemp = [];
                $insertTemp['strategy_sn'] = $strategySn;
                $insertTemp['name'] = $v[0] == null ? '' : $v[0];
                $insertTemp['phone'] = (int)$v[1];
                $insertTemp['duty_date'] = $v[2] == null ? '' : $v[2];
                $insertTemp['created_at'] = $now;
                $insertTemp['updated_at'] = $now;
                $insertData[] = $insertTemp;
            }
            //dd($insertData);
            return StrategyExcel::insert($insertData);             
        }
    }
    
    
    
}

