<?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\Models\StrategyExcel;
use App\Models\StrategyTask;
use Illuminate\Support\Facades\DB;
//use App\Http\Requests\StrategySetCreateRequest;

class StrategySetController extends Controller
{
    use ValidatesRequests;
    use Tool;
    
    public function index(){
        try{
            $projectArr = $this->getAllowProjects(1);
            $strategyInfo = StrategySet::all()->toArray();
            $listInfo = [];
            foreach ($strategyInfo as $k=>$v){
                $projectSnTemp = explode("#", $v['project_sn']);
                $v['project_name'] = isset($projectArr[$projectSnTemp[0]]) ? $projectArr[$projectSnTemp[0]] : '';
                if (isset($projectSnTemp[1]) && isset($projectArr[$projectSnTemp[1]])){
                    $v['project_name'] .= $projectArr[$projectSnTemp[1]];
                }
                $v['disabled_name'] = $v['disabled'] == 0 ? '启用' : '停用';
                $v['day_type_name'] = $v['day_type'] == 0 ? '每天' : '日期前一天和当天';
                $v['frequency_type_name'] = $v['frequency_type'] == 1 ? '一天一次' : '一天两次';
                $listInfo[] = $v;
            }
            return $this->successWithInfo($listInfo);
        }catch (\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return $this->errorWithInfo('操作异常', 500);
        } 
    }
    
    public function store(Request $request,StrategyService $StrategyService){
        try{            
            $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['day_type'] == 0){ //每天、一天两次，两个时间点、一个话术或者两个话术
                $checkCallTimeSet = explode("#", $params['call_time_set']);
                if (!isset($checkCallTimeSet[1]) || empty($checkCallTimeSet[1])){
                    return $this->errorWithInfo('呼叫设置验证失败', 401);
                }
            }else{//日期前一天和当天、一天一次， 一个时间点两个话术
                $checkProjectSn = explode("#", $params['project_sn']);
                if (!isset($checkProjectSn[1]) || empty($checkProjectSn[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;
            }
            
            $allowLoginUser = $this->getAllowLoginUser($request->user_sn);
            
            $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($returnArr);
        }catch (\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return $this->errorWithInfo('操作异常', 500);
        } 
    }
    //删除策略
    public function destroy($strategySn){
        try{
            DB::transaction(function () use ($strategySn) {
                // 删除逻辑  注意多表关联的情况
                StrategySet::where('strategy_sn', $strategySn)->delete();
                StrategyExcel::where('strategy_sn', $strategySn)->delete();
                //StrategyTask::where('strategy_sn', $strategySn)->delete();
                StrategyTask::where([['strategy_sn', $strategySn],['is_created',0]])->delete(); //删除未新建的任务数据
            });
            return $this->successWithInfo('操作完成');
        }catch (\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return $this->errorWithInfo('操作异常', 500);
        } 
    }
    //子账号列表
    public function getUsersList(Request $request){        
        $usersInfo = $this->getAllowLoginUser($request->user_sn);
        return $this->successWithInfo($usersInfo);
    }
    //项目列表
    public function getProjectsList(){
        $projectInfo = $this->getAllowProjects(0);
        return $this->successWithInfo($projectInfo);
    }
    //主叫号码列表
    public function getCallNumberList(){
        $callNumbnerInfo = $this->getAllowCallNumber();
        return $this->successWithInfo($callNumbnerInfo);
    }
    
    //下载模板及下载导入失败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('下载异常', 500);
        }
        
    }
    
    //导入excel数据
    public function importExcelData(Request $request,StrategyService $StrategyService){
        try{
            $validator = Validator::make($request->all(), [
                'strategy_sn' => 'required',
                'upload' => 'required'
            ]);
            
            if ($validator->fails()) {
                return $this->errorWithInfo('表单验证失败', 401);
            } 
            
            $strategySn = $request->strategy_sn;
            $strategyInfo = StrategySet::where('strategy_sn',$strategySn)->first();
            if (empty($strategyInfo)){
                return $this->errorWithInfo('策略不存在', 401);
            }
            $day_type = $strategyInfo->day_type;
            if (isset($request->upload) && !empty($request->upload)){ //excel文件上传
                $total = $successTotal = $failTotal = 0;
                $failDataFile = '';
                $excelData = $StrategyService->validUploadExcel($request,'upload',8388608); //限制最大上传文件8M
                if (isset($excelData['code'])){
                    return $this->errorWithInfo($excelData['msg'], 401);
                }
                //验证excel数据格式及不合格数据原因
                $excelDataValid = $StrategyService->validExcelData($excelData, $day_type);
                extract($excelDataValid);
                
                if (isset($successTotal) && $successTotal > 0){
                    $insertExcelReturn = $StrategyService->insertStrategyExcel($strategySn, $successData);
                    //添加最新导入数及总数
                    $updateArr['latest_total'] = $successTotal;
                    $updateArr['total'] = $strategyInfo->total + $successTotal;
                    StrategySet::where('strategy_sn',$strategySn)->update($updateArr);
                }
                
                //返回成功数、失败数、失败导出文件
                $returnArr = compact('total','successTotal','failTotal','failDataFile');
                return $this->successWithInfo($returnArr);
            }else{
                return $this->errorWithInfo('请选择导入文件', 401);
            }
        }catch (\Exception $e){
            Log::channel('api')->error($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return $this->errorWithInfo('操作异常', 500);
        } 
    }
}
