package com.jeeplus.modules.sg.materialmodule.activiti.web;

import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
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.entity.EngineeringAmount;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.materialmodule.activiti.entity.MaterialModule;
import com.jeeplus.modules.sg.materialmodule.activiti.entity.NonPower;
import com.jeeplus.modules.sg.materialmodule.activiti.service.MaterialModuleService;
import com.jeeplus.modules.sg.picking.activiti.entity.CapitalExport;
import com.jeeplus.modules.sys.utils.UserUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.activiti.engine.repository.ProcessDefinition;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/materialmodule/activiti")
public class MaterialModuleController extends BaseController {
    @Autowired
    private MaterialModuleService materialModuleService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private ProjectService projectService;

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

    /**
     * 施工模块发起页面
     */
    @RequestMapping(value = "materialModuleForm")
    public String materialModuleForm(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/materialModuleForm";
    }

    /**
     * 电气开工报告页面
     */
    @RequestMapping(value = "electricalStart")
    public String electricalStart(MaterialModule materialModule, Model model) {
        //查询项目的日计划作业模式
        String planDay = materialModuleService.findPlanDay(materialModule.getReserveProjectName());
        if (null != planDay && !"".equals(planDay)) {
            materialModule.setOperationMethod(planDay);
        } else {
            materialModule.setOperationMethod("未安排项目计划安排");
        }
        //查询开领料单进场施工材料
        List<EngineeringAmount> processList = materialModuleService.findProcessList(materialModule.getReserveProjectName());
        if (null == processList || processList.size() <= 0) {

        } else {
            String a = "";
            for (EngineeringAmount e : processList
            ) {
                a += e.getCivilMaterials() + e.getCivilUnit() + ";";
            }
            materialModule.setNewWorkload(a);
        }

        //拆旧表
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/electricalStart";
    }

    /**
     * 电气竣工页面
     * */
    @RequestMapping(value = "electricalEnd")
    public String electricalEnd(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/electricalEnd";
    }


    /**
     * 施工单位项目经理判断项目是否包含涉电工作
     */
    @RequestMapping(value = "managerWhether")
    public String managerWhether(MaterialModule materialModule, Model model) {
        MaterialModule materialShow = materialModuleService.get(materialModule.getAct().getProcInsId());
        model.addAttribute("materialShow", materialShow);
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/managerWhether";
    }

    /**
     * 审核电气竣工流程
     * */
    @RequestMapping(value = "reElectricalEnd")
    public String reElectricalEnd(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/reElectricalEnd";
    }

    /**
     * 上传涉电开工资料
     * */
    @RequestMapping(value = "powerFile")
    public String powerFile(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/powerFile";
    }

    /**
     * 涉电竣工报告
     * */
    @RequestMapping(value = "PowerEnd")
    public String PowerEnd(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/PowerEnd";
    }

    /**
     * 审核涉电竣工报告
     * */
    @RequestMapping(value = "rePowerEnd")
    public String rePowerEnd(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/rePowerEnd";
    }

    /**
     * 审核涉电竣工报告
     * */
    @RequestMapping(value = "PowerWhether")
    public String PowerWhether(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/PowerWhether";
    }

    /**
     * 导出涉电电气报告管理页面
     * */
    @RequestMapping(value = "exportPowerList")
    public String exportPowerList(MaterialModule materialModule, Model model) {
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/exportPowerList";
    }

    /**
     * 导出土建数据展示页面
     */
    @ResponseBody
    @RequestMapping(value = "exportListData")
    public Map<String, Object> exportListData(MaterialModule materialModule, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<MaterialModule> page = materialModuleService.findListPage(new Page<MaterialModule>(request, response), materialModule);
        return getBootstrapData(page);
    }

