package com.jeeplus.modules.projectAssess.web;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
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.projectAssess.entity.ProjectAssessInfo;
import com.jeeplus.modules.projectAssess.service.ProjectAssessService;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workadministrativeatamp.entity.WorkAdministrativeAtamp;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workgooutapply.entity.WorkGoOutInfo;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.worksealform.entity.WorkSealForm;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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

/**
 * 项目评估Controller
 * @author 徐滕
 * @version 2020-05-08
 */
@Controller
@RequestMapping(value = "${adminPath}/project/projectAssess")
public class ProjectAssessController extends BaseController {

    @Autowired
    private ProjectAssessService projectAssessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    protected HistoryService historyService;

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

    /**
     * 查询项目评估信息
     * @param projectAssessInfo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("project:projectAssess:list")
    @RequestMapping(value = {"list", ""})
    public String list(ProjectAssessInfo projectAssessInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        if(UserUtils.isManager()){
            model.addAttribute("flag","1");
        }
        Page<ProjectAssessInfo> page = projectAssessService.findPage(new Page<ProjectAssessInfo>(request, response), projectAssessInfo);
        model.addAttribute("page", page);
        model.addAttribute("companyName",projectAssessInfo.getCompanyName());
        model.addAttribute("projectName",projectAssessInfo.getProjectName());
        model.addAttribute("beginDate",projectAssessInfo.getBeginDate());
        model.addAttribute("endDate",projectAssessInfo.getEndDate());
        return "modules/projectAssess/projectAssessList";
    }

    /**
     * 查看，增加，编辑开票管理表单页面
     */
    @RequiresPermissions(value={"project:projectAssess:add","project:projectAssess:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(ProjectAssessInfo projectAssessInfo, Model model) {
        Role loginUserRole = new Role();
                User user = UserUtils.getUser();
        if (null != user.getRoleList()){
            loginUserRole = user.getRoleList().get(0);

        }
        if (projectAssessInfo != null && StringUtils.isNotBlank(projectAssessInfo.getId())) {
            projectAssessInfo = projectAssessService.get(projectAssessInfo.getId());
            Office office = projectAssessService.getOfficeName(projectAssessInfo.getProjectId());
            projectAssessInfo.setCompanyName(office.getParent().getName());
            projectAssessInfo.setOfficeName(office.getTopCompany());
            projectAssessInfo.setOfficeId(office.getId());
        }else {
            projectAssessInfo.setCreateBy(UserUtils.getUser());
            projectAssessInfo.setCreateDate(new Date());
        }
        model.addAttribute("loginUserRole", loginUserRole);
        model.addAttribute("projectAssess", projectAssessInfo);
        return "modules/projectAssess/projectAssessForm";
    }

    /**
     * 项目评估详情查看
     * @param projectAssessInfo
     * @param model
     * @return
     */
    @RequiresPermissions(value={"project:projectAssess:view"})
    @RequestMapping(value = "view")
    public String view(ProjectAssessInfo projectAssessInfo, Model model) {
        if (projectAssessInfo!=null&&StringUtils.isNotBlank(projectAssessInfo.getId())) {
            projectAssessInfo = projectAssessService.queryProjectAssessDetail(projectAssessInfo);
        }
        model.addAttribute("projectAssess", projectAssessInfo);
        return "modules/projectAssess/projectAssessView";
    }

    /**
     * 项目评估申请
     * @param projectAssessInfo
     * @param model
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"project:projectAssess:add","project:projectAssess:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(ProjectAssessInfo projectAssessInfo, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, projectAssessInfo)){
            return form(projectAssessInfo, model);
        }
        projectAssessInfo.setStatus(ProjectStatusEnum.IN_APRL.getValue());
        String str = "";
        if(StringUtils.isNotBlank(projectAssessInfo.getId())){//编辑表单保存
            ProjectAssessInfo t = projectAssessService.get(projectAssessInfo.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(projectAssessInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            str = projectAssessService.saveProjectAssess(t);//保存
        }else{//新增表单保存
            str = projectAssessService.saveProjectAssess(projectAssessInfo);//保存
        }
        if (StringUtils.isNotBlank(str)){
            addMessage(redirectAttributes, "保存项目评估失败:"+str);
        }else {
            addMessage(redirectAttributes, "保存项评估成功");
        }
        return "redirect:"+ Global.getAdminPath()+"/project/projectAssess/?repage";
    }

    /**
     * 保存项目
     */
    @RequiresPermissions(value={"project:projectAssess:add","project:projectAssess:edit"},logical=Logical.OR)
    @RequestMapping(value = "tstore")
    public String tStore(ProjectAssessInfo projectAssessInfo, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, projectAssessInfo)){
            return form(projectAssessInfo, model);
        }
        try {
//            projectRecords.setProjectStatus(ProjectStatusEnum.TSTORE.getValue());
            if (!projectAssessInfo.getIsNewRecord()) {//编辑表单保存
                ProjectAssessInfo t = projectAssessService.get(projectAssessInfo.getId());//从数据库取出记录的值
                MyBeanUtils.copyBeanNotNull2Bean(projectAssessInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
                projectAssessService.saveProjectAssessTstore(t,ProjectStatusEnum.TSTORE);//保存
            } else {//新增表单保存
                projectAssessService.saveProjectAssessTstore(projectAssessInfo,ProjectStatusEnum.TSTORE);//保存
            }
            addMessage(redirectAttributes, "暂存项目成功");
        }catch (Exception e){
            logger.error("暂存项目异常：",e);
            addMessage(redirectAttributes, "暂存项目异常:"+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/project/projectAssess/?repage";
    }


    /**
     * 首页流程查看跳转方法
     * @param projectAssessInfo
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "getProcess")
    public String getProcess(ProjectAssessInfo projectAssessInfo, Model model,HttpServletRequest request){
        model.addAttribute("processInstanceId", projectAssessInfo.getProcessInstanceId());
        return "modules/projectAssess/projectAssessTask";
    }

    /**
     * 审核操作
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(ProjectAssessInfo projectAssessInfo, RedirectAttributes redirectAttributes) {
        if (null == projectAssessInfo.getAct()){
            projectAssessInfo.setAct(getByAct(projectAssessInfo.getProcessInstanceId()));
        }
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = projectAssessInfo.getAct().getTaskDefKey();
        List<User> users = null;
        if ("bzshb".equals(taskDefKey)){
            users = UserUtils.getByProssType(projectAssessInfo.getProcessInstanceId(),3);
            if (users==null )
                users = projectAssessService.getMasterUserList(projectAssessInfo.getProjectId());
                //users = UserUtils.getByRoleActivityEnname("master",2,UserUtils.getSelectOffice().getId(),"11",projectAssessInfo.getCreateBy());
        }else  if ("master".equals(taskDefKey)){
            users = UserUtils.getByRoleActivityEnname("cwzg",3,UserUtils.getSelectOffice().getId(),"11",projectAssessInfo.getCreateBy());
        }else  if ("cwzg".equals(taskDefKey)){
            users = UserUtils.getByRoleActivityEnname("fzjl",3,UserUtils.getSelectOffice().getId(),"11",projectAssessInfo.getCreateBy());
        }else  if ("fzjl".equals(taskDefKey)){
            users = UserUtils.getByRoleActivityEnname("zjl",3,UserUtils.getSelectOffice().getId(),"11",projectAssessInfo.getCreateBy());
        }else  if ("zjl".equals(taskDefKey)){
                users = UserUtils.getByRoleActivityEnname("zjl",3,UserUtils.getSelectOffice().getId(),"11",projectAssessInfo.getCreateBy());
        }else if ("modifyApply".equals(taskDefKey)){
            users = UserUtils.getByProssType(projectAssessInfo.getProcessInstanceId(),1);
        }
        //return "redirect:" + Global.getAdminPath() + "/project/projectAssess/?repage";
        String flag = projectAssessInfo.getAct().getFlag();
        if ("yes".equals(flag) && (users==null || users.size()==0)){
            addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
        }else {
            String str = projectAssessService.auditProjectAssess(projectAssessInfo,users);
            addMessage(redirectAttributes, str);
        }
        if (StringUtils.isNotBlank(projectAssessInfo.getHome()) && "home".equals(projectAssessInfo.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/project/projectAssess/?repage";
        }
    }

    /**
     * 审核撤回操作
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "revoke")
    public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        HashMap<String, String> requestMap = findRequestMap(request);
        String processInstanceId = requestMap.get("processInstanceId");
        String id = requestMap.get("id");
        try {
            ProjectAssessInfo projectAssessInfo = projectAssessService.get(id);
            if(5==projectAssessInfo.getStatus()){
                addMessage(redirectAttributes, "项目评审已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/project/projectAssess/?repage";
            }
            projectAssessService.cancelProcess(projectAssessInfo);
            addMessage(redirectAttributes, "撤回该项目评审成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该项目评审失败");
        }
        return "redirect:" + Global.getAdminPath() + "/project/projectAssess/?repage";
    }

    /**
     * 审核驳回修改方法
     */
    @RequiresPermissions(value={"project:projectAssess:edit"},logical=Logical.OR)
    @RequestMapping(value = "modify")
    public String modify(ProjectAssessInfo projectAssessInfo, Model model) {
        projectAssessInfo = projectAssessService.queryProjectAssess(projectAssessInfo);
        ProcessInstance processInstance = actTaskService.getProcIns(projectAssessInfo.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);
            projectAssessInfo.setAct(act);
        }

        model.addAttribute("projectAssess", projectAssessInfo);
        return "modules/projectAssess/projectAssessModifyApply";
    }

    /**
     * 删除项目
     */
    @RequiresPermissions("project:projectAssess:del")
    @RequestMapping(value = "delete")
    public String delete(ProjectAssessInfo projectAssessInfo, RedirectAttributes redirectAttributes) {
        int status = projectAssessInfo.getStatus();
        if(status==ProjectStatusEnum.TSTORE.getValue()||status==ProjectStatusEnum.REJECTED.getValue()||status==ProjectStatusEnum.RECALL.getValue()){
            projectAssessService.delete(projectAssessInfo);
            addMessage(redirectAttributes, "删除项目评估成功");
            return "redirect:"+Global.getAdminPath()+"/project/projectAssess/?repage";
        }else {
            addMessage(redirectAttributes, "删除项目评估失败，只有“暂存”、“驳回”、“撤回”状态的项目才能删除");
        }
        return "redirect:"+Global.getAdminPath()+"/project/projectAssess/?repage";
    }

    public Act getByAct(String processInstanceId){
        Act act = new Act();
        ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
        if (processInstance!=null) {
            List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
            if(taskList!=null && taskList.size()>1){
                for (Task taskInfok:taskList) {
                    if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
                        act.setTaskId(taskInfok.getId());
                        act.setTaskName(taskInfok.getName());
                        act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                        act.setProcDefId(taskInfok.getProcessDefinitionId());
                        act.setProcInsId(taskInfok.getProcessInstanceId());
                        act.setTask(taskInfok);
                    }
                }
            }else {
                Task task = actTaskService.getCurrentTaskInfo(processInstance);
                act.setTaskId(task.getId());
                act.setTaskName(task.getName());
                act.setTaskDefKey(task.getTaskDefinitionKey());
                act.setProcDefId(task.getProcessDefinitionId());
                act.setProcInsId(task.getProcessInstanceId());
                act.setTask(task);
            }
        }
        return  act;
    }
}
