<?php
namespace app\modules\logic\services;
use app\modules\common\Helper;
use yii\web\UploadedFile;
use Yii;
use yii\db\Query;
/**
 * 公用上传服务费
 */
class UploadService {
	
	private $para;

	private $model_name = ['tech', 'shop'];

	protected function response($code, $msg = '', $info = '',$controller = 'middle')
    {
        $error_arr = Yii::$app->params['returnInfo'];
        $result = '';
        if (!isset($error_arr[$controller]) or !isset($error_arr[$controller][$code])) {
            if (isset($error_arr['middle'][$code])) {
                $result = $error_arr['middle'][$code];
            } elseif (isset($error_arr['default_error'][$code])) {
                $result = $error_arr['default_error'][$code];
            } else {
                $result = $error_arr['default_error']['not_find_error'];
            }
        } else {
            $result = $error_arr[$controller][$code];
        }
        $result['info'] = $info;
        if (!empty($msg)) {
            $result['msg'] = $msg;
        }
        return $result;
    }

    /**
     * 文件类型检测
     */
    private  function checkType($type)
    {
        $allowFiles = array("png", "jpg", "jpeg");//允许的图片上传
        if (in_array($type, $allowFiles)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 文件大小检测
     * @return bool
     */
    private function checkSize($size)
    {
        $maxSize = 20480000;//限制图片大小 ，单位B
        return $size <= $maxSize;
    }

    /**
     * 文件类型检测
     */
    private function checkUpType($type)
    {
        $allowFiles = array("image/png", "image/jpg", "image/jpeg", "image/gif");//允许的图片上传
        if (in_array($type, $allowFiles)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * APP上传图片
     */
    public function sendUpimg($param)
    {
    	$this->para = $param;
        if (!isset($this->para['filename']) || empty($this->para['filename'])) {
            return $this->response('para_error', '未指定文件上传控件名称');
        }
        if (!isset($this->para['modelname']) || empty($this->para['modelname']) || !in_array($this->para['modelname'], $this->model_name)) {
            return $this->response('para_error', '未指定模组名称');
        }

        $modelname = $this->para['modelname'];
        $product_pic_file = UploadedFile::getInstanceByName($this->para['filename']);
        if (empty($product_pic_file)) {
            return $this->response('para_error', '图片未上传');
        }

        //检查文件大小是否超出限制
        if (!$this->checkSize($product_pic_file->size)) {
            return $this->response('image_error', '图片超出限制');
        }
        if (!$this->checkUpType($product_pic_file->type)) {
            return $this->response('image_error', '图片格式不正确');
        }
        $dirname = '/uploads/app/images/' . date("Ym");
        
        if (!file_exists(UPLOAD_PATH . $dirname) && !mkdir(UPLOAD_PATH . $dirname, 0777, true)) {
            return $this->response('server_error', '图片保存目录无法创建');
        } elseif (!is_writeable(UPLOAD_PATH . $dirname)) {
            return $this->response('server_error', '图片保存文件夹无写入权限');
        }
        //保存文件，重命名
        $sava_path = $dirname . '/' . $modelname . '_' . date("Ymd") . '_' . uniqid() . '.' . $product_pic_file->extension;
        if (!$product_pic_file->saveAs(UPLOAD_PATH . $sava_path)) {
            return $this->response('server_error', '图片失败');
        }

        $arr_insert = array(
            "model" => $modelname,
            "path" => $sava_path,
            "terminal_type" => $this->para['terminalType'],
            "addtime" => time(),
            "addip" => Yii::$app->request->getUserIP()
        );

        $conn = Yii::$app->db;
        $conn->createCommand()->insert('{{%upload_file}}', $arr_insert)->execute();
        $last_id = $conn->getLastInsertID();
        if ($last_id > 0) {
            return $this->response('deal_succ', '图片上传成功', $last_id);
        } else {
            return $this->response('server_error', '上传失败');
        }
    }

    /**
     *多 图片上传
     */
    public function sendUpimgs($param)
    {
    	$this->para = $param;
        if (!isset($this->para['filename']) || empty($this->para['filename'])) {
            return $this->response('para_error', '未指定文件上传控件名称');
        }
        if (!isset($this->para['modelname']) || empty($this->para['modelname'])) {
            return $this->response('para_error', '未指定模组名称');
        }

        $modelname = $this->para['modelname'];
        $product_pic_file = UploadedFile::getInstancesByName($this->para['filename']);
        if (empty($product_pic_file) || !is_array($product_pic_file)) {
            return $this->response('para_error', '图片未上传');
        }

        $dirname = '/uploads/images/app/' . date("Ym");

        //创建目录失败
        if (!file_exists(UPLOAD_PATH . $dirname) && !mkdir(UPLOAD_PATH . $dirname, 0777, true)) {
            return $this->response('image_error', '图片保存目录无法创建');
        } elseif (!is_writeable(UPLOAD_PATH . $dirname)) {
            return $this->response('image_error', '图片保存文件夹无写入权限');
        }

        $last_id_str = '';
        foreach ($product_pic_file as $k => $value) {
            //检查文件大小是否超出限制
            if (!$this->checkSize($value->size)) {
                return $this->response('image_error', '图片超出限制');
            }
            if (!$this->checkUpType($value->type)) {
                return $this->response('image_error', '图片格式不正确');
            }
            //保存文件，重命名
            $sava_path = $dirname . '/' . $modelname . '_' . date("Ymd") . '_' . uniqid() . '.' . $value->extension;


            $re = $value->saveAs(UPLOAD_PATH . $sava_path);


            $arr_insert = array(
                "model" => $modelname,
                "path" => $sava_path,
                "terminal_type" => $this->para['terminalType'],
                "addtime" => time(),
                "addip" => Yii::$app->request->getUserIP()
            );

            $conn = Yii::$app->db;
            $conn->createCommand()->insert('{{%upload_file}}', $arr_insert)->execute();
            $last_id = $conn->getLastInsertID();
            $last_id_str .= $last_id . ',';
        }
        $last_id_str = substr($last_id_str, 0, -1);


        if (!empty($last_id_str)) {
            return $this->response('deal_succ', '图片上传成功', $last_id_str);
        } else {
            return $this->response('server_error', '上传失败');
        }
    }

}