<?php

namespace App\Http\Controllers\Manage\Cp;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Cp\Transformers\CpSubTransformer;
use App\Modules\Cp\Models\CpSub;
use Illuminate\Http\Request;
use DB;
use Excel;

class CpSubController extends Controller
{
	public $msg;
	
	public function sub_import_view(){
		\Log::info('sub_import_view');
		$msg = '';
		return view('manage.web.cp.sub_import',compact('msg'));
	}
    
    /**
     * 书籍数据导入
     */
    public function subs_import(Request $request)
    {
    	ini_set('memory_limit', '1024M');
    	$condition = $request->all();
    	 
    	$msg = '';
    	 
        if($request->file('file')){
        	Excel::load($request->file('file'), function($reader) {
		        //获取excel的第几张表
			    $reader = $reader->getSheet(0);
			    //获取表中的数据
			    $results = $reader->toArray();
			    die($results);
			    $import_subs = array();
			    foreach($results as $result){
			    	$import_sub = array();
			    	$import_sub['cp_user_id'] = $result[0];
			    	$import_sub['month'] = $result[1];
			    	$import_sub['bid'] = $result[2];
			    	$import_sub['num'] = $result[3];
			    	$import_sub['book_name'] = mysql_escape_string($result[4]);
			    	$import_subs[] = $import_sub;
			    }
			    $this->import_subs($import_subs,false);
		    });
	    
        }
        else{
        	\Log::info('subs_import_null');
        }
        
        return response()->success($this->msg);

    }
    
    function import_subs($subs,$need_first_one=false){
    	$datas = array();
    	foreach($subs as $key=>$sub){
    		if($key > 0 || $need_first_one){
    			$sub = trim($sub);
    			if(isset($sub['cp_user_id']) && !empty($sub['cp_user_id'])){
    				$origin_data = DB::table('cp_subs')->where(['cp_user_id'=>$sub['cp_user_id'],'month'=>$sub['month'],'bid'=>$sub['bid']])->first();
    				if(empty($origin_data)){
    					$data = array();
    					$data['cp_user_id'] = $sub['cp_user_id'];
    					$data['month'] = $sub['month'];
    					$data['bid'] = $sub['bid'];
    					$data['num'] = $sub['num'];
    					$data['book_name'] = mysql_escape_string($sub['book_name']);
    					$data['created_at'] = date('Y-m-d H:i:s');
    					$data['updated_at'] = date('Y-m-d H:i:s');
    					$datas[] = $data;
    				}else{
    					\Log::info('subs_import_exist_cu_user_id:'.$sub['cp_user_id'].' month:'.$sub['month'].' bid:'.$sub['bid']);
    					$this->msg .= $sub.' 已存在<br>';
    				}
    	
    			}else{
    				\Log::info('subs_import_error_cu_user_id:'.$sub['cp_user_id'].' month:'.$sub['month'].' bid:'.$sub['bid']);
    				$this->msg .= empty($sub)?'':$sub.' 格式有问题<br>';
    			}
    		}
    	}
    	
    	if(!empty($datas)){
    		CpSub::insert($datas);
    	}
    	//			    v('last_data');
    	//			    v($datas);
    	$this->msg = empty($this->msg)?'导入成功':$this->msg.',剩下导入成功';
    	//			    v('$msg');v($this->msg);
    }
}
