package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.service.IFileInfoService;
import cn.com.ctop.crawler.modules.music.entity.BytedanceMusicInfo;
import cn.com.ctop.crawler.modules.music.service.IBytedanceMusicInfoService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * 音乐信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-10-28
 */
@Slf4j
@Api(tags = "音乐信息")
@RestController
@RequestMapping("/ctop/bytedanceMusicInfo")
public class BytedanceMusicInfoController {
    @Autowired
    private IBytedanceMusicInfoService bytedanceMusicInfoService;
    @Autowired
    private IFileInfoService fileInfoService;

    @PostMapping(value = "/netEaseDownLoad")
    public void netEasedownLoad(@RequestBody JSONObject data, HttpServletResponse response) throws Exception {
        String fileName = data.getString("musicName");
        String fileUrl = data.getString("musicUrl");
        String filePath = fileInfoService.downLoadByUrl(fileUrl);
        File file = new File(filePath);
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Content-Length", file.length() + "");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("audio/mp3");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    @PostMapping(value = "/downLoad")
    public void downLoad(Long id, HttpServletResponse response) throws Exception {
        if (null == id || id == 0) {
            log.error("抖音音乐文件下载异常:参数异常");
            return;
        }
        BytedanceMusicInfo musicInfo = bytedanceMusicInfoService.getById(id);
        if (null == musicInfo) {
            log.error("抖音音乐文件下载异常:音乐数据不存在");
            return;
        }
        musicInfo.setDownloadNum(musicInfo.getDownloadNum() + 1);
        bytedanceMusicInfoService.updateById(musicInfo);
        String author = musicInfo.getAuthor();
        String name = musicInfo.getName();
        String fileName = author + "-" + name + ".mp3";
        String filePath = fileInfoService.downLoadByUrl(musicInfo.getMusicUrl());
        File file = new File(filePath);
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Content-Length", buffer.length + "");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("audio/mp3");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    /**
     * 分页列表查询
     *
     * @param bytedanceMusicInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "音乐信息-分页列表查询", notes = "音乐信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BytedanceMusicInfo>> queryPageList(BytedanceMusicInfo bytedanceMusicInfo,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<BytedanceMusicInfo>> result = new Result<>();
        QueryWrapper<BytedanceMusicInfo> queryWrapper = QueryGenerator.initQueryWrapper(bytedanceMusicInfo, req.getParameterMap());
        Page<BytedanceMusicInfo> page = new Page<>(pageNo, pageSize);
        IPage<BytedanceMusicInfo> pageList = bytedanceMusicInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param bytedanceMusicInfo
     * @return
     */
    @ApiOperation(value = "音乐信息-添加", notes = "音乐信息-添加")
    @PostMapping(value = "/add")
    public Result<BytedanceMusicInfo> add(@RequestBody BytedanceMusicInfo bytedanceMusicInfo) {
        Result<BytedanceMusicInfo> result = new Result<>();
        try {
            bytedanceMusicInfoService.save(bytedanceMusicInfo);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param bytedanceMusicInfo
     * @return
     */
    @ApiOperation(value = "音乐信息-编辑", notes = "音乐信息-编辑")
    @PutMapping(value = "/edit")
    public Result<BytedanceMusicInfo> edit(@RequestBody BytedanceMusicInfo bytedanceMusicInfo) {
        Result<BytedanceMusicInfo> result = new Result<BytedanceMusicInfo>();
        BytedanceMusicInfo bytedanceMusicInfoEntity = bytedanceMusicInfoService.getById(bytedanceMusicInfo.getId());
        if (bytedanceMusicInfoEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = bytedanceMusicInfoService.updateById(bytedanceMusicInfo);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "音乐信息-通过id删除", notes = "音乐信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            bytedanceMusicInfoService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "音乐信息-批量删除", notes = "音乐信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<BytedanceMusicInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<BytedanceMusicInfo> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.bytedanceMusicInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "音乐信息-通过id查询", notes = "音乐信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BytedanceMusicInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<BytedanceMusicInfo> result = new Result<>();
        BytedanceMusicInfo bytedanceMusicInfo = bytedanceMusicInfoService.getById(id);
        if (bytedanceMusicInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(bytedanceMusicInfo);
            result.setSuccess(true);
        }
        return result;
    }
}
