package com.jeeplus.assess.program.configuration.projectList.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.assess.program.configuration.projectList.domain.ProgramProjectListInfo;
import com.jeeplus.assess.program.configuration.projectList.service.ProjectListService;
import com.jeeplus.assess.program.configuration.projectList.service.dto.*;
import com.jeeplus.assess.projectRecords.Utils.EasyPoiUtil;
import com.jeeplus.assess.workContract.domain.WorkContractInfo;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.flowable.feign.IAssessApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.assess.utils.FreemarkerUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags ="项目列表管理")
@RestController
@RequestMapping(value = "/program/projectList")
public class ProjectListController {

    @Resource
    private ProjectListService projectListService;

    /**
     * 查询当前登录人所属项目组的项目
     * @return
     */
    @ApiOperation(value = "查询当前登录人所属项目组的项目")
    @GetMapping(value = "/getOverArchiveFlag")
    public ResponseEntity<String> getOverArchiveFlag() {
        return projectListService.getOverArchiveFlag();
    }

    /**
     * 查询项目签发单完成后3天未归档项目信息
     * @return
     */
    @GetMapping("getOverdueFilingProjectList")
    public String getOverdueFilingProjectList(){
        List<ProgramProjectListInfo> listInfos = projectListService.getOverdueFilingProjectList();
        return JSON.toJSONString(listInfos);
    }

    /**
     * 修改报告归档 归档状态信息
     * @param id
     * @param archiveStatus
     * @param overArchiveStatus
     */
    @GetMapping("updateArchiveStatus")
    public void updateArchiveStatus(@RequestParam(value = "id")String id,
                                    @RequestParam(value = "archiveStatus")String archiveStatus,
                                    @RequestParam(value = "overArchiveStatus")String overArchiveStatus){
        projectListService.updateArchiveStatus(id, archiveStatus, overArchiveStatus);
    }

