package com.jeeplus.modules.workprojectcompletion.web;


import com.google.common.base.Strings;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullPay;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workprojectcompletion.dao.WorkProjectCompletionDao;
import com.jeeplus.modules.workprojectcompletion.entity.WorkProjectCompletionInfo;
import com.jeeplus.modules.workprojectcompletion.service.WorkProjectCompletionService;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 项目竣工
* */
@Controller
@RequestMapping(value = "${adminPath}/workprojectcompletion/workProjectCompletion")
public class WorkProjectCompletionController extends BaseController {


    @Autowired
    private WorkProjectCompletionService workProjectCompletionService;

    @Autowired
    private WorkClientInfoService workClientInfoService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private WorkProjectCompletionDao workProjectCompletionDao;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

    @Autowired
    private WorkFullManageService workFullManageService;

    @Autowired
    private ActivityService activityService;

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


    @RequiresPermissions("workprojectcompletion:workprojectcompletion:workFullManageList")
    @RequestMapping("/workFullManageList")
    public String workFullManageList(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (workFullManage!=null && StringUtils.isNotBlank(workFullManage.getProjectId())){
            workFullManage = workFullManageService.get(workFullManage.getProjectId());
        }
        if(!UserUtils.getSelectRoleInfo()){
            String id = UserUtils.getUser().getId();
            workFullManage.setQueryCon(id);
            workFullManage.setMasterId(UserUtils.getUser().getId());
        }
        //查询项目归档的数据
        Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response), workFullManage);
        List<WorkFullManage> list = page.getList();
        for (WorkFullManage workFull:list){
            if(!Strings.isNullOrEmpty(workFull.getHostMaster())){
                String[] split = workFull.getHostMaster().split(",");
                String hostMasterName = workFullManageService.getPeople(split);
                workFull.setHostMasterName(hostMasterName);
            }

            if(!Strings.isNullOrEmpty(workFull.getFollowMaster())){
                String[] split1 = workFull.getFollowMaster().split(",");
                String followMasterName = workFullManageService.getPeople(split1);
                workFull.setFollowMasterName(followMasterName);
            }
            if(!Strings.isNullOrEmpty(workFull.getHostMember())){
                String[] split2 = workFull.getHostMember().split(",");
                String hostMemberName = workFullManageService.getPeople(split2);
                workFull.setHostMemberName(hostMemberName);
            }
            if(!Strings.isNullOrEmpty(workFull.getFollowMember())){
                String[] split3 = workFull.getFollowMember().split(",");
                String followMemberName = workFullManageService.getPeople(split3);
                workFull.setFollowMemberName(followMemberName);
            }
            WorkProjectCompletionInfo workProjectCompletionInfo = workProjectCompletionService.getByProjectId(workFull.getId());
            if(workProjectCompletionInfo!=null && StringUtils.isNotBlank(workProjectCompletionInfo.getProcessInstanceId())){
                boolean state = actTaskService.isProcessEnd(workProjectCompletionInfo.getProcessInstanceId());
                if (state){
                    workFull.setQueryCon("true");
                }
            }
        }
        //查询是否存没有已通过的信息
        page.setList(list);
        model.addAttribute("page", page);
        return "modules/workprojectcompletion/workFullManageCompletionList";
    }
    /*
    * 项目竣工列表
    * 查询所有的
    * */
