package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.dto.GovCriterionFileDto;
import com.nantian.cloud.jljc.entity.GovCriterion;
import com.nantian.cloud.jljc.service.GovCriterionService;
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.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.nantian.cloud.jljc.vo.util.FileUtil.getFileSize;


/**
 * 节能减排法规标准
 *
 * @author
 * @date 2018-09-27 15:20:44
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/govCriterion")
@Api(value = "govCriterion", tags = "节能减排法规标准")
public class GovCriterionController {
    private final GovCriterionService govCriterionService;
    private final MinioTemplate minioTemplate;


    /**
     * 分页查询
     *
     * @param page         分页对象
     * @param govCriterion
     * @return
     */
    @GetMapping("/page")
    @SysLog("分页获取节能减排法规标准")
    @ApiOperation(value = "分页获取节能减排法规标准", notes = "分页获取节能减排法规标准")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "govCriterion", value = "节能减排法规标准（查询条件：标准名称criterionName、标准分类criterionType）", required = false, dataType = "json", paramType = "path")
    })
    public R getGovCriterionPage(Page page, GovCriterion govCriterion) {
        //return R.ok(govCriterionService.page(page, Wrappers.query(govCriterion)));
        govCriterion.setDelFlag("1"); //筛选未删除项
        return R.ok(govCriterionService.getPageScope(page, govCriterion));
    }


    /**
     * 信息
     *
     * @param govCriterionId
     * @return R
     */
    @GetMapping("/{govCriterionId}")
    @SysLog("根据id获取节能减排法规标准")
    @ApiOperation(value = "根据id获取节能减排法规标准", notes = "根据id获取节能减排法规标准")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("govCriterionId") Integer govCriterionId) {
        return R.ok(govCriterionService.getById(govCriterionId));
    }

    /**
     * 保存
     */
    @PostMapping
    @SysLog("新增节能减排法规标准")
    @ApiOperation(value = "新增节能减排法规标准", notes = "新增节能减排法规标准")
    @ApiImplicitParam(name = "GovCriterionFileDto", value = "节能减排法规标准文件上传对象", required = true)
    //public R save(@RequestBody GovCriterion govCriterion) {
    public R save(GovCriterionFileDto govCriterionFileDto) throws Exception {
        //return R.ok(govCriterionService.save(govCriterion));
        return getByCriterionFileDto(govCriterionFileDto, new GovCriterion());
    }

    /**
     * 修改
     */
    @PutMapping
    @SysLog("修改节能减排法规标准")
    @ApiOperation(value = "修改节能减排法规标准", notes = "修改节能减排法规标准")
    @ApiImplicitParam(name = "GovCriterionFileDto", value = "节能减排法规标准文件上传对象", required = true)
    //public R updateById(@RequestBody GovCriterion govCriterion) {
    public R updateById(GovCriterionFileDto govCriterionFileDto) throws Exception {
        //return getByAdvancedFileDto(govCriterion,new GovCriterion());
        GovCriterion govCriterion = govCriterionService.getById(govCriterionFileDto.getId());
        if (govCriterion == null) {
            return R.failed("节能减排法规标准不存在，修改失败！");
        }
        return getByCriterionFileDto(govCriterionFileDto, govCriterion);
    }

    /**
     * 删除
     *
     * @param govCriterionId
     * @return R
     */
    @DeleteMapping("/{govCriterionId}")
    @SysLog("删除节能减排法规标准")
    @ApiOperation(value = "删除节能减排法规标准", notes = "删除节能减排法规标准")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R removeById(@PathVariable Integer govCriterionId) {
        GovCriterion govCriterion = govCriterionService.getById(govCriterionId);
        if (govCriterion == null) {
            return R.failed("节能减排法规标准不存在，删除失败！");
        }
        ScUser u = SecurityUtils.getUser();
        govCriterion.setUserid(u.getId());
        govCriterion.setUpdateTime(new Date());
        govCriterion.setDelFlag("4");
        return R.ok(govCriterionService.updateById(govCriterion));
    }

    /**
     * 根据文件上传对象更新先进技术资料信息
     */
    public R getByCriterionFileDto(GovCriterionFileDto govCriterionFileDto, GovCriterion govCriterion) throws Exception {
        //更新先进技术资料对象
        ScUser u = SecurityUtils.getUser();
        if (govCriterion.getId() == null) { //新增时，设置部门id，注销标志
            govCriterion.setDeptId(u.getDeptId());
            govCriterion.setDelFlag("1");
        }
        govCriterion.setUserid(u.getId());
        govCriterion.setUpdateTime(new Date());
        govCriterion.setCriterionType(govCriterionFileDto.getType());
        govCriterion.setStandard(govCriterionFileDto.getStandard());
        govCriterion.setImplementationTime(govCriterionFileDto.getImplementationTime());
        govCriterion.setReleaseTime(govCriterionFileDto.getReleaseTime());
        MultipartFile file = govCriterionFileDto.getFile();
        if (file == null) {
            //return R.failed("文件不存在，更新先进技术资料信息失败");
            govCriterion.setCriterionName(govCriterionFileDto.getFileName());
        } else {
            //上传文件
            String uuid = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename(); //文件名
            //minioTemplate.putObject("jljc", uuid, inputStream);
            minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");

            //获取文件大小
            String fileSize = getFileSize(file.getSize());
            govCriterion.setFileSize(fileSize);

            //获取文件名称（不含文件后缀）
            String[] strings = fileName.split("\\.");
            String newFileName = strings[0];

            //fileName + "<" + uuid   文件名、uuid的拼接
            govCriterion.setFile(fileName + "<" + uuid);
            govCriterion.setCriterionName(govCriterionFileDto.getFileName() != null ? govCriterionFileDto.getFileName() : newFileName);
        }

        boolean flag = govCriterionService.saveOrUpdate(govCriterion);
        //return flag ? R.ok(fileName + "<" + uuid) : R.failed("更新节能减排法规标准失败！");
        return R.ok(flag);
    }

}
