package com.xjrsoft.module.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.UploadUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.config.OSSConfig;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.oss.factory.OssFactory;
import com.xjrsoft.module.system.dto.FileDownloadDto;
import com.xjrsoft.module.system.dto.FileListDto;
import com.xjrsoft.module.system.dto.FilePageDto;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import com.xjrsoft.module.system.vo.FileListVo;
import com.xjrsoft.module.system.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 文件关联关系表 前端控制器
 * </p>
 *
 * @author tzx
 * @since 2022-03-08
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/file")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/file", tags = "文件")
@AllArgsConstructor
public class FileController {
    private IFileService fileService;

    private OSSConfig ossConfig;


    @GetMapping("/info")
    @ApiOperation(value = "根据文件Id获取单个文件数据")
    public R info(@RequestParam String id) {
        return R.ok(fileService.getById(id));
    }

    @GetMapping
    @ApiOperation(value = "查询文件列表（不分页）")
    public R list(@Valid FileListDto dto) {

        List<FileListVo> list = new ArrayList<>();
        if(dto.getFolderId() != null || dto.getFileName() != null || dto.getProcessId() != null){
           list = fileService.selectJoinList(FileListVo.class, MPJWrappers.<File>lambdaJoin()
                    .like(StrUtil.isNotBlank(dto.getFileName()), File::getFileName, dto.getFileName())
                    .eq(ObjectUtil.isNotNull(dto.getFolderId()), File::getFolderId, dto.getFolderId())
                    .eq(StrUtil.isNotBlank(dto.getProcessId()), File::getProcessId, dto.getProcessId())
                    .select(File::getId)
                    .select(File.class, x -> VoToColumnUtil.fieldsToColumns(FileListVo.class).contains(x.getProperty()))
                    .selectAs(User::getName, FileListVo::getCreateUserName)
                    .leftJoin(User.class, User::getId, File::getCreateUserId)
                    .last(StrUtil.isNotBlank(dto.getField()), GlobalConstant.ORDER_BY + StringPool.SPACE + StrUtil.toUnderlineCase(dto.getField()) + StringPool.SPACE + ConventPage.getOrder(dto.getOrder())));

        }

        return R.ok(list);
    }

    @GetMapping("/page")
    @ApiOperation(value = "查询文件列表(分页)")
    public R page(@Valid FilePageDto dto) {
        LambdaQueryWrapper<File> wrapper = Wrappers.<File>query().lambda()
                .like(StrUtil.isNotBlank(dto.getFileName()), File::getFileName, dto.getFileName())
                .eq(ObjectUtil.isNotNull(dto.getFolderId()), File::getFolderId, dto.getFolderId())
                .eq(StrUtil.isNotBlank(dto.getProcessId()), File::getProcessId, dto.getProcessId());

        IPage<File> page = fileService.page(ConventPage.getPage(dto), wrapper);
        PageOutput<File> pageOutput = ConventPage.getPageOutput(page, File.class);
        return R.ok(pageOutput);
    }

    @DeleteMapping
    @ApiOperation(value = "删除文件(可批量)")
    public R delete(@RequestBody List<Long> ids) {

        return R.ok(fileService.removeBatchByIds(ids));
    }

    @DeleteMapping("/delete-single")
    @ApiOperation(value = "删除组件 删除单个文件")
    public R delete(@RequestBody Long id) {

        File deleteFile = fileService.getById(id);
        //找到没有被删除的文件
        List<File> list = fileService.list(Wrappers.lambdaQuery(File.class).eq(File::getFolderId, deleteFile.getFolderId()).ne(File::getId, id));

        //如果删除的是最后一个文件  就返回空值
        if(list.size() > 0){
            Long newfolderId = IdWorker.getId();

            for (File newFile : list) {
                newFile.setId(null);
                newFile.setFolderId(newfolderId);
            }
            List<File> insertFile = new ArrayList<>(list);

            fileService.saveBatch(insertFile);

            return R.ok(newfolderId);

        }
        else {
            return R.ok(StringPool.EMPTY);
        }

    }

