<?php

namespace App\Model;

use App\Jobs\UploadChangePrice;
use Illuminate\Database\Eloquent\Model;
use RedisDB;
use Request;
use App\map\UploadLogMap;
use Illuminate\Support\Facades\Storage;
use DB;

class UploadLogModel extends Model
{
    protected $connection='yunxin';
    protected $table='upload_log';
    protected $primaryKey='id';
    public $timestamps = false;

    public function getList($type,$create_uid){

        $collert=Request::only('p','limit','type');
        $collert=TrimX($collert,true,['p','limit','type']);
        $limit=!empty($collert['limit'])?$collert['limit']:10;
        $p=!empty($collert['p'])?$collert['p']:1;

        //查数据
        $UploadLogType = UploadLogMap::$type;
        $UploadLogStatus = UploadLogMap::$status;
        $list=$this->whereIn('type',$type)->where("create_uid",$create_uid)->orderBy('id','desc')->paginate($limit,['*'],'p',$p)->toArray();
        foreach ($list['data'] as $key => &$v) {
            $v['create_time'] =timeToDate($v['create_time']);
            $v['status'] = @$UploadLogStatus[$v['status']];
            $v['type'] = @$UploadLogType[$v['type']];
        }
        return [0,'成功',$list['data'],$list['total']];
    }

    public function LogInfo($id){
        if(empty($id)) return false;
        $info=$this->where('id',$id)->first();
        $info && $info=$info->toArray();
        return $info;
    }
    public function UpdateLog($up_id,$data){
        if(empty($up_id)) return false;
        if(empty($data)) return false;
        $result=$this->where('up_id','=',$up_id)->update($data); //debug
        if(!$result) return false;
        return true;
    }
    //插入任务
    public function addLog($create_uid,$type,$remark)
    {
        return $this->insertGetId(['create_uid'=>$create_uid,'type'=>$type,'extend'=>$_SERVER['HTTP_HOST'],'create_time'=>time(),'remark'=>json_encode($remark, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);
    }
    public function UpdateLogArr($id,$info,$status='',$Log,$data=[]){
        if(empty($id)) return false;
        $data['update_time'] = time();
        $Log[] = date('Y-m-d H:i',$data['update_time']).$info;
        $data['log'] = json_encode($Log, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        empty($status) || $data['status']=$status;
        $result=$this->where('id','=',$id)->update($data); //debug
        if(!$result) return false;
        return true;
    }
    //生成的文件上传到OSS
    public function SaveDownFile($FileName=''){
        if(empty($FileName)) return false;
        $result=json_decode(UploadToOss(storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$FileName),true);
        if(empty($result['code']) || $result['code'] != 200 || empty($result['data'][0])) return false;
        return $result['data'][0];
    }
    //上传文件
    public function uploadFile($create_name = ''){
        $file = Request::file('file');
        if ($file->isValid()) {
            $ext = $file->getClientOriginalExtension();
            $realPath = $file->getRealPath();
            if($ext!='csv'){
                $this->Export(10001,'上传格式错误');
            }
            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用新建的uploads本地存储空间(目录)
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            if(!$bool) return [10002,'文件处理失败'];
            $filePath = storage_path().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$filename;
            $result=json_decode(UploadToOss($filePath),true);
            Storage::disk('uploads')->delete($filename);

            if(!empty($result['code']) && $result['code']==200 && !empty($result['data'][0])){
                $data['file_path']= $result['data'][0];
                $data['log']=json_encode([
                    date('Y-m-d H:i',time()). '建立任务'
                ]);
                $data['create_time'] = $data['update_time']  =time();
                $data['create_name'] = $create_name;
                $data['type']=1;
                DB::connection($this->connection)->beginTransaction();
                $insert=$this->insertGetId($data);

                if($insert){
                    $return=dispatch(new UploadChangePrice($insert));
                    if($return){
                        DB::connection($this->connection)->commit();
                        return [0,'上传成功,请等待系统自动处理'];
                    }else{
                        return [10004,'上传失败'];
                    }
                }else{
                    return [10003,'上传失败'];
                }
            }else{
                return [10002,'上传失败'];
            }
        }else{
            return [10005,'上传失败'];
        }
    }


}