package com.nantian.cloud.jljc.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nantian.cloud.jljc.entity.DictRegion;
import com.nantian.cloud.jljc.entity.TFaCheckAccept;
import com.nantian.cloud.jljc.entity.TFaLegalInvestigate;
import com.nantian.cloud.jljc.entity.TFaProcessControl;
import com.nantian.cloud.jljc.service.DictRegionService;
import com.nantian.cloud.jljc.service.TFaCheckAcceptService;
import com.nantian.cloud.jljc.vo.TFaTotalDataVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.data.datascope.DataScope;
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 lombok.AllArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 固定资产投资项目节能审查事后验收报告表 前端控制器
 * </p>
 *
 * @author fyf
 * @since 2022-02-15
 */
@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("/tFaCheckAccept")
public class TFaCheckAcceptController {

    @Autowired
    MinioTemplate minioTemplate;

    @Autowired
    TFaCheckAcceptService tFaCheckAcceptService;

    @Autowired
    DictRegionService dictRegionService;

    @PostMapping("/fileUpload/{id}")
    @SysLog("根据id添加固定资产投资项目节能审查事后验收报告表文件")
    public R fileUpload(@PathVariable Integer id,@RequestParam("file") MultipartFile[] multipartFiles) throws Exception {
        ScUser u = SecurityUtils.getUser();
        if (multipartFiles.length > 0) {
            for (MultipartFile multipartFile : multipartFiles) {
                //获取文件名称
                String fileName = multipartFile.getOriginalFilename();
                //获取文件的后缀
                String extension = "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                //生成新的文件名称
                String newFileName = "SHYS" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                        + UUID.randomUUID().toString()
                        .replace("-", "") + extension;
                //文件的大小
                long size = multipartFile.getSize();
                //文件的类型
                String contentType = multipartFile.getContentType();
                //上传文件
                InputStream inputStream = multipartFile.getInputStream();
                minioTemplate.putObject("jljc", newFileName, inputStream, inputStream.available(), "application/octet-stream");
                //文件信息保存到数据库
                TFaCheckAccept tFaCheckAccept = new TFaCheckAccept();
                TFaCheckAccept one = tFaCheckAcceptService.getOne(
                        new QueryWrapper<TFaCheckAccept>()
                                .eq("del_flag", 1)
                                .eq("project_id", id));
                tFaCheckAccept.setDelFlag(1);
                tFaCheckAccept.setExtension(extension);
                tFaCheckAccept.setFilePath("jljc/" + newFileName);
                tFaCheckAccept.setFileSize(String.valueOf(size));
                tFaCheckAccept.setFileType(contentType);
                tFaCheckAccept.setNewFileName(newFileName);
                tFaCheckAccept.setOldFileName(fileName);
                tFaCheckAccept.setDeptId(u.getDeptId());
                tFaCheckAccept.setUpdateTime(new Date());
                tFaCheckAccept.setUserId(u.getId());
                tFaCheckAccept.setUploadTime(new Date());
                tFaCheckAccept.setId(one.getId());
                tFaCheckAcceptService.updateById(tFaCheckAccept);
                return R.ok();
            }
        } else {
            return R.failed("上传文件为空！");
        }

        return R.ok();
    }

    @GetMapping("/fileDownload/{id}")
    @SysLog("根据id下载固定资产投资项目节能审查事后验收报告表文件")
    public R fileDownload(@PathVariable("id") Integer id) throws IOException {
        TFaCheckAccept tFaCheckAccept = tFaCheckAcceptService.getById(id);
        //获取文件名
        String newFileName = tFaCheckAccept.getNewFileName();
        //文件下载
        minioTemplate.getObject("jljc",newFileName);
        return R.ok();
    }