    /**
     * 新增/修改
     */
    @ApiOperation(value = "新增/修改")
    @PostMapping(value = "/save")
    public ResponseEntity<String> save(@RequestBody ProjectListDto projectListDto) throws Exception{
        String id = projectListService.save(projectListDto,"1");
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 2022项目-新增/修改
     */
    @ApiOperation(value = "新增/修改")
    @PostMapping(value = "/save2022")
    public ResponseEntity<String> save2022(@RequestBody ProjectListDto projectListDto) throws Exception{
        String id = projectListService.save(projectListDto,"2022");
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 新增/修改项目归档
     */
    @ApiOperation(value = "新增/修改项目归档")
    @PostMapping(value = "/saveFormArchive")
    public ResponseEntity saveFormArchive(@RequestBody ProgramArchiveDto programArchiveDto) throws Exception{
        String id = projectListService.saveFormArchive(programArchiveDto);
        return ResponseUtil.newInstance().add("businessTable", "program_archive").add("businessId", id).ok ("操作成功");
    }

    /**
     * 新增/修改三级校审
     */
    @ApiOperation(value = "新增/修改三级校审")
    @PostMapping(value = "/saveFormThree")
    public ResponseEntity saveFormThree(@RequestBody ProgramAuditDto programAuditDto) throws Exception{
        String id = projectListService.saveFormThree(programAuditDto);
        return ResponseUtil.newInstance().add("businessTable", "program_audit").add("businessId", id).ok ("操作成功");
    }

    /**
     * 流程保存
     */
    @ApiOperation(value = "流程保存")
    @PostMapping(value = "/saveForm")
    public ResponseEntity saveForm(@RequestBody ProjectListDto projectListDto) throws Exception{
        String id = projectListService.save(projectListDto,"1");
        return ResponseUtil.newInstance().add("businessTable", "program_project_list_info").add("businessId", id).ok ("操作成功");
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = "/findById")
    public ResponseEntity<ProjectListDto> save(@RequestParam String id){
        ProjectListDto dto = projectListService.findById(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据id查询三级校审
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询三级校审")
    @GetMapping(value = "/findByIdAudit")
    public ResponseEntity<ProgramAuditDto> findByIdAudit(@RequestParam String id){
        ProgramAuditDto dto = projectListService.findByIdAudit(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据id查询项目归档
     * @return
     */
    @ApiOperation(value = "根据id查询项目归档")
    @GetMapping(value = "/findByIdArchive")
    public ResponseEntity<ProgramArchiveDto> findByIdArchive(@RequestParam String id){
        ProgramArchiveDto dto = projectListService.findByIdArchive(id);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id删除")
    @GetMapping(value = "/deleteById")
    public ResponseEntity<String> deleteById(@RequestParam String id){
        String s = projectListService.deleteById(id);
        return ResponseEntity.ok(s);
    }


    /**
     * 批量删除字典
     */
    @DemoMode
    @ApiLog("批量删除项目信息")
    @PreAuthorize("hasAuthority('program:registered:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        String idArray[] = ids.split ( "," );
        for(String id: idArray){
            projectListService.deleteById ( id );
        }
        return ResponseEntity.ok ( "删除信息成功！" );
    }

    /**
     * 合同信息列表查询
     * @param dto
     * @param page
     * @return
     */
    @ApiOperation(value = "合同信息列表查询")
    @GetMapping(value = "/findContractPageList")
    public ResponseEntity<IPage<WorkContractInfo>> findContractPageList(ContractDto dto, Page<WorkContractInfo> page) {
        IPage<WorkContractInfo> pageList = projectListService.findContractPageList(dto, page);
        return ResponseEntity.ok(pageList);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody ProjectListDto dto) {
        String s = projectListService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 根据id修改三级校审状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改三级校审状态值status")
    @PostMapping(value = "/updateStatusByAuditId")
    public ResponseEntity<String> updateStatusByAuditId(@RequestBody ProjectListDto dto) {
        String s = projectListService.updateStatusByAuditId(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 根据id修改项目归档状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改项目归档状态值status")
    @PostMapping(value = "/updateStatusByArchiveId")
    public ResponseEntity<String> updateStatusByArchiveId(@RequestBody ProjectListDto dto) {
        String s = projectListService.updateStatusByArchiveId(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 项目登记列表
     * @param info
     * @param page
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "项目登记列表")
    @GetMapping(value = "/list")
    public ResponseEntity<IPage<ProgramProjectListInfo>> list(ProgramProjectListInfo info, Page<ProgramProjectListInfo> page) throws Exception {
        IPage<ProgramProjectListInfo> list = projectListService.list(page, info, "1");
        return ResponseEntity.ok (list);
    }

    /**
     * 项目登记列表,和上面list接口是一样的，目的时跳过list mapper接口的数据规则（比如仅部门可见、仅自己可见之类的）
     */
    @GetMapping(value = "/list2")
    public ResponseEntity<IPage<ProgramProjectListInfo>> list2(ProgramProjectListInfo info, Page<ProgramProjectListInfo> page) throws Exception {
        IPage<ProgramProjectListInfo> list = projectListService.list2(page, info, "1");
        return ResponseEntity.ok (list);
    }

    /**
     * 2022项目-项目登记列表
     * @param info
     * @param page
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "2022项目-项目登记列表")
    @GetMapping(value = "/list2022")
    public ResponseEntity<IPage<ProgramProjectListInfo>> list2022(ProgramProjectListInfo info, Page<ProgramProjectListInfo> page) throws Exception {
        IPage<ProgramProjectListInfo> list = projectListService.list(page, info, "2022");
        return ResponseEntity.ok (list);
    }


    @ApiLog(value = "导出项目信息")
    @GetMapping("exportFile")
    @ApiOperation(value = "导出项目信息")
    public void exportFile(ProgramProjectListInfo info, Page <ProgramProjectListInfo> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<ProgramProjectListInfo> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = projectListService.list (page,info,"1").getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = projectListService.list (page,info,"1").getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = projectListService.list (page,info,"1").getRecords();
        }
        List<ExportFileDto> exportFileDtos = projectListService.exportList(result);
        EasyPoiUtil.exportExcel ( exportFileDtos, sheetName,  sheetName, ExportFileDto.class, fileName, response );

    }




    /**
     * 根据项目id生成报告号
     * @param id
     * @return
     */
    @ApiOperation(value = "根据项目id生成报告号")
    @GetMapping(value = "/saveReportNo")
    public ResponseEntity<String> saveReportNo(@RequestParam("id") String id) throws Exception {
        String s = projectListService.saveReportNo(id);
        if (StringUtils.isNotBlank(s)) {
            return ResponseEntity.ok("已生成报告号："+s);
        }else{
            return ResponseEntity.badRequest().body("报告号生成失败");
        }
    }

    /**
     * 下载评估报告装订后浏览审核记录表
     * 下载一级校审表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadFirstAuditTpl")
    @ResponseBody
    public void downloadFirstAuditTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.getAuditInfoMap(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);

        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("firstAudit.ftl","UTF-8");

            File docFile = new File("一级校审.doc");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("一级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"一级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"一级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 下载二级校审表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadSecondAuditTpl")
    @ResponseBody
    public void downloadSecondAuditTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.getAuditInfoMap(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("secondAuditFtl.ftl","UTF-8");

            File docFile = new File("二级校审.doc");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("二级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"二级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"二级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 下载三级校审表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadThirdlyAuditTpl")
    @ResponseBody
    public void downloadThirdlyAuditTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.getAuditInfoMap(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("thirdlyAudit.ftl","UTF-8");

            File docFile = new File("三级校审.doc");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("三级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"三级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"三级校审.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 下载资产评估项目（校对）审核记录表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadProofreadAuditTpl")
    @ResponseBody
    public void downloadProofreadAuditTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.getProofreadAuditMap(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("proofreadAudit.ftl","UTF-8");

            File docFile = new File("资产评估项目（校对）审核记录表.xls");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("资产评估项目（校对）审核记录表.xls",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"资产评估项目（校对）审核记录表.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"资产评估项目（校对）审核记录表.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }

    }

    /**
     * 下载评估报告装订后浏览审核记录表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadAuditRecordFormAfterBindingTpl")
    @ResponseBody
    public void downloadAuditRecordFormAfterBindingTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.getAuditRecordFormAfterBindingMap(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("auditRecordFormAfterBinding.ftl","UTF-8");

            File docFile = new File("评估报告装订后浏览审核记录表.xls");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("评估报告装订后浏览审核记录表.xls",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"评估报告装订后浏览审核记录表.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"评估报告装订后浏览审核记录表.xls");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }
    }

    /**
     * 下载报告签发表
     * @param response
     * @param info
     */
    @RequestMapping(value="downloadReportAusstellungTpl")
    @ResponseBody
    public void downloadReportAusstellungTpl(HttpServletResponse response, ProgramProjectListInfo info)  {
        Map data = projectListService.downloadReportAusstellungTpl(info);


        //模板对象
        Template template=null;
        //下载文件地址
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = this.getClass().getResource("/").getPath()+"/freemarker";
        }else{
            filePath = "/mnt/project/cloud/freemarker";
        }
        //freemaker模板路径
        File path = new File(filePath);
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            //选择对应的ftl文件
            template = cfg.getTemplate("reportAusstellung.ftl","UTF-8");

            File docFile = new File("报告签发单.doc");
            FreemarkerUtil.generateFile(data,template,docFile);
            com.jeeplus.assess.utils.ResponseUtil.docResponse("报告签发单.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                //获取tomcat的路径
                String tomcatFilePath=System.getProperty("catalina.home");
                //删除tomcat目录下的处理后的文件信息
                File tomcatFile = new File(tomcatFilePath+"/bin/"+"报告签发单.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }else{
                //删除目录下的处理后的文件信息
                File tomcatFile = new File("/mnt/project/cloud/"+"报告签发单.doc");
                if (tomcatFile.isFile()) {
                    tomcatFile.delete();
                }
            }
        }
    }


    /**
     * 查询当前登录人所属项目组的项目
     * @return
     */
    @ApiOperation(value = "查询当前登录人所属项目组的项目")
    @GetMapping(value = "/getHaveProjectIds")
    public ResponseEntity<List<String>> getHaveProjectIds() {
        return projectListService.getHaveProjectIds();
    }

    @ApiOperation(value = "根据项目id以及校审等级查询三级校审详情")
    @GetMapping(value = "/findByProIdAndLevel")
    public ResponseEntity<ProgramAuditDto> findByProIdAndLevel(String programId, String auditLevel) {
        return projectListService.findByProIdAndLevel(programId, auditLevel);
    }
}
