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

import java.util.*;

import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyImportUtils;
import com.jeeplus.modules.sys.entity.User;

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.web.BaseController;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.Construction;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import org.activiti.engine.*;
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.*;

/**
 * 施工交底Controller
 *
 * @author
 * @version 2019-11-08
 */
@Controller
@RequestMapping(value = "${adminPath}/managementcenter/activiti")

public class ConstructionController extends BaseController {

    @Autowired
    private ConstructionService constructionService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProjectService projectService;

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


    /**
     * 查看，增加，编辑请假申请表单页面
     */
    @RequestMapping(value = "form/{mode}")
    public String form(@PathVariable String mode, Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
//		model.addAttribute("roleCodes");
        if ("add".equals(mode) || "edit".equals(mode)) {
            return "modules/sg/managementcenter/activiti/constructionForm";
        } else {//audit(施工单位，项目经理组织交底)
            return "modules/sg/managementcenter/activiti/constructionAudit";
        }

    }

    /**
     * 人工审核页面
     * */
    /**
     * 查看，增加，编辑请假申请表单页面
     */
    @RequestMapping(value = "artificial")
    public String form2(Construction construction, Model model) {
//        String proId = construction.getAct().getProcDefId();
//        String pInId = construction.getProcInsId();
//        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        RepositoryService rs = processEngine.getRepositoryService();
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/artificialJudgment";
    }

    /**
     * 配网运行人员判定设计变更
     * */
    @RequestMapping(value = "operatorDesignChange")
    public String form3(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/operatorDesignChange";
    }

    /*
              交底:判断项目是否需要关闭
           */
    @RequestMapping(value = "speciallyForm")
    public String speciallyForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/speciallyForm";
    }
    /*
      项目关闭，配网工程专职判定
   */
    @RequestMapping(value = "managerForm")
    public String managerForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/managerCloseForm";
    }
    /*
        项目关闭，配网运行人员
     */
    @RequestMapping(value = "memberForm")
    public String memberForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/memberForm";
    }


    /*
       项目关闭，配网系统专职
    */
    @RequestMapping(value = "departmentForm")
    public String departmentForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/departmentForm";
    }

/**
 * 政策处理
 * */
    @RequestMapping(value = "policiesChange")
    public String policiesChange(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/policiesChange";
    }



    /**
     * 政策处理项目经理判断是否需要继续
     * */
    @RequestMapping(value = "managerPolicesChange")
    public String managerPolicesChange(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/managerPolicesChange";
    }

    /**
     * 经研所审核页面
     * */
    @RequestMapping(value = "economicsDesignChange")
    public String form4(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/economicsDesignChange";
    }

    /**
     * 项目经理判断是否继续设计变更
     * */
    @RequestMapping(value = "managerDesignChange")
    public String managerDesignChange(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/managerDesignChange";
    }

    /**政处处理（行政政处）*/

    /**
     * 上传未盖章施工方案（行政政处开始）
     * */
    @RequestMapping(value = "coveredForm")
    public String coveredForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/coveredForm";
    }

    /**
     * 施工方案盖章
     * */
    @RequestMapping(value = "sealForm")
    public String sealForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/sealForm";
    }



