package com.nantian.cloud.jljc.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.mapper.TFaFixedAssetsMapper;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.TFaProjectVO;
import com.nantian.cloud.jljc.vo.TFaUnionPieceVo;
import com.nantian.cloud.jljc.vo.util.FileUtil;
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.annotation.Inner;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 固定资产投资项目节能审查企业项目表 前端控制器
 * </p>
 *
 * @author fyf
 * @since 2022-02-15
 */
@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("/tFaFixedAssets")
public class TFaFixedAssetsController {

    @Autowired
    TFaFixedAssetsService tFaFixedAssetsService;

    @Autowired
    TFaUnionPieceService tFaUnionPieceService;

    @Autowired
    HttpServletRequest req;

    /**
     * 接件文件
     */
    @Autowired
    TFaProjectMaterialService tFaProjectMaterialService;

    /**
     * 评审机构信息
     */
    @Autowired
    TFaAccreditingBodyService tFaAccreditingBodyService;

    /**
     * 实地踏勘文件
     */
    @Autowired
    TFaFieldReconnaissanceService tFaFieldReconnaissanceService;

    /**
     * 专家意见
     */
    @Autowired
    TFaSpecialistOpinionService tFaSpecialistOpinionService;

    /**
     * 技术审查报告
     */
    @Autowired
    TFaTechnologyReportService tFaTechnologyReportService;

    /**
     * 资环处接件
     */
    @Autowired
    TFaInvestmentService tFaInvestmentService;

    /**
     * 合法性审查报告
     */
    @Autowired
    TFaLegalInvestigateService tFaLegalInvestigateService;

    /**
     * 职能部门意见
     */
    @Autowired
    TFaFunctionalOpinionService tFaFunctionalOpinionService;

    /**
     * 现场检查记录
     */
    @Autowired
    TFaProcessControlService tFaProcessControlService;

    /**
     * 事后验收报告
     */
    @Autowired
    TFaCheckAcceptService tFaCheckAcceptService;

    @Autowired
    MinioTemplate minioTemplate;

    /**
     * 获取分页数据
     * @param page
     * @param tFaFixedAssets
     * @return
     */
    @GetMapping("/page")
    @SysLog("分页获取固定资产投资项目节能审查企业项目表")
    public R getPage(Page page, TFaFixedAssets tFaFixedAssets){
//        tFaFixedAssets.setDelFlag(1);
        return R.ok(tFaFixedAssetsService.getPage(page, tFaFixedAssets,new DataScope()));
    }

    /**
     * 获取项目详细信息
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    @SysLog("根据id获取固定资产投资项目节能审查企业项目表")
    public R getInfo(@PathVariable Integer id){
        return R.ok(tFaFixedAssetsService.getById(id));
    }

    /**
     * 项目状态(1.接件，2.评审机构评审，3.资环处评审，4.项目评审完毕（项目实施），0.退件)
     * @param tFaFixedAssets
     * @return
     */
    @PutMapping("/update")
    @SysLog("修改固定资产投资项目状态")
    public R update(@RequestBody TFaFixedAssets tFaFixedAssets){
        ScUser u = SecurityUtils.getUser();
        tFaFixedAssets.setUserId(u.getId());
        tFaFixedAssets.setDeptId(u.getDeptId());
        tFaFixedAssets.setUpdateTime(new Date());
        tFaFixedAssets.setDelFlag(1);
        tFaFixedAssetsService.updateById(tFaFixedAssets);
        return R.ok();
    }

    /**
     * 项目状态(1.接件，2.评审机构评审，3.资环处评审，4.项目评审完毕（项目实施），0.退件)
     * @param tFaFixedAssets
     * @return
     */
    @PostMapping("/save")
    @SysLog("保存固定资产投资项目状态")
    public R save(@RequestBody TFaFixedAssets tFaFixedAssets){
        ScUser u = SecurityUtils.getUser();
        tFaFixedAssets.setUserId(u.getId());
        tFaFixedAssets.setDeptId(u.getDeptId());
        tFaFixedAssets.setUpdateTime(new Date());
        tFaFixedAssets.setDelFlag(1);
        tFaFixedAssets.setStatusData(9);
        tFaFixedAssetsService.save(tFaFixedAssets);
        return R.ok();
    }