    /**
     * 涉电开工报告
     * */
    @RequestMapping(value = "PowerStart")
    public String PowerStart(MaterialModule materialModule, Model model) {
        //查询项目的日计划作业模式
        String planDay = materialModuleService.findPlanDay(materialModule.getReserveProjectName());
        if (null != planDay && !"".equals(planDay)) {
            materialModule.setOperationMethod(planDay);
        } else {
            materialModule.setOperationMethod("未安排项目计划安排");
        }
        //查询开领料单进场施工材料
        List<EngineeringAmount> processList = materialModuleService.findProcessList(materialModule.getReserveProjectName());
        if (null == processList || processList.size() <= 0) {

        } else {
            String a = "";
            for (EngineeringAmount e : processList
            ) {
                a += e.getCivilMaterials() + e.getCivilUnit() + ";";
            }
            materialModule.setNewWorkload(a);
        }
        model.addAttribute("materialModule", materialModule);
        return "modules/sg/materialmodule/activiti/PowerStart";
    }

    /**
     * 施工流程发起
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(MaterialModule materialModule, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(materialModule);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        String projectId = materialModule.getProjectId();
        if (projectId == null || "".equals(projectId)) {
            j.setSuccess(false);
            j.setMsg("请选择项目");
            return j;
        }
        boolean electric = false;
        //判单钢管杠，水泥杠，存在电气，判断是否包含
        List<MaterialInfo> allInfo = projectService.findAllInfo(projectId);
        if (allInfo.size() > 0) {
            for (MaterialInfo mi : allInfo
            ) {
                String materialName = mi.getMaterialName();
                if (null != materialName && !"".equals(materialName)) {
                    //判断项目是否包含描述为钢管杆或水泥杠的物料，存在步入电气流程
                    if (materialName.contains("钢管杆") || materialName.contains("水泥杆")) {
                        electric = true;
                        break;
                    }
                }
            }
        }
        //查询出项目的基础信息，停电线路（如果纯在），人员流转信息
        Construction blockAss = projectService.findBlockAss(projectId);
        Map<String, Object> vars = Maps.newHashMap();
        //没用电气及涉电 运行条件
        vars.put("no", false);
        //没有电气，有涉电 运行条件
        vars.put("notContain", false);
        //包含电气/涉电-优先电气 运行条件
        vars.put("electrical", false);
        if (electric) {
            //发送开始电气流程
            vars.put("electrical", true);
        } else {
            //没用电气进行涉电
            //获取项目的领料单，查询停电线路
            String blackoutLine = blockAss.getQuantity().getBlackoutLine();
            if (null != blackoutLine && !"".equals(blackoutLine) && "不涉电".equals(blackoutLine)) {
                //填写停电线路,不为空，-步入发起涉电流程
                vars.put("notContain", true);
            } else {
                vars.put("no", true);
            }
        }

        if (StringUtils.isBlank(materialModule.getId())) {
            vars.put("manager", UserUtils.getByUserName(blockAss.getAssignment().getConstructionManage()).getLoginName());
            materialModule.setProjectId(blockAss.getProjectId());
            materialModule.setProjectName(blockAss.getProjectName());
            materialModule.setReserveProjectName(blockAss.getReserveProjectName());
            //保存项目储备项目名称，项目定义号，项目名称
            materialModuleService.save(materialModule);
            //修改项目状态
            materialModuleService.updateConstructionStatus("1", blockAss.getReserveProjectName());
            // 启动流程
            ProcessDefinition p = actProcessService.getProcessDefinition(materialModule.getAct().getProcDefId());
            String title = materialModule.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcess(p.getKey(), "sg_construction_process", materialModule.getId(), title, vars);
            j.setMsg("发起施工流程成功!");
            j.getBody().put("targetUrl", "/act/task/process/");
        }
        return j;
    }

    /**
     * 导出涉电-电气开工报告
     * */
    @ResponseBody
    @RequestMapping(value = "electricityStart")
    public AjaxJson exportElectricityStart(MaterialModule materialModule, HttpServletRequest request, HttpServletResponse response){
        AjaxJson j = new AjaxJson();
        Template template = null;
        File path = new File(this.getClass().getResource("/").getPath() + "/freemarker");
        Configuration cfg = new Configuration();
        try {
            cfg.setDefaultEncoding("UTF-8");
            //配置cfg对象
            cfg.setDirectoryForTemplateLoading(path);
//            根据模板名称获取Template对象
            template = cfg.getTemplate("electricityStart.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        MaterialModule materialModule1 = materialModuleService.findById(materialModule.getId());
        String projectName = materialModule1.getProjectName();
        String buildingUnit = materialModule1.getBuildingUnit();
        String projectNumber = materialModule1.getProjectNumber();
        String constructionUnit = materialModule1.getConstructionUnit();
        String plannedStart = materialModule1.getPlannedStart();
        String plannedEnd = materialModule1.getPlannedEnd();
        String projectManager = materialModule1.getProjectManager();
        String lineName = materialModule1.getLineName();
        String personInCharge = materialModule1.getPersonInCharge();
        String workPlace = materialModule1.getWorkPlace();
        String wayOfWorking = materialModule1.getWayOfWorking();
        String startConstruction = materialModule1.getStartConstruction();
        String startLoad = materialModule1.getStartLoad();
        String startCrossover = materialModule1.getStartCrossover();

        Date createDate = materialModule1.getCreateDate();
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String dateYear = df.format(createDate);

        data.put("projectName", projectName);
        data.put("projectNumber",projectNumber );
        data.put("buildingUnit", buildingUnit);
        data.put("constructionUnit", constructionUnit);
        data.put("plannedStart",plannedStart );
        data.put("projectManager", projectManager);
        data.put("personInCharge", personInCharge);
        data.put("plannedEnd", plannedEnd);
        data.put("lineName",lineName );
        data.put("workPlace", workPlace);
        data.put("dateYear", dateYear);
        data.put("wayOfWorking", wayOfWorking);
        data.put("startConstruction", startConstruction);
        data.put("startLoad", startLoad);
        data.put("startCrossover", startCrossover);

        File docFile = new File(path + "\\开工报告-电气（含涉电）.xls");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("开工报告-电气（含涉电）.xls", docFile, response);
        return j;
    }

    /**
     * 竣工报告-涉电（含电气）
     * */
    @ResponseBody
    @RequestMapping(value = "electricityEnd")
    public AjaxJson electricityEnd(MaterialModule materialModule, HttpServletRequest request, HttpServletResponse response){
        AjaxJson j = new AjaxJson();
        Template template = null;
        File path = new File(this.getClass().getResource("/").getPath() + "/freemarker");
        Configuration cfg = new Configuration();
        try {
            cfg.setDefaultEncoding("UTF-8");
            //配置cfg对象
            cfg.setDirectoryForTemplateLoading(path);
//            根据模板名称获取Template对象
            template = cfg.getTemplate("electricityEnd.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        MaterialModule materialModule1 = materialModuleService.findById(materialModule.getId());
        String projectName = materialModule1.getProjectName();
        String buildingUnit = materialModule1.getBuildingUnit();
        String projectNumber = materialModule1.getProjectNumber();
        String constructionUnit = materialModule1.getConstructionUnit();
        String actualStart = materialModule1.getActualStart();
        String projectManager = materialModule1.getProjectManager();
        String personInCharge = materialModule1.getPersonInCharge();
        String actualEnd = materialModule1.getActualEnd();
        String lineName = materialModule1.getLineName();
        String workPlace = materialModule1.getWorkPlace();
        String completedWork = materialModule1.getCompletedWork();
        String endConstruction = materialModule1.getEndConstruction();
        String endLoad = materialModule1.getEndLoad();
        String endCrossover = materialModule1.getEndCrossover();

        Date createDate = materialModule1.getCreateDate();
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String dateYear = df.format(createDate);

        data.put("projectName", projectName);
        data.put("projectNumber",projectNumber );
        data.put("buildingUnit", buildingUnit);
        data.put("constructionUnit", constructionUnit);
        data.put("actualStart",actualStart );
        data.put("projectManager", projectManager);
        data.put("personInCharge", personInCharge);
        data.put("actualEnd", actualEnd);
        data.put("lineName",lineName );
        data.put("workPlace", workPlace);
        data.put("dateYear", dateYear);
        data.put("completedWork", completedWork);
        data.put("endConstruction", endConstruction);
        data.put("endLoad", endLoad);
        data.put("endCrossover", endCrossover);

        File docFile = new File(path + "\\竣工报告-涉电（含电气）.xls");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("竣工报告-涉电（含电气）.xls", docFile, response);
        return j;
    }
}


