package com.nantian.cloud.jljc.controller;


import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.TFaAccreditingBody;
import com.nantian.cloud.jljc.entity.TFaFixedAssets;
import com.nantian.cloud.jljc.entity.TFaProjectMaterial;
import com.nantian.cloud.jljc.entity.TFaUnionPiece;
import com.nantian.cloud.jljc.service.TFaAccreditingBodyService;
import com.nantian.cloud.jljc.service.TFaFixedAssetsService;
import com.nantian.cloud.jljc.service.TFaProjectMaterialService;
import com.nantian.cloud.jljc.service.TFaUnionPieceService;
import com.nantian.cloud.jljc.vo.TFaProjectVO;
import com.nantian.cloud.jljc.vo.TFaUnionPieceVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 固定资产投资项目节能审查接件信息表 前端控制器
 * </p>
 *
 * @author fyf
 * @since 2022-02-15
 */
@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("/tFaUnionPiece")
public class TFaUnionPieceController {

    @Autowired
    TFaUnionPieceService tFaUnionPieceService;

    @Autowired
    TFaFixedAssetsService tFaFixedAssetsService;

    @Autowired
    TFaProjectMaterialService tFaProjectMaterialService;

    @Autowired
    MinioTemplate minioTemplate;

    @Autowired
    TFaAccreditingBodyService tFaAccreditingBodyService;

    /**
     * 获取分页数据
     *
     * @param page
     * @param tFaUnionPiece
     * @return
     */
    @GetMapping("/page")
    @SysLog("分页获取固定资产投资项目节能审查接件信息表")
    public R getPage(Page page, TFaUnionPiece tFaUnionPiece) {
        tFaUnionPiece.setDelFlag(1);
        return R.ok(tFaUnionPieceService.getPage(page, tFaUnionPiece));
    }

    /**
     * 接件信息详情
     *
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    @SysLog("根据id获取固定资产投资项目节能审查接件信息表")
    public R getInfo(@PathVariable Integer id) {
        TFaUnionPiece tFaUnionPiece = tFaUnionPieceService.getOne(
                new QueryWrapper<TFaUnionPiece>().eq("project_id", id));
        TFaFixedAssets tFaFixedAssets = tFaFixedAssetsService.getById(id);
        TFaUnionPieceVo tFaUnionPieceVo = new TFaUnionPieceVo();
        tFaUnionPieceVo.setUnionPieceDate(tFaUnionPiece.getUpdateTime());
        tFaUnionPieceVo.setUnionPieceMan(tFaUnionPiece.getUnionPieceMan());
        tFaUnionPieceVo.setProjectId(tFaUnionPiece.getProjectId());
        tFaUnionPieceVo.setProjectName(tFaFixedAssets.getProjectName());
        tFaUnionPieceVo.setProjectStatus(tFaFixedAssets.getProjectStatus());
        return R.ok(tFaUnionPieceVo);
    }

    @GetMapping("/unionIn")
    public R unionIn(){
        ScUser u = SecurityUtils.getUser();
        String userRealName = u.getUserRealName();
        Date date = new Date();
        return R.ok(MapUtil.builder().put("unionPieceMan", userRealName).put("unionPieceDate", date).map());
    }

    /**
     * 接件人员信息更新
     * @param tFaUnionPiece
     * @return
     */
    @PostMapping("/infoUpdate")
    @SysLog("固定资产投资项目节能审查接件信息表 接件人员信息更新")
    public R infoUpdate(@RequestBody TFaUnionPiece tFaUnionPiece){
        ScUser u = SecurityUtils.getUser();
        tFaUnionPiece.setUpdateTime(new Date());
        tFaUnionPiece.setDeptId(u.getDeptId());
        tFaUnionPiece.setUserId(u.getId());
        tFaUnionPiece.setUpdateTime(new Date());
        tFaUnionPiece.setDelFlag(1);
        tFaUnionPieceService.save(tFaUnionPiece);
        return R.ok();
    }

    /**
     * 报送评审机构
     * @param id
     * @return
     */
    @PostMapping("/report/{id}")
    @SysLog("固定资产投资项目节能审查接件信息表 报送评审机构")
    public R reportInstitution(@PathVariable("id") Integer id, Integer time){
        ScUser u = SecurityUtils.getUser();
        TFaUnionPiece tFaUnionPiece = tFaUnionPieceService.getById(id);
        Integer projectid = tFaUnionPiece.getProjectId();
        TFaFixedAssets tFaFixedAssets = tFaFixedAssetsService.getById(projectid);
        tFaFixedAssets.setProjectStatus(2);
        tFaFixedAssets.setDeptId(u.getDeptId());
        tFaFixedAssets.setUserId(u.getId());
        tFaFixedAssets.setUpdateTime(new Date());
        tFaFixedAssetsService.getById(tFaFixedAssets);
        TFaAccreditingBody tFaAccreditingBody = new TFaAccreditingBody();
        tFaAccreditingBody.setProjectId(projectid);
        tFaAccreditingBody.setTimeLimit(time);
        tFaAccreditingBody.setDeptId(u.getDeptId());
        tFaAccreditingBody.setUserId(u.getId());
        tFaAccreditingBody.setUpdateTime(new Date());
        tFaAccreditingBodyService.save(tFaAccreditingBody);
        return R.ok();
    }

