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

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.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.test.utils.FreemarkerUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import com.jeeplus.core.excel.utils.EasyPoiUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.program.configuration.projectList.domain.ProgramProjectListInfo;
import com.jeeplus.test.program.configuration.projectList.mapper.ProgramReportNoMapper;
import com.jeeplus.test.program.configuration.projectList.service.ProjectListService;
import com.jeeplus.test.program.configuration.projectList.service.dto.*;
import com.jeeplus.test.projectRecords.domain.Project;
import com.jeeplus.test.projectRecords.service.dto.FileUploadListDTO;
import com.jeeplus.test.projectRecords.service.dto.ProjectDTO;
import com.jeeplus.test.projectRecords.service.mapstruct.ProjectWrapper;
import com.jeeplus.test.workContract.domain.WorkContractInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
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.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Resource
    private ProjectListService projectListService;

    /**
     * 新增/修改
     */
    @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);
    }

    /**
     * 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);
    }

    /**
     * 导出
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/exportFile")
    @ApiOperation(value = "导出")
    public void exportFileUploadList(ProgramProjectListInfo info,String tabType, HttpServletResponse response) throws Exception{
        List<ExportFileDto> infos = projectListService.exportList(info,tabType);
        String title = "项目登记列表信息";
        String sheetName = "项目登记列表信息";
        if("2022".equals(tabType)){
            title = "2022年" + title;
            sheetName = "2022年" + sheetName;
        }
        EasyPoiUtil.exportExcel(infos, title,  sheetName, ExportFileDto.class, "", 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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("一级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"一级校审.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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("二级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"二级校审.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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("三级校审.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"三级校审.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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("资产评估项目（校对）审核记录表.xls",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"资产评估项目（校对）审核记录表.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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("评估报告装订后浏览审核记录表.xls",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"评估报告装订后浏览审核记录表.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;
        //freemaker模板路径
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        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.test.utils.ResponseUtil.docResponse("报告签发单.doc",docFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //获取tomcat的路径
            String tomcatFilePath=System.getProperty("catalina.home");
            //删除tomcat目录下的处理后的文件信息
            File tomcatFile = new File(tomcatFilePath+"/bin/"+"报告签发单.doc");
            if (tomcatFile.isFile()) {
                tomcatFile.delete();
            }
        }
    }

}
