package com.yccrc.kede.controller.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mchange.io.FileUtils;
import com.yccrc.common.annotation.Log;
import com.yccrc.common.config.YccrcConfig;
import com.yccrc.common.constant.Constants;
import com.yccrc.common.core.controller.BaseController;
import com.yccrc.common.enums.BusinessType;
import com.yccrc.common.exception.ServiceException;
import com.yccrc.common.utils.PageUtils;
import com.yccrc.common.vo.Result;
import com.yccrc.kede.domain.Attach;
import com.yccrc.kede.enums.AttachTypeEnum;
import com.yccrc.kede.service.IAttachService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
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.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 项目附件信息Controller
 *
 * @author yccrc
 * @date 2022-04-25
 */
@Api(tags = "附件信息")
@RestController
@RequestMapping("/common/attach")
public class AttachController extends BaseController {
    @Autowired
    private IAttachService attachService;


    @ApiOperation(value = "查询附件列表")
    @GetMapping("/attach/{attachType}/{dataId}")
    public Result<Page<Attach>> list(@PathVariable("attachType") AttachTypeEnum attachType, @PathVariable("dataId") Integer dataId) {
        QueryWrapper<Attach> queryWrapper = new QueryWrapper<Attach>().eq("attach_type", attachType).eq("data_id", dataId);
        return new Result<Page<Attach>>().ok(attachService.page(PageUtils.initPage(), queryWrapper));

    }

    @ApiOperation(value = "查询附件列表")
    @GetMapping("/attach/{attachType}/{dataId}/{fileType}")
    public Result<Page<Attach>> list(@PathVariable("attachType") AttachTypeEnum attachType,
                                     @PathVariable("dataId") Integer dataId,
                                     @PathVariable("fileType") String fileType) {
        QueryWrapper<Attach> queryWrapper = new QueryWrapper<Attach>()
                .eq("attach_type", attachType)
                .eq("data_id", dataId)
                .eq("file_type", fileType);
        return new Result<Page<Attach>>().ok(attachService.page(PageUtils.initPage(), queryWrapper));

    }

    @ApiOperation(value = "附件上传")
    @PostMapping("upload")
    public Result<Attach> upload(@RequestParam(value = "attachType", required = false) AttachTypeEnum attachType,
                                 @RequestParam(value = "dataId", required = false) Integer dataId,
                                 @RequestParam(value = "fileType", required = false) String fileType,
                                 MultipartFile file) throws IOException {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String fileKey = IdUtil.fastSimpleUUID() + "." + suffix;
        String uploadPath = YccrcConfig.getUploadPath();
        FileUtil.mkdir(uploadPath);
        String dest = uploadPath + fileKey;
        file.transferTo(new File(dest));

        //file.transferTo(new File(chuanglxConfig.getProfile()));
        Attach attach = new Attach();
        //保存数据信息至数据库
        attach.setFileName(file.getOriginalFilename());
        attach.setFileSize(file.getSize());
        attach.setFileKey(fileKey);
        attach.setUrl(YccrcConfig.getDomain() + Constants.RESOURCE_PREFIX + "/upload/" + fileKey);
        attach.setDataId(dataId);
        attach.setFileType(fileType);
        attach.setAttachType(attachType);
        try {
            attach.setCreateBy(super.getUsername());
        } catch (Exception e) {

        }

        attachService.save(attach);
        return new Result<Attach>().ok(attach);
    }


    @ApiOperation(value = "附件上传")
    @PostMapping("uploads")
    public Result<List<Attach>> upload(@RequestParam(value = "attachType", required = false) AttachTypeEnum attachType,
                                       @RequestParam(value = "dataId", required = false) Integer dataId,
                                       @RequestParam(value = "fileType", required = false) String fileType,
                                       MultipartFile[] files) throws IOException {
        List<Attach> attachments = new ArrayList<>();
        for (MultipartFile file : files) {
            Result<Attach> upload = upload(attachType, dataId, fileType, file);
            attachments.add(upload.getData());
        }
        return new Result<List<Attach>>().ok(attachments);
    }

    @ApiOperation(value = "删除附件信息")
    @Log(title = "附件信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Long[] ids) {
        return new Result<Boolean>().ok(attachService.removeByIds(Arrays.asList(ids)));
    }

    @ApiOperation(value = "下载附件")
    @GetMapping("/{ids}")
    public void download(HttpServletResponse response, @PathVariable Long[] ids) throws IOException {
        if (ids == null || ids.length == 0) throw new ServiceException("请选择需要下载的附件");
        String fileName = "";
        byte[] data = null;
        if (ids.length == 1) {
            Attach attach = attachService.getById(ids[0]);
            fileName = attach.getFileName();
            File file = new File(YccrcConfig.getUploadPath() + attach.getFileKey());
            data = IoUtil.readBytes(new FileInputStream(file));
        } else {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ZipOutputStream zip = new ZipOutputStream(outputStream);
            for (Long id : ids) {
                Attach attach = attachService.getById(id);
                File file = new File(YccrcConfig.getUploadPath() + attach.getFileKey());
                if (file.exists()) {
                    try {
                        // 添加到zip
                        zip.putNextEntry(new ZipEntry(attach.getFileName()));

                        IOUtils.write(FileUtils.getBytes(file), zip);
                        zip.flush();
                        zip.closeEntry();
                    } catch (IOException e) {
                        logger.error("文件写入压缩包失败：" + attach.getFileName(), e);
                    }

                }
            }
            IOUtils.closeQuietly(zip);
            data = outputStream.toByteArray();
            fileName = DateUtil.format(new Date(), "HHmmss") + ".zip";
        }
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
