package com.ruoyi.web.controller.back;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.MusicInfo;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MusicUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.config.AliConfig;
import com.ruoyi.system.mapper.MusicInfoMapper;
import com.ruoyi.system.mapper.ShopUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RequestMapping("/file")
@RestController
public class FileController extends BaseController {

    @Autowired
    private ShopUserMapper shopUserMapper;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    @Autowired
    private MusicInfoMapper musicInfoMapper;

    /**
     * 下载OSS文件
     */
    @GetMapping("/download/{objectName}/{fileName}")
    public void downloadOssFile(@RequestParam(value = "musicId",required = false) String musicId, @PathVariable("objectName") String objectName, @PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            String ossPath = objectName + "/" + fileName;
            // 检查用户登录状态

            // 获取文件字节
            if (objectName.equals("musicFile")) {
                LoginUser userInfo = SecurityUtils.getLoginUser();
                SysUser sysUser = userInfo.getUser();
               if (sysUser == null) {
                   if (StrUtil.isBlank(musicId)) {
                       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                       response.setContentType("application/json;charset=UTF-8");
                       response.getWriter().write("{\"code\":400,\"msg\":\"音乐ID不能为空\"}");
                       return;
                   }
                   ShopUser shopUser = userInfo.getShopUser();
                   if (shopUser == null) {
                       response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                       response.setContentType("application/json;charset=UTF-8");
                       response.getWriter().write("{\"code\":401,\"msg\":\"用户未登录\"}");
                       return;
                   }
                   //shopUser = shopUserMapper.selectShopUserByUserId(userId);
                   MusicInfo musicInfo = musicInfoMapper.selectByMusicId(musicId);

                   if (musicInfo == null) {
                       response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                       response.setContentType("application/json;charset=UTF-8");
                       response.getWriter().write("{\"code\":404,\"msg\":\"音乐信息不存在\"}");
                       return;
                   }

                   if (musicInfo.getVip() != null && musicInfo.getVip() == 1) {
                       // 判断用户vip
                       if (!MusicUtil.getShopIsVip(shopUser)) {
                           response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                           response.setContentType("application/json;charset=UTF-8");
                           response.getWriter().write("{\"code\":403,\"msg\":\"该音乐为VIP专享，请升级VIP后下载\"}");
                           return;
                       }
                   }
               }
            }
            
            byte[] data = AliConfig.ossDown(ossPath);
            if (data == null || data.length == 0) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":404,\"msg\":\"文件不存在或下载失败\"}");
                return;
            }
            
            // 设置响应头，支持中文文件名
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            response.getOutputStream().write(data);
            response.getOutputStream().flush();
            
        } catch (Exception e) {
            try {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"msg\":\"下载失败: " + e.getMessage() + "\"}");
            } catch (Exception ignored) {
            }
        }
    }

}
