<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/9/26
 * Time: 上午11:06
 */

class uploader
{
    public function upfileOp()
    {
        $file_path = $this->file_path();
        $member_id = $_SESSION['member_id'];
        $file_name = $this->upfile($file_path,$err);
        if($file_name == false) {
            return self::outerr(errcode::ErrUploadFileFailed);
        }
        $file_path = DS.$member_id.DS.$file_name;
        $ret = Model("member")->editMember(array('member_id' => $member_id),array('member_avatar' => $file_path));
        if ($ret) {
            $_SESSION['member_avatar'] = $file_path;
            $url = UPLOAD_SITE_URL . "/shop/avatar{$file_path}";
            return self::outsuccess(array('member_avatar' => $url));
        } else {
            return self::outerr(errcode::ErrDB);
        }
    }

    private function upfile($img,&$err)
    {
        $member_id = $_SESSION['member_id'];

        $upload = new FileUploader();
        if($upload->init_files($img,$member_id,$err) == false) {
            return false;
        }

        $upload_dir = ATTACH_AVATAR.DS.$member_id.DS;
        $upload->set('default_dir',$upload_dir.$upload->getSysSetPath());
        $thumb_width	= '480,1024';
        $thumb_height	= '480,1024';

        $upload->set('max_size',C('image_max_filesize'));
        $upload->set('thumb_width', $thumb_width);
        $upload->set('thumb_height',$thumb_height);
        $upload->set('fprefix',$member_id);
        $upload->set('thumb_ext', '_240,_1024');
        $result = $upload->upfile('file');
        if($result == true) {
            return $upload->file_name;
        } else {
            $err = array('code' => errcode::ErrUpfile, 'msg' => $upload->error);
            return false;
        }
    }

    private function file_path()
    {
        $file_path = $_POST["file_path"];
        if(file_exists($file_path) == false) {
            $file_path = BASE_ROOT_PATH . '/data/upload/upfile' . $file_path;
        }
        return $file_path;
    }
}