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.entity.EnterpriseInfo;
import com.nantian.cloud.jljc.entity.TProjectEnergySaving;
import com.nantian.cloud.jljc.service.EnterpriseInfoService;
import com.nantian.cloud.jljc.service.TProjectEnergySavingService;
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.annotation.Inner;
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.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;


/**
 * 固定资产投资项目节能审查
 *
 * @date 2020-09-21
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tProjectEnergySaving")
@Api(value = "tProjectEnergySaving", tags = "固定资产投资项目节能审查")
public class TProjectEnergySavingController {
    @Autowired
    private TProjectEnergySavingService tProjectEnergySavingService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private EnterpriseInfoService enterpriseInfoService;


    /**
     * 分页查询
     */
    @GetMapping("/pageCmp")
    @SysLog("分页获取固定资产投资项目节能审查")
    @ApiOperation(value = "分页获取固定资产投资项目节能审查", notes = "分页获取固定资产投资项目节能审查")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "tProjectEnergySaving", value = "固定资产投资项目节能审查对象（查询条件：项目名称projectName、" +
                    "项目状态state 1申请,2审核、企业名称epcName、企业编码epc、项目类别projectType、处置方式action 1备案,2审批,3核准）", required = false, dataType = "json", paramType = "path")
    })
    public R getTProjectEnergySavingPageByCmp(Page page, TProjectEnergySaving tProjectEnergySaving) {
        ScUser u = SecurityUtils.getUser();
        if(StringUtils.isBlank(u.getEnterpriseCode())){
          return  R.failed("用户所属企业信用代码为空，请检查用户信息！");
        }
        tProjectEnergySaving.setEpc(u.getEnterpriseCode());
        tProjectEnergySaving.setDelFlag("1"); //筛选未删除项
        return R.ok(tProjectEnergySavingService.queryListByCmp(page, tProjectEnergySaving));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @SysLog("分页获取固定资产投资项目节能审查")
    @ApiOperation(value = "分页获取固定资产投资项目节能审查", notes = "分页获取固定资产投资项目节能审查")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "tProjectEnergySaving", value = "固定资产投资项目节能审查对象（查询条件：项目名称projectName、" +
                    "项目状态state 1申请,2审核、企业名称epcName、企业编码epc、项目类别projectType、处置方式action 1备案,2审批,3核准）", required = false, dataType = "json", paramType = "path")
    })
    public R getTProjectEnergySavingPage(Page page, TProjectEnergySaving tProjectEnergySaving) {
        tProjectEnergySaving.setDelFlag("1"); //筛选未删除项
        return R.ok(tProjectEnergySavingService.getPageScope(page, tProjectEnergySaving));
    }


    /**
     * 分页查询
     */
    @GetMapping("/page2")
    @SysLog("分页获取固定资产投资项目节能审查（政府端）")
    @ApiOperation(value = "分页获取固定资产投资项目节能审查（政府端）", notes = "分页获取固定资产投资项目节能审查（政府端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "tProjectEnergySaving", value = "固定资产投资项目节能审查对象（查询条件：项目名称projectName、" +
                    "项目状态state,1 申请,2 初审,3机构评审,4 备案、企业名称epcName、企业编码epc、项目类别projectType）", required = false, dataType = "json", paramType = "path")
    })
    public R getTProjectEnergySavingPage2(Page page, TProjectEnergySaving tProjectEnergySaving) {
        //只有申报的项目政府端才能看到 （即state为1,2,3,4政府端可以看到） state2表示为政府端
        return R.ok(tProjectEnergySavingService.getPageScope2(page, tProjectEnergySaving));
    }

    /**
     * 根据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(tProjectEnergySavingService.getById(id));
    }

    /**
     * 新增/修改固定资产投资项目节能审查
     */
    @PostMapping("/renew")
    @SysLog("新增/修改固定资产投资项目节能审查")
    @ApiOperation(value = "新增/修改固定资产投资项目节能审查", notes = "新增/修改固定资产投资项目节能审查")
    @ApiImplicitParam(name = "TProjectEnergySaving", value = "固定资产投资项目节能审查对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TProjectEnergySaving tProjectEnergySaving) {
        ScUser u = SecurityUtils.getUser();

        if (tProjectEnergySaving.getId() == null) {//新增
            tProjectEnergySaving.setDelFlag("1");
            //tProjectEnergySaving.setDeptId(u.getDeptId());
            //获取企业信息
            EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
            //企业端新增信息，添加deptid
            tProjectEnergySaving.setDeptId(info != null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
            tProjectEnergySaving.setDeptId(u.getDeptId());
            tProjectEnergySaving.setEpc(u.getEnterpriseCode());
           EnterpriseInfo enterprise = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
            if (enterprise != null) {
                tProjectEnergySaving.setEpcName(enterprise.getCmpName());
            }
            tProjectEnergySaving.setEpcName( enterpriseInfoService.getNameByCode(u.getEnterpriseCode()));
        }else{//修改
            /*if(tProjectEnergySaving.getState() != null){
                if("1".equals(tProjectEnergySaving.getState())){
                    return R.failed("固定资产投资项目已申报，修改失败！");
                }else if("2".equals(tProjectEnergySaving.getState())){
                    return R.failed("固定资产投资项目已初审，修改失败！");
                }else if("3".equals(tProjectEnergySaving.getState())){
                    return R.failed("固定资产投资项目已机构评审，修改失败！");
                }else if("4".equals(tProjectEnergySaving.getState())){
                    return R.failed("固定资产投资项目已备案，修改失败！");
                }else{}
            }*/
            //政府审核不过，企业端需要修改，stat：1/2/3 修改放过；政府一旦备案就不可修改
            if("4".equals(tProjectEnergySaving.getState())){
                return R.failed("固定资产投资项目已备案，修改失败！");
            }
        }

        tProjectEnergySaving.setUserid(u.getId());
        tProjectEnergySaving.setUpdateTime(new Date());
        return R.ok(tProjectEnergySavingService.saveOrUpdate(tProjectEnergySaving));
    }

    /**
     * 企业申报固定资产投资项目
     */
    @PostMapping("/submit")
    @SysLog("企业申报固定资产投资项目")
    @ApiOperation(value = "企业申报固定资产投资项目", notes = "企业申报固定资产投资项目")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R save(Long id) {

        TProjectEnergySaving tProjectEnergySaving = tProjectEnergySavingService.getById(id);
        if (tProjectEnergySaving == null) {
            return R.failed("固定资产投资项目不存在，申报失败！");
        }
        if(tProjectEnergySaving.getApplicationForm()==null){
            return R.failed("请提交附件，固定资产投资项目节能审查申请书，再申报！");
        }
        if(tProjectEnergySaving.getEnergySavingProject()==null){
            return R.failed("请提交附件，固定资产投资项目节能报告，再申报！");
        }
        if(tProjectEnergySaving.getFeasibilityStudyReport()==null){
            return R.failed("请提交附件，项目可行性研究报告（或项目申请报告或项目备案登记表），再申报！");
        }

        ScUser u = SecurityUtils.getUser();
        tProjectEnergySaving.setUserid(u.getId());
        tProjectEnergySaving.setUpdateTime(new Date());
        tProjectEnergySaving.setState("1");
        return R.ok(tProjectEnergySavingService.updateById(tProjectEnergySaving));
    }

    /**
     * 上传文件材料
     */
    @SneakyThrows
    @PostMapping("/upload")
    @ApiOperation(value = "上传文件材料", notes = "上传文件材料")
    @SysLog("上传固定资产投资项目节能审查文件材料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "type", value = "文件类型（1：附件固定资产投资项目节能审查申请书，" +
                    "2：附件固定资产投资项目节能报告，" +
                    "3：附件项目可行性研究报告（或项目申请报告或项目备案登记表）", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "file", value = "文件流", required = true, dataType = "File", paramType = "path"),
    })
    public R upload(String type, @RequestParam("file") MultipartFile file, Long id) {

        TProjectEnergySaving tProjectEnergySaving = tProjectEnergySavingService.getById(id);
        if (tProjectEnergySaving == null) {
            return R.failed("固定资产投资项目节能审查不存在，上传附件失败");
        }

        //上传文件
        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 fileUrl = fileName + "<" + uuid;
        if ("1".equals(type)) {
            //1：附件固定资产投资项目节能审查申请书
            tProjectEnergySaving.setApplicationForm(fileUrl);
        } else if ("2".equals(type)) {
            //2：附件固定资产投资项目节能报告
            tProjectEnergySaving.setEnergySavingProject(fileUrl);
        } else if ("3".equals(type)) {
            //3：附件项目可行性研究报告（或项目申请报告或项目备案登记表）
            tProjectEnergySaving.setFeasibilityStudyReport(fileUrl);
        } else {
            return R.failed("文件类型错误，上传附件失败");
        }
        ScUser u = SecurityUtils.getUser();
        tProjectEnergySaving.setUserid(u.getId());
        tProjectEnergySaving.setUpdateTime(new Date());

        boolean b = tProjectEnergySavingService.updateById(tProjectEnergySaving);
        return R.ok(fileUrl);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @SysLog("删除固定资产投资项目节能审查")
    @ApiOperation(value = "删除固定资产投资项目节能审查", notes = "删除固定资产投资项目节能审查")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R removeById(Integer id) {
        TProjectEnergySaving tProjectEnergySaving = tProjectEnergySavingService.getById(id);
        if (tProjectEnergySaving == null) {
            return R.failed("固定资产投资项目节能审查不存在，删除失败");
        }
        ScUser u = SecurityUtils.getUser();
        tProjectEnergySaving.setDelFlag("4");
        tProjectEnergySaving.setUserid(u.getId());
        tProjectEnergySaving.setUpdateTime(new Date());
        return R.ok(tProjectEnergySavingService.updateById(tProjectEnergySaving));
    }

}
