package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.TPolicy;
import com.nantian.cloud.jljc.service.TPolicyService;
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.Date;
import java.util.UUID;


/**
 * 政策文件
 *
 * @since 2021-02-03
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tPolicy")
@Api(value = "tPolicy", tags = "政策文件")
public class TPolicyController {
    private final TPolicyService tPolicyService;
    private final MinioTemplate minioTemplate;

    /**
     * 分页获取政策文件（政府）
     */
    @GetMapping("/pageGov")
    @SysLog("分页获取政策文件（政府）")
    @ApiOperation(value = "分页获取政策文件（政府）", notes = "分页获取政策文件（政府）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "tPolicy", value = "查询条件（名称policyTitle、发布人publisher、发布单位issued、" +
                    "所属单位（1：节能，2：计量，3：公共机构）userDept、附件名fileName）", required = false, dataType = "json", paramType = "path")
    })
    public R gettPolicyPageGov(Page page, TPolicy tPolicy) {
        if (tPolicy.getUserDept() == null || "".equals(tPolicy.getUserDept())) {
            return R.failed("userDept不能为空!");
        }
        return R.ok(tPolicyService.getPageGov(page, tPolicy));
    }

    /**
     * 分页获取政策文件（企业）
     */
    @GetMapping("/pageCmp")
    @SysLog("分页获取政策文件（企业）")
    @ApiOperation(value = "分页获取政策文件（企业）", notes = "分页获取政策文件（企业）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "tPolicy", value = "查询条件（名称policyTitle、发布人publisher、发布单位issued、" +
                    "所属单位（1：节能，2：计量，3：公共机构）userDept、附件名fileName）", required = false, dataType = "json", paramType = "path")
    })
    public R gettPolicyPageCmp(Page page, TPolicy tPolicy) {
        return R.ok(tPolicyService.getPageCmp(page, tPolicy));
    }

    /**
     * 根据id获取政策文件
     */
    @GetMapping("/getById")
    @SysLog("根据id获取政策文件")
    @ApiOperation(value = "根据id获取政策文件", notes = "根据id获取政策文件")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(Integer id) {
        return R.ok(tPolicyService.getById(id));
    }

    /**
     * 更新政策文件
     */
    @PostMapping("/update")
    @SysLog("更新政策文件")
    @ApiOperation(value = "更新政策文件", notes = "更新政策文件")
    @ApiImplicitParam(name = "tPolicyFileDto", value = "政策文件文件上传对象", required = true)
    public R saveOrUpPolicy(MultipartFile file, TPolicy tPolicy) throws Exception {

        if (tPolicy.getUserDept() == null || "".equals(tPolicy.getUserDept())) {
            return R.failed("userDept不能为空!");
        }

        ScUser u = SecurityUtils.getUser();
        if (tPolicy.getId() != null) { //修改
            tPolicy.setUserid(u.getId());
            tPolicy.setUpdateTime(new Date());
        } else { //新增
            tPolicy.setUserid(u.getId());
            tPolicy.setDeptId(u.getDeptId());
            tPolicy.setDelFlag("1");
            tPolicy.setCreatTime(new Date());
            tPolicy.setUpdateTime(new Date());
        }

        if (file != null) {
            //上传文件
            String uuid = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename(); //文件名
            minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");
            //fileName + "<" + uuid   文件名、uuid的拼接
            tPolicy.setFileUrl(fileName + "<" + uuid);

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

        return R.ok(tPolicyService.saveOrUpdate(tPolicy));
    }

    /**
     * 根据id删除政策文件
     */
    @DeleteMapping("/delete")
    @SysLog("根据id删除政策文件")
    @ApiOperation(value = "根据id删除政策文件", notes = "根据id删除政策文件")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R removeById(Integer id) {
        TPolicy tPolicy = tPolicyService.getById(id);
        if (tPolicy == null) {
            return R.failed("政策文件不存在，删除失败！");
        }
        ScUser u = SecurityUtils.getUser();
        tPolicy.setUserid(u.getId());
        tPolicy.setUpdateTime(new Date());
        tPolicy.setDelFlag("4");
        return R.ok(tPolicyService.updateById(tPolicy));
    }

}
