package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.domain.FileExchangePackage;
import com.ruoyi.business.domain.FileExchangePackageLog;
import com.ruoyi.business.service.IFileExchangePackageLogService;
import com.ruoyi.business.service.IFileExchangePackageService;
import com.ruoyi.common.core.exception.BusinessException;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.FebsUtil;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.ruoyi.common.core.constant.Constants.NO;
import static com.ruoyi.common.core.constant.Constants.YES;

/**
 * 对外文件打包Controller
 * 
 * @author ruoyi
 * @date 2024-01-29
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/filePackage")
@RequiredArgsConstructor
public class FileExchangePackageController extends BaseController {

    private final IFileExchangePackageService fileExchangePackageService;
    private final IFileExchangePackageLogService fileExchangePackageLogService;

    /**
     * 查询对外文件打包列表
     */
    @RequiresPermissions("business_package_list")
    @GetMapping
    public AjaxResult list(FileExchangePackage fileExchangePackage) {
        List<FileExchangePackage> list = fileExchangePackageService.selectFileExchangePackageList(fileExchangePackage);
        return success(list);
    }

    /**
     * 查询对外文件打包列表(分页)
     */
    @RequiresPermissions("business_package_list")
    @GetMapping("/list")
    public TableDataInfo pageList(FileExchangePackage fileExchangePackage) {
        startPage();
        List<FileExchangePackage> list = fileExchangePackageService.selectFileExchangePackageList(fileExchangePackage);
        return getDataTable(list);
    }

    /**
     * 获取对外文件打包详细信息
     */
    @RequiresPermissions("business_package_query")
    @GetMapping(value = "/{id}")
    public AjaxResult getFileExchangePackageById(@PathVariable("id") Long id) {
        return success(fileExchangePackageService.selectFileExchangePackageById(id));
    }

    /**
     * 新增对外文件打包
     */
    @RequiresPermissions("business_package_add")
    @Log(title = "对外文件打包", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addFileExchangePackage(@RequestBody FileExchangePackage fileExchangePackage) {
        fileExchangePackage.setDeptIdPath(SecurityUtils.getDeptIdPath());
        fileExchangePackage.setDeptName(SecurityUtils.getDeptName());
        fileExchangePackage.setCreateUserId(SecurityUtils.getUserId());
        fileExchangePackage.setCreateBy(SecurityUtils.getUsername());
        return toAjax(fileExchangePackageService.insertFileExchangePackage(fileExchangePackage));
    }

    /**
     * 修改对外文件打包
     */
    @RequiresPermissions("business_package_edit")
    @Log(title = "对外文件打包", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateFileExchangePackage(@RequestBody FileExchangePackage fileExchangePackage) {
        fileExchangePackage.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(fileExchangePackageService.updateFileExchangePackage(fileExchangePackage));
    }

    /**
     * 批量删除对外文件打包
     */
    @RequiresPermissions("business_package_delete")
    @Log(title = "对外文件打包", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteByIds/{ids}")
    public AjaxResult delete(@PathVariable Long[] ids) {
        return toAjax(fileExchangePackageService.deleteFileExchangePackageByIds(ids));
    }

    /**
     * 删除对外文件打包
     */
    @RequiresPermissions("business_package_delete")
    @Log(title = "对外文件打包", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteById/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        return toAjax(fileExchangePackageService.deleteFileExchangePackageById(id));
    }

    /**
     * 导出对外文件打包列表
     */
    @RequiresPermissions("business_package_export")
    @Log(title = "对外文件打包", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FileExchangePackage fileExchangePackage) {
        List<FileExchangePackage> list = fileExchangePackageService.selectFileExchangePackageList(fileExchangePackage);
        ExcelUtil<FileExchangePackage> util = new ExcelUtil<FileExchangePackage>(FileExchangePackage.class);
        util.exportExcel(response, list, "对外文件打包数据");
    }

    /**
     * 获取文件，单条
     */
    @GetMapping("/getFile")
    public void getFile(FileExchangePackage fileExchangePackage, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<FileExchangePackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileExchangePackage::getInterfaceUrl, fileExchangePackage.getInterfaceUrl());
        FileExchangePackage one = fileExchangePackageService.getOne(queryWrapper);
        if(one == null) {
            throw new BusinessException("没有对应的接口");
        }
        LambdaQueryWrapper<FileExchangePackageLog> queryWrapperLog = new LambdaQueryWrapper<>();
        queryWrapperLog.eq(FileExchangePackageLog::getParentId, one.getId());
        queryWrapperLog.eq(FileExchangePackageLog::getStatus, NO);
        queryWrapperLog.last("limit 1");
        FileExchangePackageLog packageLog = fileExchangePackageLogService.getOne(queryWrapperLog);
        if(packageLog == null) {
            FebsUtil.makeSuccessResponse(response, "所有文件已下载");
            return;
        }
        String packageFileName = packageLog.getPackageFileName();
        response.setHeader("zip-secret", packageLog.getFileSecret());
        try{
            FileUtils.setAttachmentResponseHeader(response, packageFileName);
            FileUtils.writeBytes(one.getFilePosition() + File.separator + packageFileName, response.getOutputStream());
            LambdaUpdateWrapper<FileExchangePackageLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(FileExchangePackageLog::getId, packageLog.getId());
            updateWrapper.set(FileExchangePackageLog::getStatus, YES);
            fileExchangePackageLogService.update(updateWrapper);
        } catch (IOException e) {
            throw new ServiceException("下载失败");
        }
    }
}