    @DeleteMapping("/delete")
    @SysLog("删除固定资产投资项目状态")
    public R removeById(Integer id){
        ScUser u = SecurityUtils.getUser();
        TFaFixedAssets tFaFixedAssets = tFaFixedAssetsService.getById(id);
        tFaFixedAssets.setDelFlag(4);
        tFaFixedAssets.setUserId(u.getId());
        tFaFixedAssets.setDeptId(u.getDeptId());
        tFaFixedAssets.setUpdateTime(new Date());
        tFaFixedAssetsService.updateById(tFaFixedAssets);
        return R.ok();
    }

    /**
     * 根据项目Id获取该项目全部文件资料
     * @param id
     * @return
     */
    @GetMapping("/getFileInfoById/{id}")
    @SysLog("根据项目Id获取该项目全部文件资料")
    public R getFileInfoById(@PathVariable("id") Integer id){
        Map<String,List<String>> fileMap = new HashMap<>();
        //查询接件中的文件
        TFaUnionPiece tFaUnionPiece = tFaUnionPieceService.getById(id);
        Integer personId = tFaUnionPiece.getId();
        List<TFaProjectMaterial> file = tFaProjectMaterialService.list(
                new QueryWrapper<TFaProjectMaterial>()
                        .eq("union_piece_id", personId));
        List<String> PMfileList = new ArrayList<>();
        if (file.size() > 0){
            for (TFaProjectMaterial tFaProjectMaterial : file) {
                PMfileList.add(tFaProjectMaterial.getOldFileName());
            }
        }
        //查询实地探勘中的文件
        List<TFaFieldReconnaissance> tFaFieldReconnaissances = tFaFieldReconnaissanceService.list(
                new QueryWrapper<TFaFieldReconnaissance>().eq("project_id", id));
        List<String> FRfileList = new ArrayList<>();
        if (tFaFieldReconnaissances.size() > 0){
            for (TFaFieldReconnaissance tFaFieldReconnaissance : tFaFieldReconnaissances) {
                FRfileList.add(tFaFieldReconnaissance.getOldFileName());
            }
        }
        //查询专家及专家组意见
        List<TFaSpecialistOpinion> tFaSpecialistOpinion = tFaSpecialistOpinionService.list(new QueryWrapper<TFaSpecialistOpinion>()
                .eq("project_id", id));
        List<String> SOfileList = new ArrayList<>();
        if (tFaSpecialistOpinion.size() > 0){
            for (TFaSpecialistOpinion faSpecialistOpinion : tFaSpecialistOpinion) {
                SOfileList.add(faSpecialistOpinion.getOldFileName());
            }
        }
        //查询技术审查报告
        List<TFaTechnologyReport> tFaTechnologyReport = tFaTechnologyReportService.list(new QueryWrapper<TFaTechnologyReport>()
                .eq("project_id", id));
        List<String> TRfileList = new ArrayList<>();
        if (tFaTechnologyReport.size() > 0){
            for (TFaTechnologyReport faTechnologyReport : tFaTechnologyReport) {
                TRfileList.add(faTechnologyReport.getOldFileName());
            }
        }
        //查询合法性审查报告
        List<TFaLegalInvestigate> tFaLegalInvestigate = tFaLegalInvestigateService.list(new QueryWrapper<TFaLegalInvestigate>()
                .eq("project_id", id));
        List<String> LIfileList = new ArrayList<>();
        if (tFaLegalInvestigate.size() > 0){
            for (TFaLegalInvestigate faLegalInvestigate : tFaLegalInvestigate) {
                LIfileList.add(faLegalInvestigate.getOldFileName());
            }
        }
        //查询职能部门意见
        List<TFaFunctionalOpinion> tFaFunctionalOpinion = tFaFunctionalOpinionService.list(new QueryWrapper<TFaFunctionalOpinion>()
                .eq("project_id", id));
        List<String> FOfileList = new ArrayList<>();
        if (tFaFunctionalOpinion.size() > 0){
            for (TFaFunctionalOpinion faFunctionalOpinion : tFaFunctionalOpinion) {
                FOfileList.add(faFunctionalOpinion.getOldFileName());
            }
        }
        //查询现场检查记录
        List<TFaProcessControl> tFaProcessControl = tFaProcessControlService.list(new QueryWrapper<TFaProcessControl>()
                .eq("project_id", id));
        List<String> PCfileList = new ArrayList<>();
        if (tFaProcessControl.size() > 0){
            for (TFaProcessControl faProcessControl : tFaProcessControl) {
                PCfileList.add(faProcessControl.getOldFileName());
            }
        }
        //查询事后验收报告
        List<TFaCheckAccept> tFaCheckAccept = tFaCheckAcceptService.list(new QueryWrapper<TFaCheckAccept>()
                .eq("project_id", id));
        List<String> CAfileList = new ArrayList<>();
        if (tFaCheckAccept.size() > 0){
            for (TFaCheckAccept faCheckAccept : tFaCheckAccept) {
                CAfileList.add(faCheckAccept.getOldFileName());
            }
        }
        fileMap.put("接件", PMfileList);
        fileMap.put("实地踏勘",FRfileList);
        fileMap.put("专家及专家组意见",SOfileList);
        fileMap.put("技术审查报告",TRfileList);
        fileMap.put("合法性审查报告",LIfileList);
        fileMap.put("职能部门意见",FOfileList);
        fileMap.put("现场检查记录",PCfileList);
        fileMap.put("事后验收报告",CAfileList);
        return R.ok(fileMap);
    }