    @DeleteMapping("/fileRemove/{id}")
    @SysLog("根据id删除固定资产投资项目节能审查事后验收报告")
    public R fileRemove(@PathVariable("id") String id) throws Exception {
        ScUser u = SecurityUtils.getUser();
        TFaCheckAccept tFaCheckAccept = tFaCheckAcceptService.getById(id);
        //获取文件名
        String newFileName = tFaCheckAccept.getNewFileName();
        tFaCheckAccept.setUserId(u.getId());
        tFaCheckAccept.setDelFlag(4);
        tFaCheckAccept.setUpdateTime(new Date());
        tFaCheckAccept.setDeptId(u.getDeptId());
        tFaCheckAcceptService.updateById(tFaCheckAccept);
        //文件删除
        minioTemplate.removeObject("jljc",newFileName);
        return R.ok();
    }

    @PostMapping("/saveOrUpdate")
    @SysLog("新增/修改固定资产投资项目节能审查事后验收报告")
    public R save(@RequestBody TFaCheckAccept tFaCheckAccept){
        ScUser u = SecurityUtils.getUser();
        TFaCheckAccept one = tFaCheckAcceptService.getOne(new QueryWrapper<TFaCheckAccept>()
                .eq("project_id", tFaCheckAccept.getProjectId())
                .eq("del_flag", 1));
        if (one == null){
            tFaCheckAccept.setDelFlag(1);
            tFaCheckAccept.setDeptId(u.getDeptId());
            tFaCheckAccept.setUserId(u.getId());
            tFaCheckAccept.setUpdateTime(new Date());
            tFaCheckAcceptService.save(tFaCheckAccept);
        }else {
            tFaCheckAcceptService.updateById(tFaCheckAccept);
        }
        return R.ok();
    }

    @GetMapping("/getInfo/{id}")
    @SysLog("根据id获取固定资产投资项目节能审查事后验收报告")
    public R getInfo(@PathVariable Integer id){

        return R.ok(tFaCheckAcceptService.getOne(new QueryWrapper<TFaCheckAccept>().eq("project_id", id).eq("del_flag",1)));
    }

    @GetMapping("/getFileList/{id}")
    @SysLog("根据id获取固定资产投资项目节能审查事后验收报告")
    public R getFileList(@PathVariable Integer id){

        List<TFaCheckAccept> tFaCheckAccepts = tFaCheckAcceptService.list(
                new QueryWrapper<TFaCheckAccept>().eq("del_flag",1)
                        .eq("project_id", id));
        return R.ok(tFaCheckAccepts);
    }

    @GetMapping("/getTotal")
    public R getTotal(String deptId){
        List<TFaTotalDataVo> total = new ArrayList<>();
        if (deptId == null){
            ScUser u = SecurityUtils.getUser();
            if (u.getDeptId() == 530000){
                total = tFaCheckAcceptService.getTotal(deptId);
            }else {
                DictRegion dictRegion = dictRegionService.getOne(new QueryWrapper<DictRegion>().eq("id", u.getDeptId()));
                total = tFaCheckAcceptService.getTotal(dictRegion.getMeaning2());
            }
        }else {
            total = tFaCheckAcceptService.getTotal(deptId);
        }
        List<String> deptList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        List<Integer> count = new ArrayList<>();
        List<BigDecimal> equiList = new ArrayList<>();
        List<BigDecimal> elecList = new ArrayList<>();
        List<BigDecimal> enerList = new ArrayList<>();
        List<BigDecimal> indiList = new ArrayList<>();
        total.forEach( t -> {
            if (t.getRealName().equals("云南")){
                nameList.add("省级");
                deptList.add(t.getDeptId());
                count.add(t.getCount());
                equiList.add(t.getEquiSum());
                elecList.add(t.getElecSum());
                enerList.add(t.getEnerSum());
                indiList.add(t.getIndiSum());
            }else {
                nameList.add(t.getRealName());
                deptList.add(t.getDeptId());
                count.add(t.getCount());
                equiList.add(t.getEquiSum());
                elecList.add(t.getElecSum());
                enerList.add(t.getEnerSum());
                indiList.add(t.getIndiSum());
            }
        });
        return R.ok(MapUtil
                .builder()
                .put("name",nameList)
                .put("equi",equiList)
                .put("elec",elecList)
                .put("ener",enerList)
                .put("indi",indiList)
                .put("dept",deptList)
                .put("count",count)
                .map());
    }
}
