package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.dto.TStandardsRegulationsDto;
import com.nantian.cloud.jljc.entity.TStandardsRegulations;
import com.nantian.cloud.jljc.service.TStandardsRegulationsService;
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.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

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

@CrossOrigin
@AllArgsConstructor
@RestController
@Api(value = "TStandardsRegulations", tags = "标准法律法规")
@RequestMapping("/tStandardsRegulations")
public class TStandardsRegulationsController {

    @Autowired
    private TStandardsRegulationsService tStandardsRegulationsService;
    @Autowired
    private MinioTemplate minioTemplate;

    /**
     * 分页查询标准法律法规
     */
    @SysLog("分页查询标准法律法规")
    @ApiOperation(value = "分页查询标准法律法规", notes = "分页查询标准法律法规")
    @GetMapping("/selectall")
    @ApiImplicitParam(value = "标准法规", name = "tStandardsRegulations（查询条件：标准名name、所属系统tag、" +
            "类型type、文件状态state）", required = false, paramType = "path")
    public R selectall(Page page, TStandardsRegulations tStandardsRegulations) {
        return R.ok(tStandardsRegulationsService.selectall(page, tStandardsRegulations));
    }

    /**
     * 根据id获取标准法律法规
     */
    @SysLog("根据id获取标准法律法规")
    @GetMapping("/getById/{tStandardsRegulationsId}")
    @ApiOperation(value = "根据id获取标准法律法规", notes = "根据id获取标准法律法规")
    @ApiImplicitParam(name = "tStandardsRegulationsId", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("tStandardsRegulationsId") Integer tStandardsRegulationsId) {
        return R.ok(tStandardsRegulationsService.getById(tStandardsRegulationsId));
    }

    /**
     * 删除法规
     */
    @SysLog("删除标准法规")
    @DeleteMapping("/delete/{tStandardsRegulationsId}")
    @ApiOperation(value = "删除标准法规", notes = "删除标准法规")
    @ApiImplicitParam(name = "tStandardsRegulationsId", value = "标准法规id", required = true, dataType = "int", paramType = "path")
    public R delete(@PathVariable("tStandardsRegulationsId") Integer tStandardsRegulationsId) {
        TStandardsRegulations tStandardsRegulations = tStandardsRegulationsService.getById(tStandardsRegulationsId);
        if (tStandardsRegulations == null) {
            return R.failed("法律法规不存在，删除失败");
        }

        /*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        try {
            tStandardsRegulations.setUpdateTime(df.parse(df.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return tStandardsRegulationsService.deleteall(tStandardsRegulations);
        */

        ScUser u = SecurityUtils.getUser();
        tStandardsRegulations.setDelFlag("4");
        tStandardsRegulations.setUserid(u.getId());
        tStandardsRegulations.setUpdateTime(new Date());
        return R.ok(tStandardsRegulationsService.updateById(tStandardsRegulations));
    }


    /**
     * 根据文件对象更新标准法规
     */
    @PostMapping("/renew")
    @SysLog("根据文件对象更新标准法规")
    @ApiOperation(value = "根据文件对象更新标准法规", notes = "根据文件对象更新标准法规")
    @ApiImplicitParam(name = "TStandardsRegulationsDto", value = "标准法律法规文件上传对象", required = true, dataType = "boolean", paramType = "path")
    public R getByAdvancedFileDto(TStandardsRegulationsDto tStandardsRegulationsDto) throws Exception {
        TStandardsRegulations tStandardsRegulations = new TStandardsRegulations();
        TStandardsRegulations oldRegulations = tStandardsRegulationsService.getById(tStandardsRegulationsDto.getId());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式

        //更新标准法规
        ScUser u = SecurityUtils.getUser();
        if (oldRegulations == null) { //新增时，设置部门id，注销标志
            tStandardsRegulations.setDeptId(u.getDeptId());
            tStandardsRegulations.setDelFlag("1");
        } else { //修改时，设置主键id
            tStandardsRegulations.setId(oldRegulations.getId());
        }
        tStandardsRegulations.setUserid(u.getId());
        tStandardsRegulations.setUpdateTime(new Date());
        tStandardsRegulations.setTag(tStandardsRegulationsDto.getTag());
        tStandardsRegulations.setName(tStandardsRegulationsDto.getName());
        tStandardsRegulations.setFile(tStandardsRegulationsDto.getFile());
        tStandardsRegulations.setType(tStandardsRegulationsDto.getType());
        tStandardsRegulations.setState(tStandardsRegulationsDto.getState());
        tStandardsRegulations.setRemarks(tStandardsRegulationsDto.getRemarks());
        if (tStandardsRegulationsDto.getPublishTime() != null && !"".equals(tStandardsRegulationsDto.getPublishTime())) {
            tStandardsRegulations.setPublishTime(df.parse(tStandardsRegulationsDto.getPublishTime()));
        }
        if (tStandardsRegulationsDto.getExecuteTime() != null && !"".equals(tStandardsRegulationsDto.getExecuteTime())) {
            tStandardsRegulations.setExecuteTime(df.parse(tStandardsRegulationsDto.getExecuteTime()));
        }

        MultipartFile file = tStandardsRegulationsDto.getFileStream();
        if (file != null) {
            //上传文件
            String uuid = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename();    //文件名（含后缀）
            String fileSize = getFileSize(file.getSize());   //文件大小
            //minioTemplate.putObject("jljc", uuid, inputStream);
            minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");

            //获取文件名称（不含文件后缀）
            String[] strings = fileName.split("\\.");
            String newFileName = strings[0];
            tStandardsRegulations.setFile(fileName + "<" + uuid);
            tStandardsRegulations.setFileName(newFileName);
            tStandardsRegulations.setFileSize(fileSize);
        }

        boolean flag;
        if(oldRegulations == null){//新增
            flag = tStandardsRegulationsService.save(tStandardsRegulations);
        }else{
            flag = tStandardsRegulationsService.updateByRegulations(tStandardsRegulations);
        }
        //return flag ? R.ok(fileName + "<" + uuid) : R.failed("更新先进技术资料信息失败！");
        return R.ok(flag);
    }


