/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.oss.controller;

import com.google.gson.Gson;
import io.renren.common.exception.RRException;
import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.Constant;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.oss.service.SysOssService;
import io.renren.modules.sys.constant.Const;
import io.renren.modules.sys.service.SysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Arrays;

/**
 * 文件上传
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public static String list(@RequestParam("filePath") String filePath, ServletResponse response ){
		byte[] buf = null;
		try {
			FileInputStream fileStream = new FileInputStream(Const.FILE_PATH + filePath);
			buf = new byte[(int) fileStream.available()];
			fileStream.read(buf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        BASE64Encoder encoder = new BASE64Encoder();
        String images = "data:image/jpeg;base64," + encoder.encode(buf);
        return images;
	}

    /**
     * 获取附件信息
     */
    @GetMapping("/file")
    @RequiresPermissions("sys:oss:all")
    public static String file(@RequestParam("filePath") String filePath, ServletResponse response ){
        String url = Const.FILE_PATH + filePath;
        /*try {
            FileInputStream fileStream = new FileInputStream(Const.FILE_PATH + filePath);
            url = String.valueOf(fileStream.available());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return url;
    }


    /**
     * 云存储配置信息
     */
    @GetMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


	/**
	 * 保存云存储配置信息
	 */
	@PostMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);
		ValidatorUtils.validateEntity(config, Constant.CloudService.getByValue(config.getType()));

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}
	

	/**
	 * 上传文件
	 */
	@PostMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file,
					@RequestParam("categoryType") String type) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		String filePath = Const.FILE_PATH+type;
		File directory = new File(filePath);
		if(!directory.exists()){
			directory.mkdirs();
		}

		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

		String fileName = DigestUtils.md5DigestAsHex(file.getBytes());
		String imgPath = "/"+fileName+suffix;
		File imgFile =  new File(filePath + imgPath);
		if(!imgFile.exists()){
			imgFile.createNewFile();
		}
		FileOutputStream outStream = null;
		try {
			outStream = new FileOutputStream(imgFile);
			outStream.write(file.getBytes());
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			if(outStream !=null){
				outStream.close();
			}
		}

//		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
//
//		//保存文件信息
//		SysOssEntity ossEntity = new SysOssEntity();
//		ossEntity.setUrl(url);
//		ossEntity.setCreateDate(new Date());
//		sysOssService.save(ossEntity);

		return R.ok().put("data", type+imgPath);
	}


	/**
	 * 删除
	 */
	@PostMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

}