//    @RequiresPermissions(value={"workprojectcompletion:workProjectCompletion:list"})
//    @RequestMapping(value = {"list", ""})
//    public String  getList(WorkProjectCompletionInfo workProjectCompletionInfo, HttpServletRequest request, HttpServletResponse response, Model model){
//        Page<WorkProjectCompletionInfo> page = workProjectCompletionService.findPage(new Page<WorkProjectCompletionInfo>(request, response), workProjectCompletionInfo);
//        model.addAttribute("page", page);
//        return "modules/workprojectcompletion/workProjectCompletionList";
//    }
    /*
    * 流程追踪
    * */
    /**
     * 读取单个实体流程
     * @return
     */
    @RequestMapping(value = "getProcess")
    public String getProcessOne(WorkProjectCompletionInfo workProjectCompletionInfo, Model model) {
        model.addAttribute("processInstanceId", workProjectCompletionInfo.getProcessInstanceId());
        return "modules/workprojectcompletion/workProjectCompletionTask";
    }

    @RequestMapping(value = "form")
    public String startProcess(WorkProjectCompletionInfo workProjectCompletionInfo,Model model){
        String projectId = request.getParameter("projectId");
        WorkFullManage workFullManage = workFullManageService.get(projectId);
        String tabId = request.getParameter("tabId");
        String view = "workProjectCompletionForm";
        if("1".equals(tabId)){
            if(workProjectCompletionInfo != null){
                ProcessInstance processInstance = actTaskService.getProcIns(workProjectCompletionInfo.getProcessInstanceId());
                if (processInstance != null) {
                    Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                    Act act = new Act();
                    act.setTaskId(taskInfok.getId());
                    act.setTaskName(taskInfok.getName());
                    act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                    act.setProcDefId(taskInfok.getProcessDefinitionId());
                    act.setProcInsId(taskInfok.getProcessInstanceId());
                    act.setTask(taskInfok);
                    workProjectCompletionInfo.setAct(act);
                }
            }
            view = "workProjectCompletionEdit";
        }
        // 环节编号
        String taskDefKey = workProjectCompletionInfo.getAct().getTaskDefKey();
        // 查看工单
        if(StringUtils.isNotBlank(taskDefKey) && workProjectCompletionInfo.getAct().isFinishTask()){
            view = "workReimbursementView";
        }
        // 修改环节
        else if ("bmzr".equals(taskDefKey) || (taskDefKey!=null && taskDefKey.contains("task"))){
            view = "workProjectCompletiontAudit";
        }
        model.addAttribute("workFullManage",workFullManage);
        model.addAttribute("workProjectCompletionInfo",workProjectCompletionInfo);
        return "modules/workprojectcompletion/" + view;
    }

    /*
    * 发起项目竣工流程
    * */
    @RequestMapping("save")
    public String projectSave(WorkProjectCompletionInfo workProjectCompletionInfo, Model model,  RedirectAttributes redirectAttributes){
        if (!beanValidator(model, workProjectCompletionInfo)){
            return startProcess(workProjectCompletionInfo, model);
        }
        String projectId = request.getParameter("projectId");
        workProjectCompletionInfo.setProjectId(projectId);
        workProjectCompletionInfo.setProjectStatus("1");
        if(!workProjectCompletionInfo.getIsNewRecord()){
            Map<String, Object> variables = new HashMap<String, Object>();
            Role role = UserUtils.getSelectRole().get(0);
            StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
            variables.put("SSRHbmzr", buffer.toString()+"bmzr"); //设置部门负责人
            variables.put("applyUserId",workProjectCompletionInfo.getCreateBy().getId());
            workProjectCompletionInfo.preUpdate();
            workProjectCompletionService.save(workProjectCompletionInfo,variables);
        }else {//新增表单保存
            //SSRHbmzr 部门负责人
            Map<String, Object> variables = new HashMap<String, Object>();
            Role role = UserUtils.getSelectRole().get(0);
            StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
            variables.put("SSRHbmzr", buffer.toString()+"bmzr"); //设置部门负责人
            variables.put("applyUserId",UserUtils.getUser().getId());
            workProjectCompletionService.save(workProjectCompletionInfo,variables);
            //删除已经启动的流程

        }
        return  "redirect:"+ Global.getAdminPath()+"/workprojectcompletion/workProjectCompletion/workFullManageList?repage";
    }

    /*
    * 发起项目竣工流程
    * */
    @RequestMapping("store")
    public String store(WorkProjectCompletionInfo workProjectCompletionInfo, Model model,  RedirectAttributes redirectAttributes){
        if (!beanValidator(model, workProjectCompletionInfo)){
            return startProcess(workProjectCompletionInfo, model);
        }
        String projectId = request.getParameter("projectId");
        workProjectCompletionInfo.setProjectId(projectId);
        if("4".equals(workProjectCompletionInfo.getProjectStatus())){
            workProjectCompletionInfo.setDelFlag("1");
            workProjectCompletionService.updateFlag(workProjectCompletionInfo);
            workProjectCompletionInfo.setId("");
            workProjectCompletionInfo = new WorkProjectCompletionInfo();
            workProjectCompletionInfo.setProjectId(projectId);
        }
        workProjectCompletionInfo.setProjectStatus("0");
        if(!workProjectCompletionInfo.getIsNewRecord()){
            workProjectCompletionService.save(workProjectCompletionInfo);
        }else {//新增表单保存
            workProjectCompletionService.save(workProjectCompletionInfo);
        }
        return  "redirect:"+ Global.getAdminPath()+"/workprojectcompletion/workProjectCompletion/workFullManageList?repage";
    }

    //获取待办信息
    @RequestMapping(value = "toDoList")
    public String getToDoList(Act act, HttpServletRequest request,HttpServletResponse response, Model model){
        /*act.setProcDefKey(ActUtils.PD_WORKCOMPLETE[0]);
        List<Act> list = actTaskService.todoList(act);*/
        act.setProcDefKey("projectCompleteAudit");
        List<Act> list = new ArrayList<>();
        list.addAll(actTaskService.todoList(act));
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<Activity> activities = activityService.groupByActivityMenu("28bc804ba6df46ab807b3fd30aa72e65",companyId);
        for (Activity activity:activities){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(actTaskService.todoList(act));
        }

        Role role = UserUtils.getSelectRole().get(0);
        String officeId = "";
        if ("4".equals(role.getDataScope())){
            User user = UserUtils.getUser();
            officeId = user.getOffice().getId();
        }
        List<WorkProjectCompletionInfo> lists = new ArrayList<WorkProjectCompletionInfo>();
        for (Act a : list) {
            if(!"modifyApply".equals(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().contains("audit")) {
                WorkProjectCompletionInfo workProjectCompletionInfo = workProjectCompletionService.getByProcessInstanceId(a.getProcInsId());
                if(workProjectCompletionInfo != null){
                    WorkFullManage workFullManage = workFullManageService.get(workProjectCompletionInfo.getProjectId());
                    if (workFullManage != null && workFullManage.getCompanyId().equals(companyId)) {
                        User createBy = UserUtils.get(workProjectCompletionInfo.getCreateBy().getId());
                        if (StringUtils.isNotBlank(officeId)) {
                            if (officeId.equals(createBy.getOffice().getId())) {
                                if (a.getVars().getMap().get("applyUserId") != null) {
                                    User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
                                    if (user != null) {
                                        a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                                    }
                                }
                                workProjectCompletionInfo.setAct(a);
                                lists.add(workProjectCompletionInfo);
                            }
                        } else {
                            if (a.getVars().getMap().get("applyUserId") != null) {
                                User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
                                if (user != null) {
                                    a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                                }
                            }
                            workProjectCompletionInfo.setAct(a);
                            lists.add(workProjectCompletionInfo);
                        }
                    }
                }
            }
        }
        Page page=  new Page<WorkProjectCompletionInfo>(request, response);
        page.setList(lists);
        model.addAttribute("page", page);
        return "modules/workprojectcompletion/workProjectCompletionToDoList";
    }

    //获取已办 HistoryList
    @RequestMapping(value = "HistoryList")
    public String getHostoryList(WorkProjectCompletionInfo workProjectCompletionInfo,Act act, HttpServletRequest request,RedirectAttributes redirectAttributes, HttpServletResponse response, Model model) {
        act.setProcDefKey(ActUtils.PD_WORKCOMPLETE[0]);
        act.setProcDefKey("workfullpay");
        List<WorkProjectCompletionInfo> page = workProjectCompletionService.historicList(act);
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();

        List<Activity> activities = activityService.groupByActivityMenu("28bc804ba6df46ab807b3fd30aa72e65",companyId);
        for (Activity activity:activities){
            act.setProcDefKey(activity.getProcessKey());
            page.addAll(workProjectCompletionService.historicList(act));
        }

        model.addAttribute("list",page);
        //List<WorkProjectCompletionInfo> page = workProjectCompletionService.historicList(act);
        model.addAttribute("list", page);
        return "modules/workprojectcompletion/workProjectCompletionHistoryList";
    }

    @RequestMapping("saveAudit")
    public String saveAudit(WorkProjectCompletionInfo workProjectCompletionInfo, Model model, RedirectAttributes redirectAttributes){
        String taskDefKey = workProjectCompletionInfo.getAct().getTaskDefKey();
        //当状态为未通过时，重新修改数据
        if ("modifyApply".equals(taskDefKey)) {
            workProjectCompletionInfo.getAct().setComment("重新申请");
        } //else{
//            if (StringUtils.isBlank(workProjectCompletionInfo.getAct().getComment())){
//                addMessage(model, "请填写审核意见。");
//                return startProcess(workProjectCompletionInfo, model);
//            }
//        }
        String str = workProjectCompletionService.auditSave(workProjectCompletionInfo);
        addMessage(redirectAttributes, str);
        return  "redirect:"+ Global.getAdminPath()+"/workprojectcompletion/workProjectCompletion/toDoList?repage";
    }
    /*
    * 查看
    * */
    @RequestMapping("lookForm")
    public String getLookForm(WorkProjectCompletionInfo workProjectCompletionInfo, Model model){
        String projectId = request.getParameter("projectId");
        if(Strings.isNullOrEmpty(projectId)){
            projectId = workProjectCompletionInfo.getProjectId();
        }
        WorkFullManage workFullManage = workFullManageService.get(projectId);
        model.addAttribute("workFullManage",workFullManage);
        model.addAttribute("workProjectCompletionInfo", workProjectCompletionInfo);
        return "modules/workprojectcompletion/workProjectCompletionLookForm";
    }

    @RequestMapping("delete")
     public String  deleteProject(WorkProjectCompletionInfo workProjectCompletionInfo, RedirectAttributes redirectAttributes){
//        String userId = UserUtils.getUser().getId();
//        String leaderId []=workProjectCompletionInfo.getProjectLeaderId().split(",");
//        List<String> list= Arrays.asList(leaderId);
//        if(list.contains(userId)){
//            workProjectCompletionService.deleteProject(workProjectCompletionInfo.getProjectId());
//            addMessage(redirectAttributes, "删除成功");
//        }else {
//            addMessage(redirectAttributes, "您没有删除权限");
//        }
        return  "redirect:"+ Global.getAdminPath()+"/workprojectcompletion/workProjectCompletion/?repage";
    }

    /**
     * 审核信息
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "applyOnLeave")
    public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
        String projectId = request.getParameter("projectId");
        // 获取流程XML上的表单KEY
        String formKey = "/workprojectcompletion/workProjectCompletion/form?projectId="+projectId;
//        String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
        // 获取流程实例对象
        if (act.getProcInsId() != null){
            if(actTaskService.getProcIns(act.getProcInsId())!=null){
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            }else{
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        return "redirect:" + ActUtils.getFormUrl(formKey, act);
    }

}