/*    *//**
     * 项目经理判断是否需要政策处理（行政政处）
     * *//*
    @RequestMapping(value = "sealForm")
    public String sealForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/sealForm";
    }*/

    /**
     * 上传收据
     * */
    @RequestMapping(value = "receiptForm")
    public String receiptForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/receiptForm";
    }
    /*
        项目经理
     */
    @RequestMapping(value = "phaseManagerForm")
    public String phaseManagerForm(Construction construction, Model model){
        model.addAttribute("construction",construction);
        return "modules/sg/managementcenter/activiti/phaseManageForm";
    }
    /**
     * 上传缴费单
     * */
    @RequestMapping(value = "singleForm")
    public String singleForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/singleForm";
    }

    /**
     * 上传借款单据
     * */
    @RequestMapping(value = "documentsForm")
    public String documentsForm(Construction construction, Model model) {
        //根据流程定义号获取所有的定义流程
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/documentsForm";
    }

    /**
     * 配网运行人员判定设计变更
     * 人工审核页面
     * */
    @RequestMapping(value = "humanReview")
    public String humanReviewform(Construction construction, Model model) {
//        String proId = construction.getAct().getProcDefId();
//        String pInId = construction.getProcInsId();
//        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        RepositoryService rs = processEngine.getRepositoryService();
        //根据流程定义号获取所有的定义流程
        MyImportUtils.getTheEcho(construction,model);
        model.addAttribute("construction", construction);
        return "modules/sg/managementcenter/activiti/humanReview";
    }

    /**
     * 保存请假申请
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(Construction construction, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(construction);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        /**
         * 流程审批
         */
    if (StringUtils.isBlank(construction.getId())) {
        //获取流程图id
        String procDefId = construction.getAct().getProcDefId();
        //用于记录未发起的流程原因
        String info = "";
        //用户修改发起流程后的项目状态
        Project newProject = new Project();
        //定义vars用于指派流程走向
        Map<String, Object> vars = Maps.newHashMap();
        //获取选择的项目信息id
        String projectId = construction.getProjectId();
        //项目施工单位字段定义
        String constructionUnit = "";
        //定义施工单位角色
        String constructionUnitRole = "";
        //定义项目经理角色
        String projectManageRole = "";
        //根据，分割得到选择项目的id数组
        String[] proListId = projectId.split(",");
        //根据数组查询得到项目信息
        List<Project> listById = projectService.findListById(proListId);
        //循环项目信息
            for (Project each : listById) {
                //从项目信息种获取交底类型
                constructionUnit = each.getClarificaitonType();
                //如果施工单位不为空，系统判读施工单位交底
                if ("施工单位自行交底".equals(constructionUnit)) {
                    //施工单位交底
                    //获取施工单位角色
                    constructionUnitRole = each.getConstructionUnitRole();
                    //查询是否有此登录名用户
                    User user = constructionService.queryPerson(constructionUnitRole);
                    //如果查询不为空表示有用户，为空没有此用户
                    if (user != null) {
                        //有此用户-施工单位交底
                        vars.put("company", true);
                        vars.put("manager", false);
                        vars.put("processer", constructionUnitRole);
                        String id = each.getId();
                        construction.setApplyName(constructionUnitRole);
                        construction.setProjectId(id);
                        construction.setProjectName(each.getRequireName());
                        construction.setAcceptDate(new Date());
                        constructionService.newSave(construction);//保存
                        newProject.setStatus("1");
                        newProject.setId(id);
                        projectService.updateStatus(newProject);
                        String procDefKey = construction.getAct().getProcDefKey();
                        // 启动流程
                        try {
                            ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                            String title = construction.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                            actTaskService.startProcessNew(p.getKey(), "xm_construction_clarificaiton", construction.getId(), title, vars);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        //没有此用户
                        info += ("项目："+each.getRequireName()+"没有此施工单位人员，请核实。");
                        continue;
                    }
                } else {
                    //项目经理交底
                    //获取项目经理角色
                    projectManageRole = each.getProjectManageRole();
                    //查询是否有此登录名用户
                    User user = constructionService.queryPerson(projectManageRole);
                    //查询是否有此用户
                    if (user != null) {
                        //有此用户
                        vars.put("company", false);
                        vars.put("manager", true);
                        vars.put("processer", projectManageRole);
                        String id = each.getId();
                        construction.setApplyName(projectManageRole);
                        construction.setProjectId(id);
                        construction.setProjectName(each.getRequireName());
                        construction.setAcceptDate(new Date());
                        constructionService.newSave(construction);//保存
                        newProject.setStatus("1");
                        newProject.setId(id);
                        projectService.updateStatus(newProject);
                        String procDefKey = construction.getAct().getProcDefKey();
                        // 启动流程
                        ProcessDefinition p = actProcessService.getProcessDefinition(construction.getAct().getProcDefId());
                        String title = construction.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                        actTaskService.startProcessNew(p.getKey(), "xm_construction_clarificaiton", construction.getId(), title, vars);
                    } else {
                        //没有此用户
                        info += ("项目："+each.getRequireName()+"没有此项目经理，请核实。");
                        continue;
                    }
                }
            }
            //新增或编辑表单保存
            j.setMsg("发起流程审批成功!"+info);
            j.getBody().put("targetUrl", "/act/task/process/");
        }
        return j;
    }



}