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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActAuditService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.oa_evection.entity.oa_evection.OaEvection;
import com.jeeplus.modules.oa_evection.service.oa_evection.OaEvectionService;
import com.jeeplus.modules.sys.entity.Office;
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.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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

/**
 * 出差流程Controller
 * @author 杨帆
 * @version 2017-05-22
 */
@Controller
@RequestMapping(value = "${adminPath}/oa_evection/oaEvection")
public class OaEvectionController extends BaseController {

    @Autowired
    private OaEvectionService oaEvectionService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private OfficeService officeService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private ActAuditService actAuditService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ModelAttribute
    public OaEvection get(@RequestParam(required=false) String id){//,
//			@RequestParam(value="act.procInsId", required=false) String procInsId) {
        OaEvection oaEvection = null;
        if (StringUtils.isNotBlank(id)){
            oaEvection = oaEvectionService.get(id);
//		}else if (StringUtils.isNotBlank(procInsId)){
//			testAudit = testAuditService.getByProcInsId(procInsId);
        }
        if (oaEvection == null){
            oaEvection = new OaEvection();
        }
        return oaEvection;
    }


    @RequiresPermissions(value={"oa:evection:view","oa:evection:add","oa:evection:edit"},logical= Logical.OR)
    @RequestMapping(value = {"form"})
    public String form(OaEvection oaEvection, Model model) {
        String view = "oaEvectionForm";
        // 查看审批申请单
        if (StringUtils.isNotBlank(oaEvection.getId())){//.getAct().getProcInsId())){
            // 环节编号
            String taskDefKey = oaEvection.getAct().getTaskDefKey();
            if (taskDefKey!=null) {
                // 查看工单
                if (oaEvection.getAct().isFinishTask()) {
                    view = "oaEvectionView";
                }
                // 修改环节
                else if ("apply_end".equals(taskDefKey)) {
                    view = "oaEvectionAudit";
                }
                // 审核环节
                else if ("audit1".equals(taskDefKey)) {
                    if (StringUtils.isBlank(oaEvection.getAct().getStatus())){
                        model.addAttribute("disabled","true");
                    }else {
                        model.addAttribute("disabled","false");
                    }
                    view = "oaEvectionAudit";
                }
                //
                else if ("modifyApply".equals(taskDefKey)) {
                    view = "oaEvectionForm";
                }
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(oaEvection.getName())){
                if (oaEvection.getName().equals("view")){
                    model.addAttribute("disabled","true");
                    oaEvection.getAct().setProcInsId(oaEvection.getProcessInstanceId());
                    view = "oaEvectionAudit";
                }
            }
        }

        model.addAttribute("oaEvection", oaEvection);
        return "modules/oa_evection/"+view;
    }