    /**
     *获取项目进程信息
     * @param
     * @return
     */
    @GetMapping("/getProjectInfo")
    @SysLog("获取项目进程信息")
    public R getProjectInfo(Page page, TFaFixedAssets tFaFixedAssets){
        ScUser u = SecurityUtils.getUser();
        tFaFixedAssets.setDelFlag(1);
        IPage<TFaProjectVO> pageData = tFaFixedAssetsService.getProjectInfo(page, tFaFixedAssets,new DataScope());
        pageData.getRecords().forEach(r -> {
            r.setCanDo(r.getDeptId().equals(u.getDeptId()) ? 1 : 0);
            r.setEventStatus(r.getEventName() == null ? 0 :1);
            r.setProcessStatus(r.getInproTime() == null ? 0 : 1);
        });
        return R.ok(pageData);
    }

    @PutMapping("/back")
    public R back(@RequestBody TFaFixedAssets tFaFixedAssets){
        ScUser u = SecurityUtils.getUser();
        tFaFixedAssets.setCause(tFaFixedAssets.getCause());
        tFaFixedAssets.setUserId(u.getId());
        tFaFixedAssets.setUpdateTime(new Date());
        tFaFixedAssets.setDeptId(u.getDeptId());
        tFaFixedAssets.setProjectStatus(5);
        tFaFixedAssets.setStatusData(0);
        tFaFixedAssetsService.updateById(tFaFixedAssets);
        return R.ok();
    }

    //导出Excel模板
    @Inner(value = false)
    @GetMapping("/download")
    public R download(HttpServletResponse response) throws IOException {
        InputStream templateObject = minioTemplate.getObject("jljc", "fixedAssetsPiece.xlsx");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
//        response.setHeader("Content-disposition", URLEncoder.encode(file.getName(), "UTF-8"));

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("固定资产节能审查材料导入模板.xlsx", "UTF-8"));
        response.setHeader("Pragma", "No-cache");
        IoUtil.copy(templateObject, response.getOutputStream());

//        URL url = new ClassPathResource("mouldFile/fixedAssetsPiece.xlsx").getURL();
//        File file = new File(url.getFile());
//        if (!file.exists()){
//            return R.failed("路径有误，文件不存在！");
//        }
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/x-download;charset=utf-8");
//        response.setHeader("Content-disposition", URLEncoder.encode(file.getName(), "UTF-8"));
//
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("固定资产节能审查材料导入模板.xlsx", "UTF-8"));
//        response.setHeader("Pragma", "No-cache");
//
//        //从内存中写出来
//        OutputStream outputStream = response.getOutputStream();
//        outputStream.write(FileUtil.file2byte(file));
//        outputStream.flush();
//        outputStream.close();
        return R.ok("模板导出成功!");
    }

    //Excel导入
    @PostMapping("/excelImport")
    public R excelImport(@RequestParam("file") MultipartFile multipartFile) throws FileFormatException {
        tFaFixedAssetsService.excelImport(multipartFile);
        return R.ok();
    }

}
