<?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 App\Service\StrategyService;
use App\Models\StrategySet;
use Illuminate\Support\Facades\Log;
//use App\Http\Requests\StrategySetCreateRequest;

class StrategySetController extends Controller
{
    use ValidatesRequests;
    use Tool;
    
    public function index(){
        dd('策略列表');
    }
    
    public function store(Request $request,StrategyService $StrategyService){
        $allowLoginUser = $this->getAllowLoginUser();
        
        $validator = Validator::make($request->all(), [
            'strategy_name' => 'required|max:30',
            'user_sn' => 'required',
            'call_number' => 'required',
            'day_type' => 'required',
            'frequency_type' => 'required',
            'call_time_set' => 'required',
            'project_sn' => 'required'
        ]);
        
        if ($validator->fails()) {
            return $this->errorWithInfo('表单验证失败', 401);
        } 
        $params = $request->all();
        if ($params['frequency_type'] == 2){ //一天两次时间、项目格式验证，#号分割
            if (substr_count($params['call_time_set'], '#') != 1 || substr_count($params['project_sn'], '#') != 1){
                return $this->errorWithInfo('呼叫设置验证失败', 401);
            }
        }
        
        $successTotal = $failTotal = 0;
        $failDataFile = '';
        if (isset($params['upload'])){ //excel文件上传
            $excelData = $StrategyService->validUploadExcel($request,'upload',8388608); //限制最大上传文件8M
            if (isset($excelData['code'])){
                return $this->errorWithInfo($excelData['msg'], 401);
            }
            //验证excel数据格式及不合格数据原因
            $excelDataValid = $StrategyService->validExcelData($excelData, $params['day_type']);
            extract($excelDataValid);
            unset($params['upload']);
        }
        
        if (isset($successTotal) && $successTotal > 0){
            $params['latest_total'] = $successTotal;
            $params['total'] = $successTotal;
        }
        
        $strategySn = $this->uidd();
        $params['strategy_sn'] = $strategySn;
        $params['user_name'] = $allowLoginUser['user_name'];
        $params['parent_sn'] = $allowLoginUser['parent_sn'];
        $StrategySet = new StrategySet($params);
        $setReturn = $StrategySet->save();
        if ($setReturn){ //策略保存成功，处理excel数据
            if (isset($successTotal) && $successTotal > 0){
                $insertExcelReturn = $StrategyService->insertStrategyExcel($strategySn, $successData);                
            }
        }
        //返回成功数、失败数、失败导出文件
        $returnArr = compact('total','successTotal','failTotal','failDataFile');
        return $this->successWithInfo(['data'=>$returnArr]);
    }
    
    //项目列表
    public function getProjectsList(){
        $projectInfo = [['sn'=>'projects|a3a4259352c8e964ad6ea6c5ee8a7208','name'=>'liuy-转人工测试'],['sn'=>'projects|a3a4259352c8e964ad6ea6c5ee8a7208','name'=>'liuy-转人工测试']];
        return $this->successWithInfo(['data'=>$projectInfo]);
    }
    
    //下载模板及下载导入失败excel数据
    public function downloadModel(Request $request,StrategyService $StrategyService){        
        $excelName = "策略任务数据导入模板";
        $datas[0][0]= "姓名";
        $datas[0][1]= "*手机号码";
        $datas[0][2]= "值班日期";
        $StrategyService->storeExcelStyle($excelName, $datas,'','',1);        
    }
    
    public function downloadFailExcel(Request $request){
        $excelFile = $request->filename;
        if (empty($excelFile)){
            return $this->errorWithInfo('表单验证失败', 401);
        }
        $url = storage_path()."\\import\\".$excelFile.'.xlsx';        
        try{
            if (file_exists($url) == false){
                return $this->errorWithInfo('文件不存在，下载失败', 401);
            }
            $cont=fopen($url,'r');
            $fcontent = fread($cont,filesize($url));
            
            fclose($cont);
            //发送mp3文件MIME 头
            header('Content-Type:application/vnd.ms-excel');
            // 发送下载附件头.
            header("Content-disposition: attachment; filename=\"".$url."\"");
            header('Content-transfer-encoding: binary');
            return $fcontent;
        }catch(\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return $this->errorWithInfo('下载异常', 401);
        }
        
    }
    
    //导入excel数据
    public function importExcelData(Request $request,StrategyService $StrategyService){
        $validator = Validator::make($request->all(), [
            'strategy_sn' => 'required',
            'upload' => 'required'
        ]);
        
        if ($validator->fails()) {
            return $this->errorWithInfo('表单验证失败', 401);
        } 
        
        $strategySn = $request->strategy_sn;
        
        
        if (isset($request->upload) && !empty($request->upload)){ //excel文件上传
            $excelData = $StrategyService->validUploadExcel($request,'upload',8388608); //限制最大上传文件8M
            if (isset($excelData['code'])){
                return $this->errorWithInfo($excelData['msg'], 401);
            }
            //验证excel数据格式及不合格数据原因
            $excelDataValid = $StrategyService->validExcelData($excelData, $params['day_type']);
            extract($excelDataValid);
            unset($params['upload']);
        }else{
            return $this->errorWithInfo('请选择导入文件', 401);
        }
    }
}
