/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.bdty.modules.oss.controller;

import cn.hutool.core.io.file.FileNameUtil;
import io.bdty.common.annotation.LogOperation;
import io.bdty.common.constant.Constant;
import io.bdty.common.exception.ErrorCode;
import io.bdty.common.page.PageData;
import io.bdty.common.utils.JsonUtils;
import io.bdty.common.utils.Result;
import io.bdty.common.validator.ValidatorUtils;
import io.bdty.common.validator.group.AliyunGroup;
import io.bdty.common.validator.group.QcloudGroup;
import io.bdty.common.validator.group.QiniuGroup;
import io.bdty.modules.oss.cloud.CloudStorageConfig;
import io.bdty.modules.oss.cloud.OSSFactory;
import io.bdty.modules.oss.entity.SysOssEntity;
import io.bdty.modules.oss.service.SysOssService;
import io.bdty.modules.sys.service.SysParamsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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

    @Value("${file.uploadFolder}")
    public String uploadFolder;
    
    @Value("${file.staticAccessPath}")
    public String staticAccessPath;

    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

    @GetMapping("page")
    @ApiOperation(value = "分页")
    @RequiresPermissions("sys:oss:all")
    public Result<PageData<SysOssEntity>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysOssEntity> page = sysOssService.page(params);

        return new Result<PageData<SysOssEntity>>().ok(page);
    }

    @GetMapping("info")
    @ApiOperation(value = "云存储配置信息")
    @RequiresPermissions("sys:oss:all")
    public Result<CloudStorageConfig> info() {
        CloudStorageConfig config = sysParamsService.getValueObject(KEY, CloudStorageConfig.class);

        return new Result<CloudStorageConfig>().ok(config);
    }

    @PostMapping
    @ApiOperation(value = "保存云存储配置信息")
    @LogOperation("保存云存储配置信息")
    @RequiresPermissions("sys:oss:all")
    public Result saveConfig(@RequestBody CloudStorageConfig config) {
        //校验类型
        ValidatorUtils.validateEntity(config);

        if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }

        sysParamsService.updateValueByCode(KEY, JsonUtils.toJsonString(config));

        return new Result();
    }

    @PostMapping("upload")
    @ApiOperation(value = "上传文件")
    @RequiresPermissions("sys:oss:all")
    public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, Object>>().error(ErrorCode.UPLOAD_FILE_EMPTY);
        }

        String fileName=file.getOriginalFilename();// 文件原名称
        String url = "";
		// 判断文件类型
		String fileType=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
		if (fileType!=null) {
			String trueFileName=String.valueOf(System.currentTimeMillis())+"."+fileType;

			File outFile = new File(uploadFolder+ "/"+trueFileName);
			if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
			// 创建父文件夹
				outFile.getParentFile().mkdirs();
			}
			try {
				file.transferTo(outFile); //保存到服务器本地
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			} catch (IOException e) {
				System.out.println("上传文件出错:"+e.getMessage());
				throw e;
			}
			
			url = request.getScheme() +"://" + request.getServerName() + ":" +request.getServerPort()+request.getContextPath()+staticAccessPath.replace("**", "")+trueFileName;

		}
 

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.insert(ossEntity);

        Map<String, Object> data = new HashMap<>(1);
        data.put("src", url);

        return new Result<Map<String, Object>>().ok(data);
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:oss:all")
    public Result delete(@RequestBody Long[] ids) {
        sysOssService.deleteBatchIds(Arrays.asList(ids));

        return new Result();
    }

}