package com.nantian.cloud.jljc.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.RecordCertificateManager;
import com.nantian.cloud.jljc.service.RecordCertificateManagerService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

import static com.nantian.cloud.jljc.vo.util.ImageToBase64Util.convertFileToBase64;

/**
 * 备案管理-证书管理
 *
 * @date 2020-09-03
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/recordCertificateManager")
@Api(value = "recordCertificateManager", tags = "备案管理-证书管理")
public class RecordCertificateManagerController {
    private final RecordCertificateManagerService recordCertificateManagerService;
    private final MinioTemplate minioTemplate;


    /**
     * 根据能源管理人员id获取人员证书管理信息
     */
    @GetMapping("/personId")
    @SysLog("根据能源管理人员id获取人员证书管理信息")
    @ApiOperation(value = "根据能源管理人员id获取人员证书管理信息", notes = "根据能源管理人员id获取人员证书管理信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path")
    })
    public R getByPersonId(Long id, Page page) {
        IPage personManagerList = recordCertificateManagerService.getCertificateByPage(page, id);
        if (personManagerList == null) {
            return R.failed("获取人员证书管理信息失败！");
        } else {
            List<RecordCertificateManager> records = personManagerList.getRecords();
            List<RecordCertificateManager> newRecords = new ArrayList<>();
            for (RecordCertificateManager record : records) {
                /*if (record.getCertificatePicture() != null) {
                    record.setCertificatePictureBase64Str(Base64.getEncoder().encodeToString(record.getCertificatePicture()));
                }*/
                newRecords.add(record);
            }
            personManagerList.setRecords(newRecords);
            return R.ok(personManagerList);
        }
    }

    /**
     * 根据id获取人员证书管理信息
     */
    @GetMapping("/getById/{id}")
    @SysLog("根据id获取人员证书管理信息")
    @ApiOperation(value = "根据id获取人员证书管理信息", notes = "根据id获取人员证书管理信息")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(@PathVariable("id") Long id) {
        //人员信息
        RecordCertificateManager personManager = recordCertificateManagerService.getById(id);
        /*byte[] pictureByte = personManager.getCertificatePicture();
        if (pictureByte != null) {
            personManager.setCertificatePictureBase64Str(Base64.getEncoder().encodeToString(pictureByte));
        }*/
        return personManager != null ? R.ok(personManager) : R.failed("获取人员证书管理信息失败！");
    }

    /**
     * 新增/修改人员证书管理信息
     */
    @PostMapping("addOrUp")
    @SysLog("新增/修改人员证书管理信息")
    @ApiOperation(value = "新增/修改人员证书管理信息", notes = "新增/修改人员证书管理信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "证书文件", required = false, dataType = "File", paramType = "path"),
            @ApiImplicitParam(name = "dateStr", value = "证书获取时间", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "RecordCertificateManager", value = "人员证书管理信息对象", required = true, dataType = "json", paramType = "path")
    })
    public R addOrUp(RecordCertificateManager recordCertificateManager, MultipartFile file, String dateStr) throws Exception {

        log.error("新增/修改人员证书管理信息：{}，##文件：{}，##时间：{}", recordCertificateManager, file, dateStr);

        ScUser u = SecurityUtils.getUser();
        recordCertificateManager.setUpdateId((long) u.getId());
        recordCertificateManager.setUpdateDate(new Date());
        if (recordCertificateManager.getId() == null) { //新增
            recordCertificateManager.setDeleteFlag("1");
            recordCertificateManager.setDeptId(u.getDeptId());
        }

        if (dateStr != null && !"".equals(dateStr)) {
            recordCertificateManager.setCertificateDate(new Date(dateStr)); //Thu Sep 10 2020 00:00:00 GMT+0800 (中国标准时间)
        }
        if (file != null) {
            if (file.getSize() > 0) {
                //证书文件
                recordCertificateManager.setCertificatePicture(getFileUrl(file));
            }
        }
        return R.ok(recordCertificateManagerService.saveOrUpdate(recordCertificateManager));
    }


    public String getFileUrl(MultipartFile file) throws Exception {
        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");
        return fileName + "<" + uuid;
    }


    /**
     * 新增人员证书管理信息
     */
    @PostMapping("add")
    @SysLog("新增人员证书管理信息")
    @ApiOperation(value = "新增人员证书管理信息", notes = "新增人员证书管理信息")
    @ApiImplicitParam(name = "RecordCertificateManager", value = "人员证书管理信息对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody RecordCertificateManager recordCertificateManager) {
        String base64Str = recordCertificateManager.getCertificatePictureUrl();
        if (null != base64Str && "" != base64Str) {
            //recordCertificateManager.setCertificatePicture(Base64.getDecoder().decode(base64Str));
        }
        recordCertificateManager.setUpdateDate(new Date());
        recordCertificateManager.setDeleteFlag("1");
        boolean flag = recordCertificateManagerService.addCertificate(recordCertificateManager);
        return flag ? R.ok("新增人员证书管理信息成功") : R.failed("新增人员证书管理信息失败");
    }

    /**
     * 根据id修改人员证书管理信息
     */
    @PutMapping("update")
    @SysLog("根据id修改人员证书管理信息")
    @ApiOperation(value = "根据id修改人员证书管理信息", notes = "根据id修改人员证书管理信息")
    @ApiImplicitParam(name = "RecordCertificateManager", value = "人员证书管理信息对象", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody RecordCertificateManager recordCertificateManager) {
        String base64Str = recordCertificateManager.getCertificatePictureUrl();
        if (null != base64Str && "" != base64Str) {
            //recordCertificateManager.setCertificatePicture(Base64.getDecoder().decode(base64Str));
        }
        recordCertificateManager.setUpdateDate(new Date());
        boolean flag = recordCertificateManagerService.updateCertificateById(recordCertificateManager);
        return flag ? R.ok("修改人员证书管理信息成功") : R.failed("修改人员证书管理信息失败");
    }

    /**
     * 根据id删除人员证书管理信息
     */
    @DeleteMapping("delete")
    @SysLog("根据id删除人员证书管理信息")
    @ApiOperation(value = "根据id删除人员证书管理信息", notes = "根据id删除人员证书管理信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "id", value = "证书信息id", required = true, dataType = "string", paramType = "path")
    })
    public R removeById(Long userId, Long id) {
        RecordCertificateManager recordCertificateManager = new RecordCertificateManager();
        if (id == null) {
            return R.failed("证书信息id不能为空！");
        } else {
            recordCertificateManager.setId(id);
        }
        if (userId != null) {
            recordCertificateManager.setUpdateId(userId);
        }
        recordCertificateManager.setUpdateDate(new Date());
        recordCertificateManager.setDeleteFlag("4");
        boolean flag = recordCertificateManagerService.removeByCertificateId(recordCertificateManager);
        return flag ? R.ok("删除人员证书管理信息成功") : R.failed("删除人员证书管理信息失败");
    }
}