    @PostMapping
    @ApiOperation(value = "单文件上传")
    public R uploadFile(@RequestParam(value = "file", required = true) MultipartFile multipartFile) throws Exception {
        Long folderId = IdWorker.getId();
        Long fileId = IdWorker.getId();
        File file = uploadFile(multipartFile, folderId, fileId);
        return R.ok(file.getFileUrl());
    }

    @PostMapping("/folder")
    @ApiOperation(value = "单文件上传")
    public R uploadFileToFolder(@RequestParam Long folderId, @RequestParam MultipartFile multipartFile) throws Exception {
        Long fileId = IdWorker.getId();
        File file = uploadFile(multipartFile, folderId, fileId);
        return R.ok(file.getFileUrl());
    }


    @PostMapping("/multiple-file-upload")
    @ApiOperation(value = "多文件上传")
    public R uploadFiles(@RequestParam(value = "file") MultipartFile[] multipartFiles ) throws Exception {
        List<String> urlList = new ArrayList<>();
        if (multipartFiles != null && multipartFiles.length > 0) {
            Long folderId = IdWorker.getId();
            for (MultipartFile multipartFile : multipartFiles) {
                Long fileId = IdWorker.getId();
                File file = uploadFile(multipartFile, folderId, fileId);
                urlList.add(file.getFileUrl());
            }

        }
        return R.ok(urlList);
    }

    @PostMapping("/multiple-file-upload/folder")
    @ApiOperation(value = "多文件上传")
    @Transactional
    public R uploadFilesToFolder(@RequestParam(required = false) Long folderId, @RequestParam(value = "file") MultipartFile[] multipartFiles) throws Exception {
        List<FileVo> fileVoList = new ArrayList<>();
        if (multipartFiles != null && multipartFiles.length > 0) {
            for (MultipartFile multipartFile : multipartFiles) {
                Long fileId = IdWorker.getId();
                if (folderId == null) {
                    folderId = IdWorker.getId();
                }
                File file = uploadFile(multipartFile, folderId, fileId);
                fileVoList.add(BeanUtil.toBean(file, FileVo.class));
            }
        }
        return R.ok(fileVoList);
    }

    private File uploadFile(MultipartFile file, Long folderId, Long fileId) throws Exception {
        String filename = file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
        //保存到云服务器
        String filePath = UploadUtil.uploadFile(file);

        File fileEntity = new File();
        fileEntity.setId(fileId);
        fileEntity.setFolderId(folderId);
        fileEntity.setFileName(filename);
        fileEntity.setFileUrl(filePath);
        fileEntity.setFileSize(file.getSize());
        fileEntity.setFileSuffiex(StringPool.DOT + suffix);
        fileEntity.setFileType(suffix);

        if (GlobalConstant.imageType.contains(StringUtils.lowerCase(suffix.replace(StringPool.DOT, StringPool.EMPTY)))) {
            String thSuffix = StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG;

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImgUtil.scale(file.getInputStream(), outputStream,200,200,null);

            byte[] thBytes = outputStream.toByteArray();

            String thUrl = Objects.requireNonNull(OssFactory.build()).uploadSuffix(thBytes,StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG);
            outputStream.close();

            fileEntity.setThUrl(thUrl);
            fileEntity.setThType(thSuffix);
            fileEntity.setThName(file.getOriginalFilename().replace(suffix,StringPool.EMPTY) + "-缩略图");
            fileEntity.setThSize(Convert.toLong(thBytes.length));
        }
        fileService.save(fileEntity);
        return fileEntity;
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载文件")
    public ResponseEntity<byte[]> download(@Valid FileDownloadDto dto){
        byte[] resultBtyeAry_temp = fileService.downloadFileByZip(dto.getFolderId());
        String encodedFileName = "";
        try{
            encodedFileName = URLEncoder.encode(dto.getFileName(), "UTF-8");
        }catch (Exception e){

        }
        return RT.fileStream(resultBtyeAry_temp, encodedFileName + ".zip");
    }
}
