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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
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.workpettycash.entity.WorkPettyCash;
import com.jeeplus.modules.workpettycash.service.WorkPettyCashService;
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.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 javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 备用金申请Controller
 *
 * @author fgy
 * @version 2018-01-15
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workpettycash/workPettyCash")
public class WorkPettyCashController extends BaseController {

    @Autowired
    private WorkPettyCashService workPettyCashService;
    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private ActTaskService actTaskService;

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

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

    /**
     * 备用金申请列表页面
     */
    @RequiresPermissions("workpettycash:workPettyCash:list")
    @RequestMapping(value = {"list", ""})
    public String list(WorkPettyCash workPettyCash, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        if (!user.isAdmin()) {
            workPettyCash.setCompanyId(user.getComId());
            if (!UserUtils.isManager()) {
                workPettyCash.setCreateBy(user);//创建人
                //workPettyCash.setOfficeId(UserUtils.getSelectOffice().getId());
            }
        }

        Page<WorkPettyCash> page = workPettyCashService.findPage(new Page<WorkPettyCash>(request, response), workPettyCash);
        model.addAttribute("page", page);
        return "modules/workpettycash/workPettyCashList";
    }

    /**
     * 查看，增加，编辑备用金申请表单页面
     */
    @RequiresPermissions(value = {"workpettycash:workPettyCash:view", "workpettycash:workPettyCash:add", "workpettycash:workPettyCash:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(WorkPettyCash workPettyCash, Model model) {
        String view = "workPettyCashForm";
        // 查看审批申请单
        if (org.apache.commons.lang3.StringUtils.isNotBlank(workPettyCash.getId())) {//.getAct().getProcInsId())){
            // 环节编号
            String taskDefKey = workPettyCash.getAct().getTaskDefKey();
            if (taskDefKey != null) {
                // 查看工单
                if (workPettyCash.getAct().isFinishTask()) {
                    view = "workPettyCashView";
                }
                // 修改环节
                else if ("apply_end".equals(taskDefKey)) {
                    view = "workPettyCashAudit";
                }
                // 审核环节
                else if ("audit1".equals(taskDefKey)) {
                    if (org.apache.commons.lang3.StringUtils.isBlank(workPettyCash.getAct().getStatus())) {
                        model.addAttribute("disabled", "true");
                    } else {
                        model.addAttribute("disabled", "false");
                    }
                    view = "workPettyCashAudit";
                }
                //
                else if ("modifyApply".equals(taskDefKey)) {
                    view = "workPettyCashForm";
                }
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(workPettyCash.getName())) {
                if (workPettyCash.getName().equals("view")) {
                    model.addAttribute("disabled", "true");
                    workPettyCash.getAct().setProcInsId(workPettyCash.getProcessInstanceId());
                    view = "workPettyCashAudit";
                }
            }
        }
        model.addAttribute("workPettyCash", workPettyCash);
        return "modules/workpettycash/" + view;
    }

    /**
     * 保存备用金申请
     */
    @RequiresPermissions(value = {"workpettycash:workPettyCash:add", "workpettycash:workPettyCash:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(WorkPettyCash workPettyCash, Model model, RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, workPettyCash)) {
            return form(workPettyCash, model);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(workPettyCash.getId())) {
            WorkPettyCash t = workPettyCashService.get(workPettyCash.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(workPettyCash, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            if (t.getStatus().equals("3") || t.getStatus().equals("4")) {
                addMessage(redirectAttributes, "已结束流程不能修改！");
            } else {
                workPettyCashService.save(t);
            }
        } else {
            try {
                Map<String, Boolean> resultMap = workPettyCashService.saveWorkPettyCash(workPettyCash);
                boolean flag = resultMap.get("flag");
                if (!flag) {
                    addMessage(redirectAttributes, "不能选择自己为审批人!");
                } else {
                    boolean b = resultMap.get("b");
                    if (b) {
                        addMessage(redirectAttributes, "备用金申请已经提交");
                    } else {
                        addMessage(redirectAttributes, "系统内部错误！");
                    }
                }
            } catch (Exception e) {
                logger.info("save e.getMessage()=" + e.getMessage());
                addMessage(redirectAttributes, "系统内部错误！");
            }
        }
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }

    /**
     * 删除备用金申请
     */
    @RequiresPermissions("workpettycash:workPettyCash:del")
    @RequestMapping(value = "delete")
    public String delete(WorkPettyCash workPettyCash, RedirectAttributes redirectAttributes) {
        workPettyCashService.delete(workPettyCash);
        addMessage(redirectAttributes, "删除备用金申请成功");
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }

    /**
     * 批量删除备用金申请
     */
    @RequiresPermissions("workpettycash:workPettyCash:del")
    @RequestMapping(value = "deleteAll")
    public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            workPettyCashService.delete(workPettyCashService.get(id));
        }
        addMessage(redirectAttributes, "删除备用金申请成功");
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }

    /**
     * 执行审批任务
     *
     * @param
     * @param vars
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkPettyCash workPettyCash, Map<String, Object> vars, Model model) {
        //workPettyCashService.auditSave(workPettyCash);
        Act act = workPettyCash.getAct();
        actAuditService.saveAudit(act, act.getProcInsId(), "pettyCash", workPettyCash.getAct().getComment(), workPettyCash.getId(), "2");
        if (workPettyCash!=null && org.apache.commons.lang3.StringUtils.isNotBlank(workPettyCash.getHome()) && workPettyCash.getHome().equals("home")){
            return "redirect:" + adminPath + "/home";
        }
        return "redirect:" + adminPath + "/workpettycash/workPettyCash";
    }

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

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

        return "modules/workpettycash/workPettyCashHistoricList";
    }

    /**
     * 审核备用金申请
     *
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "applyOnWorkpettycash")
    public String applyOnWorkpettycash(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 {
            WorkPettyCash workPettyCash = workPettyCashService.getById(id);
            workPettyCash.setStatus("5");
            workPettyCash.preUpdate();
            workPettyCashService.update(workPettyCash);
            Map map = workPettyCashService.getPettyCashById(id, "1");
            j.put("data", map);
            actTaskService.endProcessInstance(processInstanceId, deleteReason);
            j.setMsg("撤销申请成功");

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


    /**
     * 导出excel文件
     */
    @RequiresPermissions("workpettycash:workPettyCash:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(WorkPettyCash workPettyCash, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "备用金申请" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<WorkPettyCash> page = workPettyCashService.findPage(new Page<WorkPettyCash>(request, response, -1), workPettyCash);
            new ExportExcel("备用金申请", WorkPettyCash.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出备用金申请记录失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("workpettycash:workPettyCash:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<WorkPettyCash> list = ei.getDataList(WorkPettyCash.class);
            for (WorkPettyCash workPettyCash : list) {
                try {
                    workPettyCashService.save(workPettyCash);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条备用金申请记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条备用金申请记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入备用金申请失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }

    /**
     * 下载导入备用金申请数据模板
     */
    @RequiresPermissions("workpettycash:workPettyCash:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "备用金申请数据导入模板.xlsx";
            List<WorkPettyCash> list = Lists.newArrayList();
            new ExportExcel("备用金申请数据", WorkPettyCash.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workpettycash/workPettyCash/?repage";
    }


}