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.entity.Information;
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.activiti.entity.UploadImages;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.entity.ModuleBlock;
import com.jeeplus.modules.sg.managementcenter.project.entity.BasicInformation;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
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.materialmodule.activiti.service.NonPowerService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.activiti.engine.repository.ProcessDefinition;
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 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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/nonPower")
public class NonPowerController extends BaseController {
    @Autowired
    private NonPowerService nonPowerService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ConstructionService constructionService;

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


    /***************************************土建流程*************************************************/

    /**
     * 土建流程发起页面
     */
    @RequestMapping(value = "nonPowerForm")
    public String nonPowerForm(NonPower nonPower, Model model) {
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/nonPowerForm";
    }

    /**
     * 土建超权限流程发起页面
     */
    @RequestMapping(value = "superNonPower")
    public String superNonPower(NonPower nonPower, Model model) {
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/superNonPower";
    }

    /**
     * 土建开工流程
     */
    @RequestMapping(value = "nonPowerStart")
    public String nonPowerStart(NonPower nonPower, Model model) {
         //通过项目需求名称查询所有的施工交底土建信息
        List<EngineeringAmount> civilWorks = nonPowerService.findCivilWorks(nonPower.getReserveProjectName());
        if (civilWorks != null) {
            String constructionCivilWorks = "";
            for (EngineeringAmount e : civilWorks) {
                constructionCivilWorks += e.getCivilWorks() + e.getCivilMaterials() + e.getCivilUnit() + ",";
            }
            nonPower.setConstructionCivilWorks(constructionCivilWorks);
        }
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/nonPowerStart";
    }

    /**
     * 土建竣工
     */
    @RequestMapping(value = "nonPowerEnd")
    public String nonPowerEnd(NonPower nonPower, Model model) {
        //通过项目需求名称查询所有的施工交底土建信息
        List<EngineeringAmount> civilWorks = nonPowerService.findCivilWorks(nonPower.getReserveProjectName());
        if (civilWorks != null) {
            String constructionCivilWorks = "";
            for (EngineeringAmount e : civilWorks) {
                constructionCivilWorks += e.getCivilWorks() + e.getCivilMaterials() + e.getCivilUnit() + ",";
            }
            nonPower.setConstructionCivilWorks(constructionCivilWorks);
        }
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/nonPowerEnd";
    }

    /**
     * 土建流程上传文件页面
     */
    @RequestMapping(value = "nonPowerStartUpload")
    public String nonPowerStartUpload(UploadImages uploadImages, Model model) {
        model.addAttribute("uploadImages", uploadImages);
        return "modules/sg/materialmodule/activiti/nonPowerStartUpload";
    }

    /**
     * 在线验收
     */
    @RequestMapping(value = "acceptance")
    public String acceptance(NonPower nonPower, Model model) {
        //通过项目需求名称查询所有的施工交底土建信息
        List<EngineeringAmount> civilWorks = nonPowerService.findCivilWorks(nonPower.getReserveProjectName());
        if (civilWorks != null) {
            String constructionCivilWorks = "";
            for (EngineeringAmount e : civilWorks) {
                constructionCivilWorks += e.getCivilWorks() + e.getCivilMaterials() + e.getCivilUnit() + ",";
            }
            nonPower.setConstructionCivilWorks(constructionCivilWorks);
        }
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/acceptance";
    }

    /**
     * 审核土建竣工
     */
    @RequestMapping(value = "nonRePowerEnd")
    public String nonRePowerEnd(NonPower nonPower, Model model) {
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/nonRePowerEnd";
    }

    /**
     * 导出土建报告管理页面
     */
    @RequestMapping(value = "nonExportList")
    public String nonExportList(NonPower nonPower, Model model) {
        model.addAttribute("nonPower", nonPower);
        return "modules/sg/materialmodule/activiti/nonExportList";
    }

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

