package com.uas.finance.controller;

import com.uas.dfs.service.FileClient;
import com.uas.finance.service.AttachService;
import com.uas.finance.model.Attach;
import com.uas.finance.service.FinancingApplyService;
import com.uas.finance.util.FileUploadHttp;
import com.uas.finance.util.FileUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 附件上传下载控制层
 * created by shicr on 2017/12/25
 **/
@RestController
@RequestMapping("/attach")
public class AttachController {

    private final static Logger logger = LoggerFactory.getLogger(AttachController.class);

    @Autowired
    private FileClient fileClient;

    @Autowired
    private AttachService attachService;

    @Autowired
    private FinancingApplyService financingApplyService;


    /**
     * 上传图片
     *
     * @param file
     * @param attach
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Attach save(MultipartFile file, Attach attach) throws Exception {
        //上传图片
        String path = FileUploadHttp.upload(FileUrl.FILE_UPLOAD, file, null);
        String name = file.getOriginalFilename();
        Long size = file.getSize();
        attach.setName(name);
        attach.setSize(size);
        attach.setPath(path);
        attach.setApplyId(attach.getApplyId());
        attach.setType(attach.getType());

        logger.info("附件保存", "success");
        return attachService.save(attach);
    }



    /**
     * 删除附件
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public void delete(Long id) {
        logger.info("删除单个附件");
         attachService.deleteOne(id);
    }

    /**
     * 查找某金融申请单的所有附件
     * @param cuId
     * @return
     */
    @RequestMapping("/findattaches")
    public List<Attach> findattaches(Long cuId) {
        List<Attach> attaches =attachService.findAttachesByCuId(cuId);
        logger.info("查找某金融申请单的所有附件", "success");
        return  attaches;
    }



    /**
     * 找到保理申请需要下载的文件
     *
     * @param fauu
     * @return
     */
    @RequestMapping("/download")
    public void findDownload(Long fauu, HttpServletResponse response) throws IOException {
        logger.info("找到保理申请需要下载的文件", "success");
        Attach attach = attachService.findDownload(fauu);
        if (attach == null) {
            throw new IllegalArgumentException("附件不存在");
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(attach.getName().getBytes("utf-8"), "iso-8859-1"));
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octec-stream");
        String path = attach.getPath();
        if (path.startsWith("https://dfs.ubtob.com")) {// 存储在dfs存储服务器，去dfs存储服务器下载
            byte[] fileBytes = fileClient.download(attach.getPath());
            if (fileBytes.length <= 0) {
                throw new IllegalArgumentException("附件不存在");
            }
            response.addHeader("Content-Length", String.valueOf(fileBytes.length));
            OutputStream os = response.getOutputStream();
            os.write(fileBytes);
            os.close();
        } else if (path.startsWith("http://") || path.startsWith("https://") || path.startsWith("ftp://") || path.startsWith("sftp://")) {
            // 存放在其他网络资源中，直接跳转至链接地址
            response.sendRedirect(path);
        } else {
            // 其他的当做是存放在本地服务器上，去本地服务器根据文件路径去获取
            File file = new File(attach.getPath());
            if (!file.exists()) {throw new IllegalArgumentException("附件不存在");}
            InputStream in = new FileInputStream(path);
            OutputStream os = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(attach.getName().getBytes("utf-8"), "iso-8859-1"));
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octec-stream");
            int data = 0;
            while ((data = in.read()) != -1) {
                os.write(data);
            }
            in.close();
            os.close();
        }
    }



}
