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.AdvancedFileDto;
import com.nantian.cloud.jljc.entity.AdvancedMaterial;
import com.nantian.cloud.jljc.entity.GovCriterion;
import com.nantian.cloud.jljc.entity.TradeType;
import com.nantian.cloud.jljc.service.AdvancedMaterialService;
import com.nantian.cloud.jljc.service.TradeTypeService;
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.math.BigDecimal;
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("/advancedMaterial")
@Api(value = "advancedMaterial", tags = "先进技术资料")
public class AdvancedMaterialController {
    private final AdvancedMaterialService advancedMaterialService;
    private final MinioTemplate minioTemplate;
    private final TradeTypeService tradeTypeService;

    /**
     * 分页查询
     *
     * @param page             分页对象
     * @param advancedMaterial
     * @return
     */
    @GetMapping("/page")
    @SysLog("分页获取先进技术资料")
    @ApiOperation(value = "分页获取先进技术资料", notes = "分页获取先进技术资料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "advancedMaterial", value = "先进技术资料对象（查询条件：技术名称techName、行业分类编码industryCode、" +
                    "行业分类名称industryName）", required = false, dataType = "json", paramType = "path")
    })
    public R getAdvancedMaterialPage(Page page, AdvancedMaterial advancedMaterial) {
        //return R.ok(advancedMaterialService.page(page, Wrappers.query(advancedMaterial)));
        advancedMaterial.setDelFlag("1"); //筛选未删除项
        return R.ok(advancedMaterialService.getPageScope(page, advancedMaterial));
    }


    /**
     * 信息
     *
     * @param advancedMaterialId
     * @return R
     */
    @GetMapping("/{advancedMaterialId}")
    @SysLog("根据id获取先进技术资料")
    @ApiOperation(value = "根据id获取先进技术资料", notes = "根据id获取先进技术资料")
    @ApiImplicitParam(name = "advancedMaterialId", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("advancedMaterialId") Integer advancedMaterialId) {
        return R.ok(advancedMaterialService.getById(advancedMaterialId));
    }

    /**
     * 新增
     */
    @PostMapping
    @SysLog("新增先进技术资料")
    @ApiOperation(value = "新增先进技术资料", notes = "新增先进技术资料")
    @ApiImplicitParam(name = "AdvancedFileDto", value = "先进技术资料文件上传对象", required = true, dataType = "json", paramType = "path")
    //public R save(@RequestBody AdvancedMaterial advancedMaterial) throws Exception {
    public R save(AdvancedFileDto advancedFileDto) throws Exception {
        //return  R.ok(advancedMaterialService.save(advancedMaterial));
        return getByAdvancedFileDto(advancedFileDto, new AdvancedMaterial());
    }

    /**
     * 修改
     */
    @PutMapping
    @SysLog("修改先进技术资料")
    @ApiOperation(value = "修改先进技术资料", notes = "修改先进技术资料")
    @ApiImplicitParam(name = "AdvancedFileDto", value = "先进技术资料文件上传对象", required = true, dataType = "json", paramType = "path")
    //public R updateById(@RequestBody AdvancedMaterial advancedMaterial) throws Exception {
    public R updateById(AdvancedFileDto advancedFileDto) throws Exception {
        AdvancedMaterial advancedMaterial = advancedMaterialService.getById(advancedFileDto.getId());
        if (advancedMaterial == null) {
            return R.failed("先进技术资料不存在，修改失败！");
        }
        return getByAdvancedFileDto(advancedFileDto, advancedMaterial);
        //return  R.ok(advancedMaterialService.updateById(advancedMaterial));
    }

    /**
     * 删除
     *
     * @param advancedMaterialId
     * @return R
     */
    @DeleteMapping("/{advancedMaterialId}")
    @SysLog("根据id删除先进技术资料")
    @ApiOperation(value = "根据id删除先进技术资料", notes = "根据id删除先进技术资料")
    @ApiImplicitParam(name = "advancedMaterialId", value = "id", required = true, dataType = "int", paramType = "path")
    public R removeById(@PathVariable Integer advancedMaterialId) {
        AdvancedMaterial advancedMaterial = advancedMaterialService.getById(advancedMaterialId);
        if (advancedMaterial == null) {
            return R.failed("先进技术资料不存在，删除失败！");
        }
        ScUser u = SecurityUtils.getUser();
        advancedMaterial.setUserid(u.getId());
        advancedMaterial.setUpdateTime(new Date());
        advancedMaterial.setDelFlag("4");
        return R.ok(advancedMaterialService.updateById(advancedMaterial));
    }

    /**
     * 根据文件上传对象更新先进技术资料信息
     */
    public R getByAdvancedFileDto(AdvancedFileDto advancedFileDto, AdvancedMaterial advancedMaterial) throws Exception {

        //更新先进技术资料对象
        ScUser u = SecurityUtils.getUser();
        if (advancedMaterial.getId() == null) { //新增时，设置部门id，注销标志
            advancedMaterial.setDeptId(u.getDeptId());
            advancedMaterial.setDelFlag("1");
        }
        advancedMaterial.setUserid(u.getId());
        advancedMaterial.setUpdateTime(new Date());
        advancedMaterial.setIndustryCode(advancedFileDto.getIndustryCode());
        advancedMaterial.setIndustryName(advancedFileDto.getIndustryName());

        //设置行业编码
        if (advancedMaterial.getIndustryName() != null) {
            TradeType tradeType = new TradeType();
            tradeType.setName(advancedMaterial.getIndustryName());
            List<TradeType> newTradeTypeList = tradeTypeService.list(Wrappers.query(tradeType));
            if (newTradeTypeList.size() > 0 && newTradeTypeList.get(0) != null) {
                advancedMaterial.setIndustryCode(newTradeTypeList.get(0).getCode());
            }
        }

        MultipartFile file = advancedFileDto.getFile();
        if (file == null) {
            //return R.failed("文件不存在，更新先进技术资料信息失败");
            advancedMaterial.setTechName(advancedFileDto.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());
            //获取文件名称（不含文件后缀）
            String[] strings = fileName.split("\\.");
            String newFileName = strings[0];
            //fileName + "<" + uuid   文件名、uuid的拼接
            advancedMaterial.setFile(fileName + "<" + uuid);
            advancedMaterial.setFileSize(fileSize);
            advancedMaterial.setTechName(advancedFileDto.getFileName() != null ? advancedFileDto.getFileName() : newFileName);
        }

        boolean flag = advancedMaterialService.saveOrUpdate(advancedMaterial);
        //return flag ? R.ok(fileName + "<" + uuid) : R.failed("更新先进技术资料信息失败！");
        return R.ok(flag);
    }

}
