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

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.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.workovertimeform.entity.WorkOvertimeForm;
import com.jeeplus.modules.workovertimeform.service.WorkOvertimeFormService;
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.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-04-26
 */
@Controller
@RequestMapping(value = "${adminPath}/workovertimeform/workOvertimeForm")
public class WorkOvertimeFormController extends BaseController {

	@Autowired
	private WorkOvertimeFormService workOvertimeFormService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private ActTaskService actTaskService;

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

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

    @ModelAttribute
    public WorkOvertimeForm get(@RequestParam(required=false) String id){//,
//			@RequestParam(value="act.procInsId", required=false) String procInsId) {
        WorkOvertimeForm workOvertimeForm = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(id)){
            workOvertimeForm = workOvertimeFormService.get(id);
//		}else if (StringUtils.isNotBlank(procInsId)){
//			testAudit = testAuditService.getByProcInsId(procInsId);
        }
        if (workOvertimeForm == null){
            workOvertimeForm = new WorkOvertimeForm();
        }
        return workOvertimeForm;
    }

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

        model.addAttribute("workOvertimeForm", workOvertimeForm);
        return "modules/workovertimeform/"+view;
    }

    /**
     * 启动加班流程
     * @param workOvertimeForm
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String save(WorkOvertimeForm workOvertimeForm, @RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files, RedirectAttributes redirectAttributes) throws Exception{
        if (org.apache.commons.lang3.StringUtils.isNotBlank(workOvertimeForm.getId())) {
            WorkOvertimeForm t = workOvertimeFormService.get(workOvertimeForm.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(workOvertimeForm, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            if (t.getStatus().equals("3") || t.getStatus().equals("4")){
                addMessage(redirectAttributes, "已结束流程不能修改！");
            }else {
                workOvertimeFormService.save(t);
            }
        } else {
            try {
                boolean b = workOvertimeFormService.saveWorkovertimeform(workOvertimeForm,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 + "/workovertimeform/workOvertimeForm";
    }


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

    /**
     * 读取所有流程
     * @return
     */
    @RequiresPermissions("workovertimeform:workovertimeForm:list")
    @RequestMapping(value = {"list", ""})
    public String list(WorkOvertimeForm workOvertimeForm, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        if (!user.isAdmin()){
            workOvertimeForm.setCompanyId(user.getComId());
            if (!UserUtils.isManager()){
                workOvertimeForm.setCreateBy(user);
            }
        }
        Page<WorkOvertimeForm> page = workOvertimeFormService.find(new Page<WorkOvertimeForm>(request, response), workOvertimeForm);
        model.addAttribute("page", page);
        return "modules/workovertimeform/workOvertimeFormList";
    }

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

    /**
     * 已办任务
     * @param act
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"workOvertimeHistoricList"})
    public String oaEvectionHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
        act.setProcDefKey("overtimeform");
        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<WorkOvertimeForm> lists = new ArrayList<WorkOvertimeForm>();
        for (Act a : list) {
            WorkOvertimeForm workOvertimeForm = workOvertimeFormService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
            if (workOvertimeForm != null && workOvertimeForm.getCompanyId().equals(companyId)) {
                if (a.getVars().getMap().get("applyUserId")!=null){
                    a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                }
                workOvertimeForm.setAct(a);
                if (com.jeeplus.common.utils.StringUtils.isNotBlank(workOvertimeForm.getId())){
                    workOvertimeForm.setName(officeService.get(companyId).getName());
                }
                lists.add(workOvertimeForm);
            }
        }
        model.addAttribute("list", lists);

        return "modules/workovertimeform/workOvertimeHistoricList";
    }

    /**
     * 审核企业信息
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "applyOnOvertime")
    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 {
            WorkOvertimeForm workOvertimeForm = workOvertimeFormService.getById(id);
            workOvertimeForm.setStatus("5");
            workOvertimeForm.preUpdate();
            workOvertimeFormService.update(workOvertimeForm);
            Map map = workOvertimeFormService.getOverTimeById(id,"1");
            j.put("data",map);
            actTaskService.endProcessInstance(processInstanceId, deleteReason);
            j.setMsg("撤销申请成功");

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


}