/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.project.web;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Basic;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.sg.audit.information.utils.FreemarkerUtil;
import com.jeeplus.modules.sg.audit.information.utils.ResponseUtil;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.Construction;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.materialInventory.service.MaterialInventoryService;
import com.jeeplus.modules.sg.managementcenter.project.entity.*;
import com.jeeplus.modules.sg.managementcenter.project.service.PickingRequisitionService;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.project.util.ExportUtil;
import com.jeeplus.modules.sg.managementcenter.project.util.ProjectImportUtil;
import com.jeeplus.modules.sg.scheduleView.entity.ScheduleView;
import com.jeeplus.modules.sg.settActivi.entity.SettActivi;
import com.jeeplus.modules.sg.settActivi.entity.SettList;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;

/**
 * 项目基础信息controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementcenter/project")
public class ProjectController extends BaseController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private PickingRequisitionService pickingRequisitionService;

    @Autowired
    private MaterialInventoryService materialInventoryService;
    @Autowired
    private OaNotifyService oaNotifyService;//通知服务类

    @Autowired
    private SystemService systemService;

    @Autowired
    private ActProcessService actProcessService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private ConstructionService constructionService;

    @ModelAttribute
    public Project get(@RequestParam(required = false) String id) {
        Project entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = projectService.get(id);
        }
        if (entity == null) {
            entity = new Project();
        }
        return entity;
    }

    /*--------------------------------------施工技术交底目录下 项目前期基本信息、施工任务分配信息、
            交底计划安排信息、基础信息拆旧、实际拆旧 等相关方法------------------------------------
     */

    /**
     * 项目前期基本信息 列表页面
     */
    @RequiresPermissions("sg:managementcenter:project:basicInformation:list")
    @RequestMapping(value = "basicInformation")
    public String basicInformation(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/projectBasicInformation";
    }

    /**
     * 施工任务分配信息 列表页面
     */
    @RequiresPermissions("sg:managementcenter:project:assignment:list")
    @RequestMapping(value = "assignment")
    public String assignment(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/projectAssignment";
    }

    /**
     * 交底计划安排信息 列表页面
     */
    @RequiresPermissions("sg:managementcenter:project:disclosurePlan:list")
    @RequestMapping(value = "disclosurePlan")
    public String disclosurePlan(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/projectDisclosurePlan";
    }

    /**
     * 基础信息拆旧表信息 列表页面
     */
    @RequestMapping(value = "tearDown")
    @RequiresPermissions("sg:managementcenter:teardown:list")
    public String tearDown(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/tearDown";
    }


    /**
     * 实际拆旧信息 列表页面
     */
    @RequestMapping(value = "tearFinal")
    @RequiresPermissions("sg:managementcenter:tearfinal:list")
    public String tearFinal(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/tearFinal";
    }


    /**
     * 项目前期基本信息 数据列表
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:basicInformation:list")
    @RequestMapping(value = "basicData")
    public Map<String, Object> basicData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String reserveProjectName = project.getReserveProjectName();
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
//        BasicInformation basicInformation = new BasicInformation();
//        project.setBasicInformation(basicInformation);
//        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        Page<Project> page = projectService.findBasicPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }


    /**
     * 施工任务分配信息 数据列表
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:assignment:list")
    @RequestMapping(value = "assData")
    public Map<String, Object> assData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String reserveProjectName = project.getReserveProjectName();
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        Page<Project> page = projectService.findAssPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 交底计划安排 数据列表
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:disclosurePlan:list")
    @RequestMapping(value = "disclosureData")
    public Map<String, Object> disclosureData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String reserveProjectName = project.getReserveProjectName();
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        Page<Project> page = projectService.findPlanPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }


    /**
     * 拆旧 数据列表
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:teardown:list", "sg:managementcenter:tearfinal:list"}, logical = Logical.OR)
    @RequestMapping(value = "tearDownData")
    public Map<String, Object> tearDownData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String reserveProjectName = project.getReserveProjectName();
        List<String> reserveList = new ArrayList<>();
        if (null != reserveProjectName && !"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        Page<Project> page = projectService.findTearDownPage(new Page<Project>(request, response), project);
        List<Project> list = page.getList();
        //处理各项金额
        for (Project p : list) {
            String rNum = p.getTearDown().getReserveNumber();
            String cNum = p.getTearDown().getConfessionNumber();
            String caNum = p.getTearDown().getChangeNumber();
            String aNum = p.getTearDown().getActualNumber();
            if (null == rNum) {
                rNum = "0";
            }
            if (null == cNum) {
                cNum = "0";
            }
            if (null == caNum) {
                caNum = "0";
            }
            if (null == aNum) {
                aNum = "0";
            }
            BigDecimal reserveNumber = new BigDecimal(rNum);
            BigDecimal actualNumber = new BigDecimal(aNum);
            BigDecimal confessionNumber = new BigDecimal(cNum);
            BigDecimal changeNumber = new BigDecimal(caNum);
            //subtract减法
            BigDecimal subtract = reserveNumber.subtract(actualNumber);
            BigDecimal confessionDifference = confessionNumber.subtract(actualNumber);
            BigDecimal changeDifference = changeNumber.subtract(actualNumber);
            p.getTearDown().setReserveBalance(subtract.toString());
            p.getTearDown().setConfessionDifference(confessionDifference.toString());
            p.getTearDown().setChangeDifference(changeDifference.toString());

        }
        return getBootstrapData(page);
    }


    /**
     * 项目前期基本信息  编辑表单页面
     */
    @RequiresPermissions(value = {"sg:managementcenter:project:basicInformation:edit"}, logical = Logical.OR)
    @RequestMapping(value = "basicInformationForm")
    public String basicInformationForm(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/basicInformationForm";
    }
    /**
     * 项目前期基本信息 保存表单
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:project:basicInformation:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        Project projectStatus = projectService.get(project.getId());
        if ("0".equals(projectStatus.getStatus())) {
            BasicInformation basicInformation = project.getBasicInformation();
            String projectNature = basicInformation.getProjectNature();
            String demandUnit = basicInformation.getDemandUnit();
            String operationUnit = basicInformation.getOperationUnit();
            String powerSupplyArea = basicInformation.getPowerSupplyArea();
            String projectType = basicInformation.getProjectType();
            String whetherSummer = basicInformation.getWhetherSummer();
            if (!"资本".equals(projectNature) && !"成本".equals(projectNature)) {
                j.setSuccess(false);
                j.setMsg("项目性质填写有误");
                return j;
            }
            if (!"经研所".equals(demandUnit) && !"新区".equals(demandUnit) && !"丹徒".equals(demandUnit) && !"城区".equals(demandUnit)) {
                j.setSuccess(false);
                j.setMsg("需求单位填写有误");
                return j;
            }
            if (!"新区".equals(operationUnit) && !"丹徒".equals(operationUnit) && !"城区".equals(operationUnit)) {
                j.setSuccess(false);
                j.setMsg("项运维单位填写有误");
                return j;
            }
            if (!"".equals(powerSupplyArea)) {
                if (!"A".equals(powerSupplyArea) && !"A+".equals(powerSupplyArea) && !"B".equals(powerSupplyArea) && !"C".equals(powerSupplyArea) && !"无".equals(powerSupplyArea)) {
                    j.setSuccess(false);
                    j.setMsg("供电区域填写有误");
                    return j;
                }
            }
            if (!"配变改造".equals(projectType)
                    && !"配变新增".equals(projectType)
                    && !"电缆项目".equals(projectType)
                    && !"杆线项目".equals(projectType)
                    && !"混合项目".equals(projectType)
                    && !"纯自动化".equals(projectType)
                    && !"纯土建".equals(projectType)
                    && !"井盖维修".equals(projectType)
                    && !"环网柜更换".equals(projectType)
                    && !"箱变更换".equals(projectType)
                    && !"其他特殊类".equals(projectType)
                    ) {
                j.setSuccess(false);
                j.setMsg("项目类型填写有误");
                return j;
            }
            if (!"是".equals(whetherSummer) && !"否".equals(whetherSummer)) {
                j.setSuccess(false);
                j.setMsg("是否迎峰度夏项目填写有误");
                return j;
            }
            Project proByName = projectService.findProByName(project.getReserveProjectName());
            //判断是不是空，是空insert新数据，不是空update数据
            if (proByName != null) {
                projectService.updateBasic(project);
            } else {
                project.getBasicInformation().setReserveProjectName(project.getReserveProjectName());
                projectService.insertBasic(project);
            }
            j.setSuccess(true);
            j.setMsg("保存成功");
        } else {
            j.setSuccess(false);
            j.setMsg("项目流程运行中不可修改信息");
        }
        return j;
    }

    /**
     *项目前期基础信息 导出
     * */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:basicInformation:export")
    @RequestMapping(value = "btnExport")
    public void exportExcel(Project project, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //判断是否有搜索条件
        //获取项目选择id  根据勾选id搜索数据 暂时不用
//        String id = project.getId();
//        if (null != id && !"".equals(id)) {
//            //根据“，”分割id，如果有选择的id，将其他搜索条件清空
//            String[] split = id.split(",");
//            List<String> searchList = new ArrayList<>();
//            for (int i = 0; i < split.length; i++) {
//                searchList.add(split[i]);
//            }
//            beforeExport.setSearchId(searchList);
//        } else {
//            beforeExport.setReserveProjectName(project.getReserveProjectName());
//            beforeExport.setProjectId(project.getProjectId());
//            beforeExport.setProjectName(project.getProjectName());
//        }
        String reserveProjectName =  URLDecoder.decode(project.getReserveProjectName(),"UTF-8");
        project.setProjectId(URLDecoder.decode(project.getProjectId(),"UTF-8"));
        project.setProjectName(URLDecoder.decode(project.getProjectName(),"UTF-8"));
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        List<Project> list = projectService.findBasicList(project);
        ExportUtil util = ExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("beforeExport");
        util.exportBasic(response,workbook,list);
    }

    /**
     * 项目前期基本信息 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:basicInformation:import")
    @RequestMapping(value = "importBasic")
    public AjaxJson importBasic(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "项目前期基本信息");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            //将写入的文件先进行规则验证
            Map<String, Object> stringObjectMap = ProjectImportUtil.basicValidation(importExcel, lastDataRowNum);
            //获取错误信息
            String errorMsg = (String) stringObjectMap.get("errorMsg");
            //获取需要导入的list
            List<Project> afterValidation = (List<Project>) stringObjectMap.get("afterValidation");
            List<Project> noCompareList = (List<Project>) stringObjectMap.get("noCompareList");
            if (afterValidation.size() > 0) {
                projectService.insertBasicList(afterValidation);
            }
            if (noCompareList.size() > 0) {
                projectService.updateBasicList(noCompareList);
            }
            int i = afterValidation.size() + noCompareList.size();
            j.setMsg("已成功导入" + i + "条项目表单记录" + errorMsg);

            //
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 施工任务分配信息 编辑表单页面
     */
    @RequiresPermissions(value = {"sg:managementcenter:project:assignment:edit"}, logical = Logical.OR)
    @RequestMapping(value = "assignmentForm")
    public String assignmentForm(Project project, Model model) {
        project = projectService.getAss(project);
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/assignmentForm";
    }

    /**
     * 施工任务分配信息 保存表单
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:project:assignment:edit"}, logical = Logical.OR)
    @RequestMapping(value = "saveAss")
    public AjaxJson saveAss(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        Boolean flag = false;
        String str = "";
        /**
         * 后台hibernate-validation插件校验
         */
        Boolean aBoolean = ProjectImportUtil.checkProcess(project.getReserveProjectName());
        if (aBoolean) {
            String disclosureType = project.getAssignment().getDisclosureType();
            String assignedUnit = project.getAssignment().getAssignedUnit();
            String constructionUnit = project.getAssignment().getConstructionUnit();
            flag = ProjectImportUtil.checkFlag(disclosureType, ProjectImportUtil.DIS_TYPE);
            if (flag) {
                str += "交底类型填写有误\t";
            }
            flag = ProjectImportUtil.checkFlag(assignedUnit, ProjectImportUtil.ASS_UNIT);
            if (flag) {
                str += "合同单位填写有误\t";
            }
            flag = ProjectImportUtil.checkFlag(constructionUnit, ProjectImportUtil.CON_UNIT);
            if (flag) {
                str += "施工单位填写有误\t";
            }
            String s = ProjectImportUtil.checkMember(project);
            str += s;
            if (!"".equals(str)) {
                j.setSuccess(false);
                j.setMsg(str);
                return j;
            }
            Project proByName = projectService.findAssByName(project.getReserveProjectName());
            List<Project> projectList = new ArrayList<>();
            //判断是不是空，是空insert新数据，不是空update数据
            if (proByName != null) {
                projectList.add(project);
                projectService.updateAssList(projectList);
            } else {
                project.getAssignment().setReserveProjectName(project.getReserveProjectName());
                String demandUnit = projectService.findDemandUnit(project.getReserveProjectName());
                if (!"经研所".equals(demandUnit)) {
                    project.getAssignment().setInstituteRole("");
                }
                projectList.add(project);
                projectService.insertAssList(projectList);
            }
            j.setSuccess(true);
            j.setMsg("保存成功");
        } else {
            j.setSuccess(false);
            j.setMsg("项目流程运行中不可修改信息");
        }
        return j;
    }

    /**
     * 施工任务分配信息  导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:assignment:import")
    @RequestMapping(value = "importAss")
    public AjaxJson importAss(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "施工任务分配信息");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            //将写入的文件先进行规则验证
            Map<String, Object> stringObjectMap = ProjectImportUtil.assValidation(importExcel, lastDataRowNum);
            //获取错误信息
            String errorMsg = (String) stringObjectMap.get("errorMsg");
            //获取需要导入的list
            List<Project> afterValidation = (List<Project>) stringObjectMap.get("afterValidation");
            List<Project> noCompareList = (List<Project>) stringObjectMap.get("noCompareList");
            if (afterValidation.size() > 0) {
                projectService.insertAssList(afterValidation);
            }
            if (noCompareList.size() > 0) {
                projectService.updateAssList(noCompareList);
            }
            int i = afterValidation.size() + noCompareList.size();
            j.setMsg("已成功导入" + i + "条记录\n" + errorMsg);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     *施工任务分配信息 导出
     * */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:assignment:export")
    @RequestMapping(value = "assExport")
    public void assExport(Project project, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String reserveProjectName =  URLDecoder.decode(project.getReserveProjectName(),"UTF-8");
        project.setProjectId(URLDecoder.decode(project.getProjectId(),"UTF-8"));
        project.setProjectName(URLDecoder.decode(project.getProjectName(),"UTF-8"));
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        List<Project> list = projectService.findAssList(project);
        ExportUtil util = ExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("assExport");
        util.exportAss(response,workbook,list);
    }


    /**
     * 交底计划安排 编辑表单页面
     */
    @RequiresPermissions(value = {"sg:managementcenter:project:disclosurePlan:edit"}, logical = Logical.OR)
    @RequestMapping(value = "disclosurePlanForm")
    public String disclosurePlanForm(Project project, Model model) {
        project = projectService.getPlan(project);
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/disclosurePlanForm";
    }

    /**
     * 交底计划安排 保存表单
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:project:disclosurePlan:edit"}, logical = Logical.OR)
    @RequestMapping(value = "savePlan")
    public AjaxJson savePlan(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        Boolean flag = false;
        String str = "";
        /**
         * 后台hibernate-validation插件校验
         */
        Boolean aBoolean = ProjectImportUtil.checkProcess(project.getReserveProjectName());
        if (aBoolean) {
            String reserveProjectName = project.getReserveProjectName();
            //判断项目前期基本信息-施工任务分配信息 是否填写完成，未完成不允许导入交底计划安排
            Project assByName = projectService.findAssByName(reserveProjectName);
            Project basicByName = projectService.findProByName(reserveProjectName);
            if (assByName == null || basicByName == null) {
                j.setSuccess(false);
                j.setMsg("请填写对应的前期基本信息/施工任务分配信息");
                return j;
            } else {
                project.setBasicInformation(basicByName.getBasicInformation());
                project.setAssignment(assByName.getAssignment());
                Project planByName = projectService.findPlanByName(reserveProjectName);
                List<Project> projectList = new ArrayList<>();
                //判断是不是空，是空insert新数据，不是空update数据
                projectList.add(project);
                if (planByName != null) {
//                    projectService.updatePlanList(projectList);
                    j.setSuccess(true);
                    j.setMsg("保存成功");
                } else {
                    projectService.insertPlanList(projectList);
                    Construction construction = new Construction();
                    construction.setReserveProjectName(project.getReserveProjectName());
                    constructionService.newSave(construction);
                    constructionService.updateStatus(project.getReserveProjectName());
                    Map<String, Object> vars = Maps.newHashMap();
                    vars.put("design", UserUtils.getByUserName(project.getAssignment().getConstructionManage()).getLoginName());
                    //发送流程，更改项目状态
                    String procDefId = projectService.findDefId("sgjd");
                    ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                    String title = project.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                    String ByName = projectService.findPlanIdByName(construction.getReserveProjectName());
                    actTaskService.startProcess(p.getKey(), "xm_construction_clarificaiton", ByName, title, vars);
                    j.setSuccess(true);
                    j.setMsg("流程发送成功");
                }
            }
        } else {
            j.setSuccess(false);
            j.setMsg("项目流程运行中不可修改信息");
        }
        return j;
    }

    /**
     * 交底计划安排  导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:disclosurePlan:import")
    @RequestMapping(value = "importPlan")
    public AjaxJson importPlan(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "交底计划安排");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            //将写入的文件先进行规则验证
            Map<String, Object> stringObjectMap = ProjectImportUtil.planValidation(importExcel, lastDataRowNum);
            //获取错误信息
            String errorMsg = (String) stringObjectMap.get("errorMsg");
            //获取需要导入的list
            List<Project> compareList = (List<Project>) stringObjectMap.get("compareList");
            List<Project> noCompareList = (List<Project>) stringObjectMap.get("noCompareList");
            List<Project> processList = new ArrayList<>();
            if (compareList.size() > 0) {
                projectService.insertPlanList(compareList);
                processList.addAll(compareList);

            }
            if (noCompareList.size() > 0) {
                projectService.updatePlanList(noCompareList);
                processList.addAll(noCompareList);
            }
            int i = compareList.size() + noCompareList.size();
            String procDefId = projectService.findDefId("sgjd");
            for (Project project : processList) {
                if ("0".equals(project.getStatus())) {
                    Construction construction = new Construction();
                    construction.setReserveProjectName(project.getReserveProjectName());
                    constructionService.newSave(construction);
                    constructionService.updateStatus(project.getReserveProjectName());
                    Map<String, Object> vars = Maps.newHashMap();
                    vars.put("design", UserUtils.getByUserName(project.getAssignment().getConstructionManage()).getLoginName());
                    //发送流程，更改项目状态
                    ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                    String title = project.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                    String planByName = projectService.findPlanIdByName(construction.getReserveProjectName());
                    actTaskService.startProcess(p.getKey(), "xm_construction_clarificaiton", planByName, title, vars);
                } else {
                    errorMsg += project.getReserveProjectName() + "不能重复发送流程\n";
                }
            }
            //将不可修改的值重新获取
            j.setMsg("已成功导入" + i + "条记录\n" + errorMsg);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     *交底计划安排 导出
     * */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:disclosurePlan:export")
    @RequestMapping(value = "planExport")
    public void planExport(Project project, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String reserveProjectName =  URLDecoder.decode(project.getReserveProjectName(),"UTF-8");
        project.setProjectId(URLDecoder.decode(project.getProjectId(),"UTF-8"));
        project.setProjectName(URLDecoder.decode(project.getProjectName(),"UTF-8"));
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        List<Project> list = projectService.findPlanList(project);
        ExportUtil util = ExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("planExport");
        util.exportPlan(response,workbook,list);
    }


    /**
     * 基础信息拆旧表信息 新增页面
     */
    @RequestMapping(value = "tearAdd")
    @RequiresPermissions("sg:managementcenter:teardown:add")
    public String tearAdd(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/tearAdd";
    }

    /**
     * 基础信息拆旧表信息 修改页面
     */
    @RequestMapping(value = "tearEidForm")
    @RequiresPermissions("sg:managementcenter:teardown:edit")
    public String tearEidForm(Project project, Model model) {
        Project tear = projectService.getTear(project);
        model.addAttribute("project", tear);
        return "modules/sg/managementcenter/project/tearEidForm";
    }

    /**
     * 基础信息拆旧表信息 保存新增
     */
    @ResponseBody
    @RequestMapping(value = "tearAddSave")
    @RequiresPermissions("sg:managementcenter:teardown:add")
    public AjaxJson tearAddSave(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        Project projectStatus = projectService.get(project.getReserveProjectName());
        if (projectStatus != null) {
            String reserveProjectName = projectStatus.getReserveProjectName();
            TearDown tearDown = project.getTearDown();
            String reservedName = tearDown.getReservedName();
            project.setProjectId(projectStatus.getProjectId());
            project.setProjectName(projectStatus.getProjectName());
            project.setReserveProjectName(reserveProjectName);
            tearDown.setConfessionName(reservedName);
            tearDown.setConfessionModel(tearDown.getReserveModel());
            tearDown.setConfessionUnit(tearDown.getReserveUnit());
            tearDown.setConfessionNumber("0");
            tearDown.setConfessionNotes("");
            tearDown.setChangeName(reservedName);
            tearDown.setChangeModel(tearDown.getReserveModel());
            tearDown.setChangeUnit(tearDown.getReserveUnit());
            tearDown.setChangeNumber("0");
            tearDown.setChangeNotes("");
            tearDown.setActualName(reservedName);
            tearDown.setActualModel(tearDown.getReserveModel());
            tearDown.setActualUnit(tearDown.getReserveUnit());
            tearDown.setActualNumber("0");
            tearDown.setActualNotes("");
            List<Project> insertList = new ArrayList<>();
            insertList.add(project);
            //根据储备项目名称和设备材料名称查询项目是否存在，存在提示无法保存
            Boolean notByName = projectService.isNotByName(reserveProjectName, reservedName);
            if (notByName) {
                j.setSuccess(false);
                j.setMsg("该项目物料信息已存在");
            } else {
                projectService.insertTearList(insertList);
                j.setSuccess(true);
                j.setMsg("保存成功");
            }
        }
        return j;
    }

    /**
     * 基础信息拆旧表信息 保存修改
     */
    @ResponseBody
    @RequestMapping(value = "tearEditSave")
    @RequiresPermissions("sg:managementcenter:teardown:edit")
    public AjaxJson tearEditSave(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        projectService.tearEditSave(project);
        j.setSuccess(true);
        j.setMsg("修改成功");
        return j;
    }


    /**
     * 基础信息拆旧表信息  导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:teardown:import")
    @RequestMapping(value = "importTear")
    public AjaxJson importTear(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        List<Project> insertList = new ArrayList<>();
        List<Project> updateList = new ArrayList<>();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "拆旧表");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            for (int i = 2; i < lastDataRowNum; i++) {
                Row row = importExcel.getRow(i);
                TearDown tearDown = new TearDown();
                Project project = new Project();
                String reserveProjectName = importExcel.getCellValue(row, 1).toString();
                Project byName = projectService.findByName(reserveProjectName);
                if (null == byName) {
                    continue;
                }
                String reservedName = importExcel.getCellValue(row, 2).toString();
                String reserveModel = importExcel.getCellValue(row, 3).toString();
                String reserveUnit = importExcel.getCellValue(row, 4).toString();
                String reserveNumber = importExcel.getCellValue(row, 5).toString();
                if ("".equals(reserveNumber) || null == reserveNumber) {
                    reserveNumber = "0";
                }
                tearDown.setReservedName(reservedName);
                tearDown.setReserveModel(reserveModel);
                tearDown.setReserveUnit(reserveUnit);
                tearDown.setReserveNumber(reserveNumber);
                tearDown.setReserveNotes(importExcel.getCellValue(row, 6).toString());
                tearDown.setConfessionName(reservedName);
                tearDown.setConfessionModel(reserveModel);
                tearDown.setConfessionUnit(reserveUnit);
                tearDown.setConfessionNumber("0");
                tearDown.setConfessionNotes("");
                tearDown.setChangeName(reservedName);
                tearDown.setChangeModel(reserveModel);
                tearDown.setChangeUnit(reserveUnit);
                tearDown.setChangeNumber("0");
                tearDown.setChangeNotes("");
                tearDown.setActualName(reservedName);
                tearDown.setActualModel(reserveModel);
                tearDown.setActualUnit(reserveUnit);
                tearDown.setActualNumber("0");
                tearDown.setActualNotes("");
                project.setReserveProjectName(byName.getReserveProjectName());
                project.setTearDown(tearDown);
                Boolean notByName = projectService.isNotByName(reserveProjectName, reservedName);
                if (notByName) {
                    updateList.add(project);
                } else {
                    insertList.add(project);
                }
            }
            if (updateList.size() > 0) {
                projectService.updateTearList(updateList);
            }
            if (insertList.size() > 0) {
                projectService.insertTearList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("插入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    /**
     * 基础信息拆旧表信息 批量删除
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:teardown:del", "sg:managementcenter:tearfinal:del"}, logical = Logical.OR)
    @RequestMapping(value = "deleteTearAll")
    public AjaxJson deleteAll(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            projectService.deleteTearAll(id);
        }
        j.setMsg("删除请假表单成功");
        return j;
    }

    /**
     * 实际拆旧信息  导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:tearfinal:import")
    @RequestMapping(value = "importFinTear")
    public AjaxJson importFinTear(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        List<Project> insertList = new ArrayList<>();
        List<Project> updateList = new ArrayList<>();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "拆旧表");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            for (int i = 2; i < lastDataRowNum; i++) {
                Row row = importExcel.getRow(i);
                TearDown tearDown = new TearDown();
                Project project = new Project();
                String reserveProjectName = importExcel.getCellValue(row, 1).toString();
                Project byName = projectService.findByName(reserveProjectName);
                if (null == byName) {
                    continue;
                }
                String reservedName = importExcel.getCellValue(row, 2).toString();
                String reserveModel = importExcel.getCellValue(row, 3).toString();
                String reserveUnit = importExcel.getCellValue(row, 4).toString();
                String reserveNumber = importExcel.getCellValue(row, 5).toString();
                String reserveNotes = importExcel.getCellValue(row, 6).toString();
                if ("".equals(reserveNumber) || null == reserveNumber) {
                    reserveNumber = "0";
                }
                tearDown.setReservedName(reservedName);
                tearDown.setReserveModel(reserveModel);
                tearDown.setReserveUnit(reserveUnit);
                tearDown.setReserveNumber("0");
                tearDown.setReserveNotes("");

                tearDown.setConfessionName(reservedName);
                tearDown.setConfessionModel(reserveModel);
                tearDown.setConfessionUnit(reserveUnit);
                tearDown.setConfessionNumber("0");
                tearDown.setConfessionNotes("");

                tearDown.setChangeName(reservedName);
                tearDown.setChangeModel(reserveModel);
                tearDown.setChangeUnit(reserveUnit);
                tearDown.setChangeNumber("0");
                tearDown.setChangeNotes("");

                tearDown.setActualName(reservedName);
                tearDown.setActualModel(reserveModel);
                tearDown.setActualUnit(reserveUnit);
                tearDown.setActualNumber(reserveNumber);
                tearDown.setActualNotes(reserveNotes);
                project.setReserveProjectName(byName.getReserveProjectName());
                project.setTearDown(tearDown);
                Boolean notByName = projectService.isNotByName(reserveProjectName, reservedName);
                if (notByName) {
                    updateList.add(project);
                } else {
                    insertList.add(project);
                }
            }
            if (updateList.size() > 0) {
                projectService.updateFinTearList(updateList);
            }
            if (insertList.size() > 0) {
                projectService.insertTearList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("插入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    /*--------------------------------分割线---------------------------------------------*/


    /**
     * 项目立项信息
     */
    @RequiresPermissions("sg:managementcenter:project:approval")
    @RequestMapping(value = "approval")
    public String approval(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/projectApproval";
    }



    /**
     * 项目关闭管理模块
     */
    @RequiresPermissions("sg:managementcenter:closure:list")
    @RequestMapping(value = "closureManagement")
    public String closureManagement(Project project, Model model) {
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/closureManagement";
    }





    /**
     * 项目立项信息 数据列表
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:list")
    @RequestMapping(value = "approvalData")
    public Map<String, Object> approvalData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String projectId = project.getProjectId();
        List<String> reserveList = new ArrayList<>();
        if (!"".equals(projectId)) {
            String[] split = projectId.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        Page<Project> page = projectService.findApprovalPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }



    /**
     * 项目关闭管理模块数据页面
     */
    @ResponseBody
    @RequestMapping(value = "closureManagementData")
    public Map<String, Object> closureManagementData(ClosureManage project, HttpServletRequest request, HttpServletResponse response, Model model) {
        String reserveProjectName = project.getReserveProjectName();
        List<String> reserveList = new ArrayList<>();
        if (null != reserveProjectName && !"".equals(reserveProjectName)) {
            String[] split = reserveProjectName.split("\\s+");
            String reserveName = "";
            for (int i = 0; i < split.length; i++) {
                reserveName = split[i];
                reserveList.add(reserveName);
            }
            project.setReserveList(reserveList);
        }
        Page<ClosureManage> page = projectService.findClosureManagementData(new Page<ClosureManage>(request, response), project);
        List<ClosureManage> list = page.getList();
        for (ClosureManage c : list) {
            CapitalPlan capitalPlan = c.getCapitalPlan();
            String whetherCloseStatus = c.getWhetherCloseStatus();
            String status = c.getStatus();
            String acquisitionStatus = c.getAcquisitionStatus();
            String constructionStatus = c.getConstructionStatus();
            String settStatus = c.getSettStatus();
            String advanceStatus = c.getAdvanceStatus();
            if ("1".equals(whetherCloseStatus)) {
                c.setWhetherCloseStatus("该项目已关闭");
            } else {
                c.setWhetherCloseStatus("项目未关闭");
            }
            //对不同流程状态进行判断重新赋值
            if ("2".equalsIgnoreCase(status)) {
                c.setStatus("流程已完成");
            } else {
                c.setStatus("流程未完成");
            }

            if ("2".equalsIgnoreCase(acquisitionStatus)) {
                c.setAcquisitionStatus("流程已完成");
            } else {
                c.setAcquisitionStatus("流程未完成");
            }

            if ("2".equalsIgnoreCase(advanceStatus)) {
                c.setAdvanceStatus("流程已完成");
            } else {
                c.setAdvanceStatus("流程未完成");
            }

            if ("2".equalsIgnoreCase(constructionStatus)) {
                c.setConstructionStatus("流程已完成");
            } else {
                c.setConstructionStatus("流程未完成");
            }

            if ("2".equalsIgnoreCase(settStatus)) {
                c.setSettStatus("流程已完成");
            } else {
                c.setSettStatus("流程未完成");
            }
            if (null != capitalPlan) {

            } else {
                //设计费-监理费-施工费未导入
                c.setDesignProblem("未完成项目资金计划管理");
                c.setSupervisionProblem("未完成项目资金计划管理");
                c.setConstructionProblem("未完成项目资金计划管理");
            }
        }
        return getBootstrapData(page);
    }


    /**
     * 表单列表数据
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:teardown:add", "sg:managementcenter:project:list"}, logical = Logical.OR)
    @RequestMapping(value = "data")
    public Map<String, Object> data(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 施工交底流程，项目选取框
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:list")
    @RequestMapping(value = "dataSys")
    public Map<String, Object> dataSys(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setStatus("0");
        project.setWhetherCloseStatus("0");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }


    /**
     * 领料模块项目选择框(修改)2020-09-22
     */
    @ResponseBody
    @RequestMapping(value = "dataPicking")
    public Map<String, Object> dataPicking(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
/*		project1.setStatus("2");
		project1.setWhetherCloseStatus("0");
		project1.setEarlyMaterial(1);
		project1.setConstructionUnitManage(UserUtils.getUser().getLoginName());*/
        project.setStatus("2");
        project.setWhetherCloseStatus("0");
        project.setEarlyMaterial("1");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 土建流程项目选择(修改2020-09-23)
     */
    @ResponseBody
    @RequestMapping(value = "materialDataPicking")
    public Map<String, Object> c(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
/*		//运行提前施工
		project1.setPreConstruction(1);
		//未进行施工流程
		project1.setConstructionStatus("0");*/
        project.setAdvanceStatus("0");
        project.setStatus("2");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 验收流程项目选择
     */
    @ResponseBody
    @RequestMapping(value = "ysDataPicking")
    public Map<String, Object> ysDataPicking(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setConstructionStatus("0");
        project.setPreConstruction("1");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 施工模块项目选择框
     */
    @ResponseBody
    @RequestMapping(value = "materialSuperNon")
    public Map<String, Object> materialSuperNon(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setAdvanceStatus("0");
        project.setAdvanceConstruction("0");
        project.setWhetherCloseStatus("0");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 政策超权限选择框
     */
    @ResponseBody
    @RequestMapping(value = "advancePolicyData")
    public Map<String, Object> advancePolicyData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setPolicyStatus("1");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 提前施工项目选择
     */
    @ResponseBody
    @RequestMapping(value = "dataAdvance")
    public Map<String, Object> dataAdvance(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
/*		project1.setPreConstruction(0);
		project1.setConstructionUnitManage(UserUtils.getUser().getLoginName());//施工项目经理*/
        project.setPreConstruction("0");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 领料申请项目选择框
     */
    @ResponseBody
    @RequestMapping(value = "pickingApplication")
    public Map<String, Object> pickingApplication(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 结算项目选择框
     */
    @ResponseBody
    @RequestMapping(value = "settData")
    public Map<String, Object> settData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        project.setSettStatus("0");
        project.setConstructionStatus("2");
        BasicInformation basicInformation = new BasicInformation();
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }

    /**
     * 表单列表数据
     */
    @ResponseBody
    @RequestMapping(value = "fundData")
    public Map<String, Object> fundData(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
        //配网资本项目
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setProjectNature("资本");
        project.setBasicInformation(basicInformation);
        Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
        return getBootstrapData(page);
    }








    /**
     * 项目立项信息修改
     */
    @RequiresPermissions(value = {"sg:managementcenter:project:view", "sg:managementcenter:project:edit"}, logical = Logical.OR)
    @RequestMapping(value = "approvalForm")
    public String approvalForm(Project project, Model model) {
        project = projectService.getApproval(project);
        model.addAttribute("project", project);
        return "modules/sg/managementcenter/project/approvalForm";
    }







    /**
     * 保存表单
     */
    @ResponseBody
    @RequiresPermissions(value = {"sg:managementcenter:project:edit"}, logical = Logical.OR)
    @RequestMapping(value = "saveApproval")
    public AjaxJson saveApproval(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        Boolean flag = false;
        String str = "";
        /**
         * 后台hibernate-validation插件校验
         */
        String projectId = project.getProjectId();
        BigDecimal projectBudget = new BigDecimal(project.getApproval().getProjectBudget());
        String constructionCost = project.getApproval().getConstructionCost();
        String materialCost = project.getApproval().getMaterialCost();
        String designFee = project.getApproval().getDesignFee();
        String supervisionFee = project.getApproval().getSupervisionFee();
        String policyFee = project.getApproval().getPolicyFee();
        String otherExpenses = project.getApproval().getOtherExpenses();
        List<String> list = new ArrayList<>();
        if (!"".equals(constructionCost) && null != constructionCost) {
            list.add(constructionCost);
        }
        if (!"".equals(materialCost) && null != materialCost) {
            list.add(materialCost);
        }
        if (!"".equals(designFee) && null != designFee) {
            list.add(designFee);
        }

        if (!"".equals(supervisionFee) && null != supervisionFee) {
            list.add(supervisionFee);
        }
        if (!"".equals(policyFee) && null != policyFee) {
            list.add(policyFee);
        }
        if (!"".equals(otherExpenses) && null != otherExpenses) {
            list.add(otherExpenses);
        }
        BigDecimal totalAmount = new BigDecimal("0");
        for (String s : list) {
            totalAmount = totalAmount.add(new BigDecimal(s));
        }
        int i = projectBudget.compareTo(totalAmount);

        if (i != 0) {
            j.setSuccess(false);
            j.setMsg("合计金额不等于项目发文金额，请核实");
            return j;
        }

        Project planByName = projectService.findApprovalByName(projectId);
        List<Project> projectList = new ArrayList<>();
        //判断是不是空，是空insert新数据，不是空update数据
        projectList.add(project);
        if (planByName != null) {
            projectService.updateApprovalList(projectList);
        } else {
            projectService.insertApprovalList(projectList);
        }
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }




    /**
     * 修改项目关闭状态
     */
    @ResponseBody
    @RequestMapping(value = "updateClosure")
    public AjaxJson updateClosure(Project project, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        projectService.updateClosure(project);
        j.setSuccess(true);
        j.setMsg("修改成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Project project, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
//			project1.setProjectManageRole(UserUtils.getUser().getLoginName());
            String fileName = "需求基本信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            HttpSession session = request.getSession();
//			Project projectEpo = (Project)session.getAttribute("projectEpo");
            BasicInformation basicInformation = new BasicInformation();
            project.setBasicInformation(basicInformation);
            Page<Project> page = projectService.findPage(new Page<Project>(request, response, -1), project);
            new ExportExcel("需求基本信息", Project.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出需求基本信息记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 下载工程量模板文件
     */
    @RequestMapping(value = "approvalTemplate")
    public void approvalTemplate(HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        String fileName = "establishment.xlsx";
        String filePath = getClass().getResource("/freemarker/" + fileName).getPath();
        File f = new File(filePath);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("项目立项信息模板" + ".xlsx").getBytes(), "iso-8859-1"));//下载文件的名称
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(f));
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
    }



    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:managementcenter:project:import")
    @RequestMapping(value = "importApproval")
    public AjaxJson importApproval(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "项目立项信息");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            //将写入的文件先进行规则验证
            Map<String, Object> stringObjectMap = ProjectImportUtil.approvalValidation(importExcel, lastDataRowNum);
            //获取错误信息
            String errorMsg = (String) stringObjectMap.get("errorMsg");
            //获取需要导入的list
            List<Project> afterValidation = (List<Project>) stringObjectMap.get("afterValidation");
            List<Project> noCompareList = (List<Project>) stringObjectMap.get("noCompareList");
            if (afterValidation.size() > 0) {
                projectService.insertApprovalList(afterValidation);
            }
            if (noCompareList.size() > 0) {
                projectService.updateApprovalList(noCompareList);
            }
            int i = afterValidation.size() + noCompareList.size();
            List<Project> processList = new ArrayList<>();
            if (afterValidation.size() > 0) {
                processList.addAll(afterValidation);
            }
            if (noCompareList.size() > 0) {
                processList.addAll(noCompareList);
            }
            j.setMsg("已成功导入" + i + "条记录\n" + errorMsg);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    /**
     * 导入设计变更拆旧表Excel数据
     */
    @ResponseBody
    @RequestMapping(value = "importDesTear")
    public AjaxJson importDesTear(@RequestParam("file") MultipartFile file, String jumpName, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        List<Project> insertList = new ArrayList<>();
        List<Project> updateList = new ArrayList<>();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "拆旧表");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            for (int i = 2; i < lastDataRowNum; i++) {
                Row row = importExcel.getRow(i);
                TearDown tearDown = new TearDown();
                Project project = new Project();
                String reserveProjectName = importExcel.getCellValue(row, 1).toString();
                if (jumpName.equals(reserveProjectName)) {
                    Project byName = projectService.findByName(reserveProjectName);
                    if (null == byName) {
                        continue;
                    }
                    String reservedName = importExcel.getCellValue(row, 2).toString();
                    String reserveModel = importExcel.getCellValue(row, 3).toString();
                    String reserveUnit = importExcel.getCellValue(row, 4).toString();
                    String reserveNumber = importExcel.getCellValue(row, 5).toString();
                    String reserveNotes = importExcel.getCellValue(row, 6).toString();
                    if ("".equals(reserveNumber) || null == reserveNumber) {
                        reserveNumber = "0";
                    }
                    tearDown.setReservedName(reservedName);
                    tearDown.setReserveModel(reserveModel);
                    tearDown.setReserveUnit(reserveUnit);
                    tearDown.setReserveNumber("0");
                    tearDown.setReserveNotes("");
                    tearDown.setConfessionName(reservedName);
                    tearDown.setConfessionModel(reserveModel);
                    tearDown.setConfessionUnit(reserveUnit);
                    tearDown.setConfessionNumber("0");
                    tearDown.setConfessionNotes("");
                    tearDown.setChangeName(reservedName);
                    tearDown.setChangeModel(reserveModel);
                    tearDown.setChangeUnit(reserveUnit);
                    tearDown.setChangeNumber(reserveNumber);
                    tearDown.setChangeNotes(reserveNotes);
                    tearDown.setActualName(reservedName);
                    tearDown.setActualModel(reserveModel);
                    tearDown.setActualUnit(reserveUnit);
                    tearDown.setActualNumber("0");
                    tearDown.setActualNotes("");
                    project.setReserveProjectName(byName.getReserveProjectName());
                    project.setTearDown(tearDown);
                    Boolean notByName = projectService.isNotByName(reserveProjectName, reservedName);
                    if (notByName) {
                        updateList.add(project);
                    } else {
                        insertList.add(project);
                    }
                }
            }
            if (updateList.size() > 0) {
                projectService.updateDesTearList(updateList);
            }
            if (insertList.size() > 0) {
                projectService.insertTearList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("插入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    /**
     * 导入施工交底拆旧表Excel数据
     */
    @ResponseBody
    @RequestMapping(value = "importConTear")
    public AjaxJson importConTear(@RequestParam("file") MultipartFile file, String jumpName, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        List<Project> insertList = new ArrayList<>();
        List<Project> updateList = new ArrayList<>();
        try {
            ImportExcel importExcel = new ImportExcel(file, 1, "拆旧表");
            int lastDataRowNum = importExcel.getLastDataRowNum();
            for (int i = 2; i < lastDataRowNum; i++) {
                Row row = importExcel.getRow(i);
                TearDown tearDown = new TearDown();
                Project project = new Project();
                String reserveProjectName = importExcel.getCellValue(row, 1).toString();
                if (jumpName.equals(reserveProjectName)) {
                    Project byName = projectService.findByName(reserveProjectName);
                    if (null == byName) {
                        continue;
                    }
                    String reservedName = importExcel.getCellValue(row, 2).toString();
                    String reserveModel = importExcel.getCellValue(row, 3).toString();
                    String reserveUnit = importExcel.getCellValue(row, 4).toString();
                    String reserveNumber = importExcel.getCellValue(row, 5).toString();
                    String reserveNotes = importExcel.getCellValue(row, 6).toString();
                    if ("".equals(reserveNumber) || null == reserveNumber) {
                        reserveNumber = "0";
                    }
                    tearDown.setReservedName(reservedName);
                    tearDown.setReserveModel(reserveModel);
                    tearDown.setReserveUnit(reserveUnit);
                    tearDown.setReserveNumber("0");
                    tearDown.setReserveNotes("");

                    tearDown.setConfessionName(reservedName);
                    tearDown.setConfessionModel(reserveModel);
                    tearDown.setConfessionUnit(reserveUnit);
                    tearDown.setConfessionNumber(reserveNumber);
                    tearDown.setConfessionNotes(reserveNotes);

                    tearDown.setChangeName(reservedName);
                    tearDown.setChangeModel(reserveModel);
                    tearDown.setChangeUnit(reserveUnit);
                    tearDown.setChangeNumber("0");
                    tearDown.setChangeNotes("");

                    tearDown.setActualName(reservedName);
                    tearDown.setActualModel(reserveModel);
                    tearDown.setActualUnit(reserveUnit);
                    tearDown.setActualNumber("0");
                    tearDown.setActualNotes("");
                    project.setReserveProjectName(byName.getReserveProjectName());
                    project.setTearDown(tearDown);
                    Boolean notByName = projectService.isNotByName(reserveProjectName, reservedName);
                    if (notByName) {
                        updateList.add(project);
                    } else {
                        insertList.add(project);
                    }
                }
            }
            if (updateList.size() > 0) {
                projectService.updateConTearList(updateList);
            }
            if (insertList.size() > 0) {
                projectService.insertTearList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("插入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入需求基本信息表单失败！失败信息：" + e.getMessage());
        }
        return j;
    }




}