package com.zcloud.modules.oss.controller;

import com.google.gson.Gson;
import com.zcloud.common.exception.ZException;
import com.zcloud.common.utils.ConfigConstant;
import com.zcloud.common.utils.Constant;
import com.zcloud.common.utils.PageUtils;
import com.zcloud.common.utils.R;
import com.zcloud.common.validator.ValidatorUtils;
import com.zcloud.modules.oss.cloud.CloudStorageConfig;
import com.zcloud.modules.oss.cloud.OSSFactory;
import com.zcloud.modules.oss.entity.SysOssEntity;
import com.zcloud.modules.oss.service.SysOssService;
import com.zcloud.modules.sys.service.SysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 文件上传
 */
@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;

	/**
	 * 列表
	 */
	@PostMapping("/list")
	//@RequiresPermission("sys:oss:all")
	public R list(@RequestBody Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

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


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

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


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

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

		return R.ok();
	}


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

		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		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("url", url);
	}


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

		return R.ok();
	}

}