    /**
     * 发起土建流程
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(NonPower nonPower, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(nonPower);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        /**
         * 流程审批
         */
        if (StringUtils.isBlank(nonPower.getId())) {
            if ("".equals(nonPower.getProjectId())) {
                j.setSuccess(false);
                j.setMsg("请选择项目");
                return j;
            }
            Project project = new Project();
            project.setId(nonPower.getProjectId());
            //通过项目id获取项目定义号，项目名称及人员信息
            Project materialProject = projectService.getAss(project);
            //定义vars用于指派流程走向
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("nopass", false);
            vars.put("pass", true);
            //获取项目定义号
            vars.put("design", UserUtils.getByUserName(materialProject.getAssignment().getConstructionManage()).getLoginName());
            //保存基础信息到流程表中"
            nonPower.setProjectId(materialProject.getProjectId());
            nonPower.setProjectName(materialProject.getProjectName());
            nonPower.setReserveProjectName(materialProject.getReserveProjectName());
            //更改项目超权限状态
            projectService.updateAdvCon(nonPower.getReserveProjectName(),"2");
            nonPowerService.save(nonPower);
            //根据项目id修改项目的土建流程状态
            constructionService.updateAdvStatus(nonPower.getProjectId());
            // 启动流程
            ProcessDefinition p = actProcessService.getProcessDefinition(nonPower.getAct().getProcDefId());
            String title = nonPower.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcessNew(p.getKey(), "xm_nonpower_process", nonPower.getId(), title, vars);
            //新增或编辑表单保存
            j.setMsg("发起流程审批成功!");
            j.getBody().put("targetUrl", "/act/task/process/");
        }
        return j;
    }

    /**
     * 发起超权限土建流程
     */
    @ResponseBody
    @RequestMapping(value = "superSave")
    public AjaxJson superSave(NonPower nonPower, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(nonPower);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        /**
         * 流程审批
         */
        if (StringUtils.isBlank(nonPower.getId())) {
            if ("".equals(nonPower.getProjectId())) {
                j.setSuccess(false);
                j.setMsg("请选择项目");
                return j;
            }
            projectService.updateAdvCon(nonPower.getProjectName(), "1");
            // 启动流程
            //定义vars用于指派流程走向
            Map<String, Object> vars = Maps.newHashMap();
            ProcessDefinition p = actProcessService.getProcessDefinition(nonPower.getAct().getProcDefId());
            String title = nonPower.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            nonPower.setId("必要数值id");
            actTaskService.startProcessNew(p.getKey(), "xm_nonpower_process", nonPower.getId(), title, vars);
            //新增或编辑表单保存
            j.setMsg("授权成功，可手动发起土建流程!");
            j.getBody().put("targetUrl", "/act/task/process/");
        }
        return j;
    }

    /**
     * 导出土建开工报告
     * */
    @ResponseBody
    @RequestMapping(value = "civilStart")
    public AjaxJson exportCivilStart(NonPower nonPower, 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("civilStart.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();

        NonPower nonPower1 = nonPowerService.getById(nonPower.getId());
        String projectId = nonPower1.getProjectId();
        String projectName = nonPower1.getProjectName();
        String reserveProjectName = nonPower1.getReserveProjectName();
        String buildingUnit = nonPower1.getBuildingUnit();
        String projectNumber = nonPower1.getProjectNumber();
        String constructionUnit = nonPower1.getConstructionUnit();
        String plannedStart = nonPower1.getPlannedStart();
        String plannedEnd = nonPower1.getPlannedEnd();
        String projectManager = nonPower1.getProjectManager();
        String lineName = nonPower1.getLineName();
        String personInCharge = nonPower1.getPersonInCharge();
        String workPlace = nonPower1.getWorkPlace();

        String civilStartReport = nonPower1.getCivilStartReport();
        Date createDate = nonPower1.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("civilStartReport",civilStartReport );
        data.put("dateYear", dateYear);

        File docFile = new File(path + "\\土建开工报告.xls");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("土建开工报告.xls", docFile, response);

        return j;
    }

    /**
     * 导出土建竣工报告
     * */
    @ResponseBody
    @RequestMapping(value = "civilEnd")
    public AjaxJson exportCivilEnd(NonPower nonPower, 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("civilEnd.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        NonPower nonPower1 = nonPowerService.getById(nonPower.getId());
        String projectId = nonPower1.getProjectId();
        String projectName = nonPower1.getProjectName();
        String reserveProjectName = nonPower1.getReserveProjectName();
        BasicInformation basicInformation = nonPower1.getBasicInformation();
        String buildingUnit = nonPower1.getBuildingUnit();
        String projectNumber = nonPower1.getProjectNumber();
        String constructionUnit = nonPower1.getConstructionUnit();
        String plannedStart = nonPower1.getActualStart();
        String plannedEnd = nonPower1.getActualEnd();
        String projectManager = nonPower1.getProjectManager();
        String lineName = nonPower1.getLineName();
        String personInCharge = nonPower1.getPersonInCharge();
        String workPlace = nonPower1.getWorkPlace();
        String civilStartReport = nonPower1.getCivilStartReport();
        String civilEndReport = nonPower1.getCivilEndReport();
        Date createDate = nonPower1.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("civilEndReport",civilEndReport);
        data.put("dateYear", dateYear);

        File docFile = new File(path + "\\土建竣工报告.xls");
        FreemarkerUtil.generateFile(data, template, docFile);
        ResponseUtil.docResponse("土建竣工报告.xls", docFile, response);

        return j;
    }

    /**
     * 土建流程上传文件报错方法
     * */
    @ResponseBody
    @RequestMapping(value = "saveUpload")
    public AjaxJson saveOld(UploadImages uploadImages, Model model, HttpServletRequest request) throws Exception{
        AjaxJson j = new AjaxJson();
        NonPower nonPower = nonPowerService.get(uploadImages.getId());
        String reserveProjectName = nonPower.getReserveProjectName();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(uploadImages);
        if (StringUtils.isNotBlank(errMsg)){
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        String loginName = UserUtils.getUser().getName();
        uploadImages.setUid(loginName);
        uploadImages.setReserveProjectName(reserveProjectName);
        //保持上传文件
        nonPowerService.saveUpload(uploadImages);
        j.setSuccess(true);
        j.setMsg("上传文件成功");
        return j;
    }
    /***************************************土建流程*************************************************/
}


