package com.jeeplus.modules.workgooutapply.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
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.ActTaskService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.sys.entity.MainDictDetail;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workgooutapply.entity.WorkGoOutInfo;
import com.jeeplus.modules.workgooutapply.service.WorkGoOutService;
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.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.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("${adminPath}/workgoout/workGoOut")
public class WorkGoOutController  extends BaseController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    WorkGoOutService workGoOutService ;

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

    /**
     * 外出申请列表页面
     * @param workGoOutInfo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("workgoout:workGoOut:list")
    @RequestMapping(value = {"list", ""})
    public String list(WorkGoOutInfo workGoOutInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WorkGoOutInfo> page = workGoOutService.findPage(new Page<WorkGoOutInfo>(request, response), workGoOutInfo);
        model.addAttribute("page", page);
        return "modules/workgoout/workGoOutList";
    }

    /**
     * 查看，增加，编辑外出申请表单页面
     * @param workGoOutInfo
     * @param model
     * @return
     */
    @RequiresPermissions(value={"workgoout:workGoOut:view"},logical= Logical.OR)
    @RequestMapping(value = "view")
    public String view(WorkGoOutInfo workGoOutInfo, Model model) {
        List<MainDictDetail> cardTypes = DictUtils.getMainDictList("card_type");
        for (MainDictDetail mainDictDetail: cardTypes) {
            if (mainDictDetail.getValue().equals(workGoOutInfo.getCar())) {
                workGoOutInfo.setCar(mainDictDetail.getLabel());
                break;
            }
        }
        model.addAttribute("workGoOut", workGoOutInfo);
        return "modules/workgoout/workGoOutView";
    }

    /**
     * 查看，增加，编辑项目盖章表单页面
     */
    @RequiresPermissions(value={"workgoout:workGoOut:view","workgoout:workGoOut:add","workgoout:workGoOut:edit"},logical=Logical.OR)
    @RequestMapping(value = "form")
    public String form(WorkGoOutInfo workGoOutInfo, Model model) {
        if(workGoOutInfo.getSubmitDate()==null){
            workGoOutInfo.setSubmitDate(new Date());
        }
        if(workGoOutInfo.getSubmiter()==null){
            workGoOutInfo.setSubmiter(UserUtils.getUser());
        }
        if(workGoOutInfo.getOffice()==null||StringUtils.isBlank(workGoOutInfo.getOffice().getId())){
            workGoOutInfo.setOffice(UserUtils.getSelectOffice());
        }
        String view = "workGoOutForm";
        String tabId = request.getParameter("tabId");
        model.addAttribute("workGoOut", workGoOutInfo);
        if("3".equals(tabId)){
            ProcessInstance processInstance = actTaskService.getProcIns(workGoOutInfo.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);
                workGoOutInfo.setAct(act);
                view = "workGoOutModifyApply";
            }
        }
        return "modules/workgoout/"+view;
    }

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

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

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkGoOutInfo workGoOutInfo, Model model,
                            RedirectAttributes redirectAttributes) {
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workGoOutInfo.getAct().getTaskDefKey();
        List<User> users = null;
        if ("bmzr".equals(taskDefKey)){
            users = UserUtils.getByProssType(workGoOutInfo.getProcessInstanceId(),2);
            if (users==null )
                users = UserUtils.getByRoleActivityEnname("fzjl",3,UserUtils.getSelectOffice().getId(),"11",workGoOutInfo.getCreateBy());
        }else  if ("fgld".equals(taskDefKey)){
            users = UserUtils.getByProssType(workGoOutInfo.getProcessInstanceId(),3);
            if (users==null )
                users = UserUtils.getByRoleActivityEnname("fzjl",3,UserUtils.getSelectOffice().getId(),"11",workGoOutInfo.getCreateBy());
        }else if ("modifyApply".equals(taskDefKey)){
            users = UserUtils.getByProssType(workGoOutInfo.getProcessInstanceId(),1);
        }
        String flag = workGoOutInfo.getAct().getFlag();
        if ("yes".equals(flag) && (users==null || users.size()==0)){
            addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
        }else {
            String str = workGoOutService.goOutProjectSave(workGoOutInfo,users);
            addMessage(redirectAttributes, str);
        }
        if (StringUtils.isNotBlank(workGoOutInfo.getHome()) && "home".equals(workGoOutInfo.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/workgoout/workGoOut/?repage";
        }
    }

    /**
     * 审核
     * @param act
     * @param workGoOutInfo
     * @param model
     * @return
     */
    @RequestMapping(value = "audit")
    public String workContractInfoAudit(Act act, WorkGoOutInfo workGoOutInfo, Model model) {

        if (act.getProcInsId() != null) {
            if (actTaskService.getProcIns(act.getProcInsId()) != null) {
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            } else {
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
            workGoOutInfo.setAct(act);
            model.addAttribute("processInstanceId", workGoOutInfo.getProcessInstanceId());
        }
        model.addAttribute("workGoOut", workGoOutInfo);
        return "modules/workgoout/workGoOutAudit";
    }

    /**
     * 流程展示请求
     * @param workGoOutInfo
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "getProcess")
    public String getProcess(WorkGoOutInfo workGoOutInfo, Model model, HttpServletRequest request){
        model.addAttribute("processInstanceId", workGoOutInfo.getProcessInstanceId());
        return "modules/workgoout/workGoOutTask";
    }


    /**
     * 撤回请求
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions(value={"workgoout:workGoOut:edit"},logical=Logical.OR)
    @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 {
            WorkGoOutInfo workGoOutInfo = workGoOutService.get(id);
            if(5==workGoOutInfo.getState()){
                addMessage(redirectAttributes, "外出申请已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/workgoout/workGoOut/?repage";
            }
            workGoOutService.cancelProcess(workGoOutInfo);
            addMessage(redirectAttributes, "撤回该外出求情审批成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该外出请求审批失败");
        }
        return "redirect:" + Global.getAdminPath() + "/workgoout/workGoOut/?repage";
    }

    /**
     * 删除项目盖章
     */
    @RequiresPermissions("workgoout:workGoOut:del")
    @RequestMapping(value = "delete")
    public String delete(WorkGoOutInfo workGoOutInfo, RedirectAttributes redirectAttributes) {
        if(5==workGoOutInfo.getState()|| 2==workGoOutInfo.getState()){
            if(5==workGoOutInfo.getState()){
                addMessage(redirectAttributes, "项目外出申请已审批通过，无法删除");
                return "redirect:"+Global.getAdminPath()+"/workgoout/workGoOut/?repage";
            }else{
                addMessage(redirectAttributes, "项目外出申请正在审核中，无法删除");
                return "redirect:"+Global.getAdminPath()+"/workgoout/workGoOut/?repage";
            }
        }
        workGoOutService.delete(workGoOutInfo);
        addMessage(redirectAttributes, "删除项目外出申请成功");
        return "redirect:"+Global.getAdminPath()+"/workgoout/workGoOut/?repage";
    }

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

    /**
     * 导入Excel数据

     */
    @RequiresPermissions("workgoout:workGoOut: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<WorkGoOutInfo> list = ei.getDataList(WorkGoOutInfo.class);
            for (WorkGoOutInfo workGoOut : list){
                try{
                    workGoOutService.save(workGoOut);
                    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()+"/workgoout/workGoOut/?repage";
    }

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