    /**
     * 修改标准法规文件
     *
     * @param
     * @return
     */
    @PutMapping("/updatefile")
    @SysLog("修改标准法规文件")
    @ApiOperation(value = "修改标准法规文件", notes = "修改标准法规文件")
    @ApiImplicitParam(name = "tStandardsRegulations", value = "tStandardsRegulations", required = true, dataType = "boolean", paramType = "path")
    public Boolean update(Long id, @RequestParam("file") MultipartFile file) throws IOException {

        TStandardsRegulations tStandardsRegulations = new TStandardsRegulations();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        // System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        try {
            tStandardsRegulations.setUpdateTime(df.parse(df.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tStandardsRegulations.setId(id);
        //System.out.println(file.getBytes()+"文件转码");
        tStandardsRegulations.setFileName(file.getOriginalFilename());

        //法律法规文件
        //tStandardsRegulations.setFile(file.getBytes());

        return tStandardsRegulationsService.updatefile(tStandardsRegulations);
    }

    /**
     * 修改标准法规
     *
     * @param
     * @return
     */
    @PutMapping("/updateAll")
    @SysLog("修改标准法规")
    @ApiOperation(value = "修改标准法规", notes = "修改标准法规")
    @ApiImplicitParam(name = "tStandardsRegulations", value = "tStandardsRegulations", required = true, dataType = "boolean", paramType = "path")
    public Boolean update(@RequestBody TStandardsRegulations tStandardsRegulations) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        // System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        try {
            tStandardsRegulations.setUpdateTime(df.parse(df.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return tStandardsRegulationsService.updateall(tStandardsRegulations);
    }

    /**
     * 添加标准法规
     *
     * @param
     * @return
     */
    @PostMapping("/insertall")
    @SysLog("添加标准法规")
    @ApiOperation(value = "添加标准法规", notes = "添加标准法规")
    @ApiImplicitParam(name = "tStandardsRegulations", value = "tStandardsRegulations", required = true, dataType = "boolean", paramType = "path")
    public Long insertall(@RequestBody TStandardsRegulations tStandardsRegulations) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        // System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        try {
            tStandardsRegulations.setUpdateTime(df.parse(df.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int rt = tStandardsRegulationsService.insertall(tStandardsRegulations);
        if (rt > 0) {
            return tStandardsRegulations.getId();
        } else {
            return null;
        }
    }


    /**
     * 添加标准法规文件
     *
     * @param
     * @return
     */
    @GetMapping("/selectFile")
    @SysLog("添加标准法规文件")
    @ApiOperation(value = "添加标准法规文件", notes = "添加标准法规文件")
    @ApiImplicitParam(name = "tStandardsRegulations", value = "tStandardsRegulations", required = true, dataType = "MultipartFile", paramType = "path")
    public HashMap<String, Object> selectFile(@RequestBody TStandardsRegulations tStandardsRegulations) throws IOException {

        tStandardsRegulationsService.selectFile(tStandardsRegulations);

        byte[] testFile = new byte[1024];

        //法律法规文件流
        //testFile = tStandardsRegulationsService.selectFile(tStandardsRegulations).getFile();

        InputStream inputStream = new ByteArrayInputStream(testFile);
        InputStreamReader input = new InputStreamReader(inputStream, "GB2312");
        BufferedReader bf = new BufferedReader(input);
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = bf.readLine()) != null) {
            sb.append(line);
        }

        System.out.println(sb.toString());
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("filename", tStandardsRegulationsService.selectFile(tStandardsRegulations).getFileName());
        map.put("file", sb);
        return map;
    }


}
