package com.xhpc.file.controller;

import com.aliyun.oss.OSSClient;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.DateUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.utils.file.FileUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.file.domain.XhpcImg;
import com.xhpc.file.service.ISysFileService;
import com.xhpc.file.service.IXhpcImgService;
import com.xhpc.system.api.domain.SysFile;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private Environment environment;

    @Autowired
    private IXhpcImgService iXhpcImgService;



    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 阿里云图片上传
     * @author
     * @date 2021-09-01 17:15
     */
    @PostMapping("photoupload")
    @ApiOperation(value = "上传", notes = "上传")
    public AjaxResult myphotoupload(HttpServletRequest request) {
        String fileNames = "";
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                fileNames = file.getOriginalFilename();
                fileNames = DateUtils.timePath() + fileNames;
                InputStream input = file.getInputStream();
                // 创建OSSClient实例
                OSSClient ossClient = new OSSClient(environment.getProperty("oss.endpoint"), environment.getProperty("oss.access-key"), environment.getProperty("oss.secret-key"));
                // 上传文件流
                ossClient.putObject(environment.getProperty("oss.bucket-name"), fileNames, input);
                ossClient.shutdown();
            }
            XhpcImg xhpcImg = new XhpcImg();
            xhpcImg.setUrl(fileNames);
            iXhpcImgService.insert(xhpcImg);
            Map<String, Object> map = new HashMap<>(16);
            map.put("imgId", StringUtils.valueOf(xhpcImg.getImgId()));
            map.put("url", "https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/" + fileNames);
            return AjaxResult.success(map);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    /*
     * TODO 阿里云图片删除
     * @author fjd
     * @date 2020-07-03 16:14
     */
    @GetMapping("alyRemove")
    @ApiOperation(value = "删除", notes = "删除")
    public Object deleteImage(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        if (StringUtils.isNull(ids)) {
            return AjaxResult.error(1006, "图片id不能未空");
        }
        String[] idList = ids.split(",");
        for (String id : idList) {
            XhpcImg xhpcImg = iXhpcImgService.info(Long.parseLong(id));
            if (StringUtils.isNotNull(xhpcImg)) {
                OSSClient ossClient = new OSSClient(environment.getProperty("oss.endpoint"), environment.getProperty("oss.access-key"), environment.getProperty("oss.secret-key"));
                ossClient.deleteObject(environment.getProperty("oss.bucket-name"), xhpcImg.getUrl());
                ossClient.shutdown();
                xhpcImg.setDelFlag(1);
                iXhpcImgService.update(xhpcImg);
            }
        }
        return AjaxResult.success();
    }
}