    /**
     * 接件材料文件上传
     *
     * @param id
     * @param multipartFiles
     * @return
     * @throws IOException
     */
    @PostMapping("/fileUpload/{id}/{fileForm}")
    @SysLog("固定资产投资项目节能审查接件信息表 接件材料文件上传")
    public R fileUpload(@PathVariable Integer id,@PathVariable Integer fileForm ,@RequestParam("file") MultipartFile[] multipartFiles) throws Exception {
        TFaUnionPiece tFaUnionPiece = tFaUnionPieceService.getOne(new QueryWrapper<TFaUnionPiece>().eq("project_id", id));
        if (multipartFiles.length > 0) {
            ScUser u = SecurityUtils.getUser();
            for (MultipartFile multipartFile : multipartFiles) {
                //获取文件名称
                String fileName = multipartFile.getOriginalFilename();
                //获取文件的后缀
                String extension = "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                //生成新的文件名称
                String newFileName = "JJ" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                        + UUID.randomUUID().toString()
                        .replace("-", "") + extension;
                //文件的大小
                long size = multipartFile.getSize();
                //文件的类型
                String contentType = multipartFile.getContentType();
                //上传文件
                InputStream inputStream = multipartFile.getInputStream();
                minioTemplate.putObject("jljc", newFileName, inputStream, inputStream.available(), "application/octet-stream");
                //文件信息保存到数据库
                TFaProjectMaterial tFaProjectMaterial = new TFaProjectMaterial();
                tFaProjectMaterial.setDelFlag(1);
                tFaProjectMaterial.setExtension(extension);
                tFaProjectMaterial.setFilePath("jljc/" + newFileName);
                tFaProjectMaterial.setFileSize(String.valueOf(size));
                tFaProjectMaterial.setFileType(contentType);
                tFaProjectMaterial.setNewFileName(newFileName);
                tFaProjectMaterial.setOldFileName(fileName);
                tFaProjectMaterial.setDeptId(u.getDeptId());
                tFaProjectMaterial.setUpdateTime(new Date());
                tFaProjectMaterial.setUserId(u.getId());
                tFaProjectMaterial.setProjectId(id);
                tFaProjectMaterial.setFileForm(fileForm);
                tFaProjectMaterialService.save(tFaProjectMaterial);
                return R.ok();
            }
        } else {
            return R.failed("上传文件为空！");
        }
        return R.ok();
    }
    /**
     * 文件下载
     *
     * @param id
     * @throws IOException
     */
    @Inner(value = false)
    @GetMapping("/fileDownload/{id}")
    @SysLog("固定资产投资项目节能审查接件信息表 文件下载")
    public R fileDownload(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        TFaProjectMaterial tFaProjectMaterial = tFaProjectMaterialService.getById(id);
        //获取文件名
        String newFileName = tFaProjectMaterial.getNewFileName();
        String oldFileName = tFaProjectMaterial.getOldFileName();
        //文件下载
        InputStream object = minioTemplate.getObject("jljc", newFileName);

        response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(oldFileName,"UTF-8"));
        response.setContentType("application/force-download");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(object,outputStream);
//        IOUtils.closeQuietly(object);
//        IOUtils.closeQuietly(outputStream);
        return R.ok();
    }

    @Inner(value = false)
    @GetMapping("getFileUrl/{newFileName}")
    public R getFileUrl(@PathVariable String newFileName,HttpServletResponse response) throws IOException {
//        TFaProjectMaterial tFaProjectMaterial = tFaProjectMaterialService.getOne(new QueryWrapper<TFaProjectMaterial>().eq("new_file_name",newFileName));

        InputStream object = minioTemplate.getObject("jljc", newFileName);
//        response.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(oldFileName,"UTF-8"));
        response.setContentType("application/pdf");
//        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(object,outputStream);
        return R.ok();
    }

    @DeleteMapping("/fileRemove/{id}")
    @SysLog("根据id删除固定资产投资项目节能审查接件信息表")
    public R fileRemove(@PathVariable("id") Integer id) throws Exception {
        ScUser u = SecurityUtils.getUser();
        TFaProjectMaterial tFaProjectMaterial = tFaProjectMaterialService.getById(id);
        //获取文件名
        String newFileName = tFaProjectMaterial.getNewFileName();
        TFaProjectMaterial projectMaterial = tFaProjectMaterialService.getOne(new QueryWrapper<TFaProjectMaterial>().eq(
                "new_file_name", newFileName
        ));
        projectMaterial.setUserId(u.getId());
        projectMaterial.setDelFlag(4);
        projectMaterial.setUpdateTime(new Date());
        projectMaterial.setDeptId(u.getDeptId());
        tFaProjectMaterialService.updateById(projectMaterial);
        //文件删除
        minioTemplate.removeObject("jljc",newFileName);
        return R.ok();
    }

}