    /**
     * 启动出差流程
     * @param oaEvection
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String save(OaEvection oaEvection, @RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files, RedirectAttributes redirectAttributes) throws Exception {
        if (StringUtils.isNotBlank(oaEvection.getId())) {
            OaEvection t = oaEvectionService.get(oaEvection.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(oaEvection, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            if (t.getStatus().equals("3") || t.getStatus().equals("4")){
                addMessage(redirectAttributes, "已结束流程不能修改！");
            }else {
                oaEvectionService.save(t);
            }
        } else {
            try{
                boolean b = oaEvectionService.saveEvection(oaEvection,this_upload_files);
                if (b) {
                    addMessage(redirectAttributes, "出差申请已经提交");
                } else {
                    addMessage(redirectAttributes, "系统内部错误！");
                }
            }catch(Exception e){
                logger.info("save e.getMessage()=" + e.getMessage());
                addMessage(redirectAttributes, "系统内部错误！");
            }
        }
        return "redirect:" + adminPath + "/oa_evection/oaEvection";
    }


    /**
     * 工单执行（完成任务）
     * @param oaEvection
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(OaEvection oaEvection,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
       /* if (StringUtils.isBlank(oaEvection.getAct().getComment())){
            addMessage(model, "请填写审核意见。");
            return form(oaEvection, model);
        }*/
        //oaEvectionService.auditSave(oaEvection);
        Act act = oaEvection.getAct();
        AjaxJson json = actAuditService.saveAudit(act, act.getProcInsId(), "evection", oaEvection.getAct().getComment(), oaEvection.getId(), "2");
        addMessage(redirectAttributes, json.getMsg());
        if (oaEvection!=null && StringUtils.isNotBlank(oaEvection.getHome()) && oaEvection.getHome().equals("home")){
            return "redirect:" + adminPath + "/home";
        }
        return "redirect:" + adminPath + "/oa_evection/oaEvection";
    }

    /**
     * 读取所有流程
     * @return
     */
    @RequiresPermissions("oa:evection:list")
    @RequestMapping(value = {"list", ""})
    public String list(OaEvection oaEvection, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        if (!user.isAdmin()){
            oaEvection.setCompanyId(user.getComId());
            if (!UserUtils.isManager()){
                oaEvection.setCreateBy(user);
            }
        }
        Page<OaEvection> page = oaEvectionService.find(new Page<OaEvection>(request, response), oaEvection);
        model.addAttribute("page", page);
        return "modules/oa_evection/oaEvectionList";
    }

    /**
     * 待办任务列表页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"oaEvectionTodoList"})
    public String oaEvectionTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
        act.setProcDefKey("evection");
        List<Act> list = actTaskService.todoList(act);
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<OaEvection> lists = new ArrayList<OaEvection>();
        for (Act a : list) {
            OaEvection oaEvection = oaEvectionService.getByProcessInstanceId(a.getProcInsId());
            if (oaEvection != null && oaEvection.getCompanyId().equals(companyId)) {
                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());
                    }
                }
                oaEvection.setAct(a);
                if (com.jeeplus.common.utils.StringUtils.isNotBlank(oaEvection.getId())){
                    oaEvection.setName(officeService.get(companyId).getName());
                }
                lists.add(oaEvection);
            }
        }
        model.addAttribute("list", lists);
        return "modules/oa_evection/oaEvectionTodoList";
    }

    /**
     * 已办任务
     * @param act
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"oaEvectionHistoricList"})
    public String oaEvectionHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
        act.setProcDefKey("evection");
        Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
        List<Act> list = page.getList();
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<OaEvection> lists = new ArrayList<OaEvection>();
        for (Act a : list) {
            OaEvection oaEvection = oaEvectionService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
            if (oaEvection != null && oaEvection.getCompanyId().equals(companyId)) {
                if (a.getVars().getMap().get("applyUserId")!=null){
                    a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                }
                oaEvection.setAct(a);
                if (com.jeeplus.common.utils.StringUtils.isNotBlank(oaEvection.getId())){
                    oaEvection.setName(officeService.get(companyId).getName());
                }
                lists.add(oaEvection);
            }
        }
        model.addAttribute("list", lists);

        return "modules/oa_evection/oaEvectionHistoricList";
    }

    /**
     * 审核信息
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "applyOnEvection")
    public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
        // 获取流程XML上的表单KEY
        String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
        //logger.info("------formKeys:"+formKeys);
        // 获取流程实例对象
        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);
    }

    /**
     * 出差申请撤销
     * @param
     * @return
     */
    @RequestMapping(value = "revoke")
    public String revoke(HttpServletRequest request, HttpServletResponse response) {

        HashMap<String, String> requestMap = findRequestMap(request);
        String processInstanceId = requestMap.get("processInstanceId");
        String id = requestMap.get("id");
        String deleteReason = requestMap.get("reason");

        AjaxJson j = new AjaxJson();
        try {
            OaEvection oaEvection = oaEvectionService.getById(id);
            oaEvection.setStatus("5");
            oaEvection.preUpdate();
            oaEvectionService.update(oaEvection);
            Map map = oaEvectionService.getEvectionById(id,"1");
            j.put("data",map);
            actTaskService.endProcessInstance(processInstanceId, deleteReason);
            j.setMsg("撤销申请成功");

            //撤销后，更改所有发送过的通知的阅读状态
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(oaEvection.getId());
            workProjectNotifyService.readByNotifyId(notify);
        }catch (Exception e){
            j.setErrorCode("101");
            logger.info(e.getMessage());
            j.setMsg("撤销申请失败");
            j.setSuccess(false);
        }
        return "redirect:" + adminPath + "/oa_evection/oaEvection";
    }
}