package com.qs.mp.web.controller.common;

import com.qs.mp.common.config.MpConfig;
import com.qs.mp.common.qcloud.QcloudFileUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.common.utils.file.FileUtils;
import com.qs.mp.core.domain.LoginUser;
import com.qs.mp.framework.security.handle.HostHolder;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/v1/mp/*")
@RestController
@Component
public class FileDownloadController extends BaseApiController {

  private static final Logger log = LoggerFactory.getLogger(FileDownloadController.class);

  /**
   * 文件上传路径
   */
  @Value("${mp.profile}")
  public String filePath;


  /**
   * 私有
   */
  @Value("${cloud.private-bucket-name}")
  private String privateBucketName;

  @Autowired
  protected HostHolder hostHolder;

  @GetMapping("file/remote/download")
  public void fileDownload(@RequestParam("name") String fileName, HttpServletResponse response,
      HttpServletRequest request) {
    if (StringUtils.isBlank(fileName)) {
      LogUtil.error(logger, "下载文件参数为空");
      return;
    }

    LoginUser loginUser = hostHolder.getUser();
//    String custId = loginUser.getCustId();

    // 判断获取权限，文件名上带了custid的，只有匹配当前登录的custId才能下载
    // 目前是get请求，商户端登录后custid没有存到loginUser里，导致这里获取不到，故先不做校验，
    // 后续要做校验再考虑商户端登录后把custid存到loginUser里。
    /*if (fileName.indexOf("/") > 0) {
      if (fileName.indexOf(custId) < 0) {
        LogUtil.error(logger, "文件和当前用户的客户ID不匹配，fileName:{0}, custId:{1}",
            fileName, custId);
        return;
      }
    }*/

    int idx = fileName.lastIndexOf("/");
    String outFileDir = MpConfig.getDownloadPath() + (idx > 0 ? fileName.substring(0, idx + 1) : "");
    File tempFile = new File(outFileDir);
    if(!tempFile.exists()) {
      tempFile.mkdirs();
    }
    try {

      QcloudFileUtils.downloadFile(fileName, privateBucketName, MpConfig.getDownloadPath(),
          fileName);

      String realFileName =
          System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
      String filePath = MpConfig.getDownloadPath() + fileName;

      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      FileUtils.setAttachmentResponseHeader(response, realFileName);
      FileUtils.writeBytes(filePath, response.getOutputStream());

      FileUtils.deleteFile(filePath);

    } catch (Exception e) {
      LogUtil.error(logger, e, "下载文件失败，fileName:{0}, custId:{1}", fileName, null);
    }
  }
}
