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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeeplus.modules.sys.entity.Menu;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;

/**
 * 流程表Controller
 * @author yangfan
 * @version 2018-01-17
 */
@Controller
@RequestMapping(value = "${adminPath}/workactivitymenu/workActivityMenu")
public class WorkActivityMenuController extends BaseController {

	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public WorkActivityMenu get(@RequestParam(required=false) String id) {
		WorkActivityMenu entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workActivityMenuService.get(id);
		}
		if (entity == null){
			entity = new WorkActivityMenu();
		}
		return entity;
	}
	
	/**
	 * 流程表列表页面
	 */
	@RequiresPermissions("workactivitymenu:workActivityMenu:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkActivityMenu workActivityMenu, HttpServletRequest request, HttpServletResponse response, Model model) {
		Office company = UserUtils.getSelectCompany();
		List<Office> offices = new ArrayList<>();
		List<Office> officeList = officeService.findByType(company);
		offices.addAll(officeList);
		model.addAttribute("list", offices);
		return "modules/workactivitymenu/officeList";
	}

	/**
	 * 流程表列表页面
	 */
	@RequestMapping(value = "workActivityMenuList")
	public String workActivityMenuList(WorkActivityMenu workActivityMenu, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("officeId", workActivityMenu.getOfficeId());
		if (StringUtils.isNotBlank(workActivityMenu.getOfficeId()) && !workActivityMenu.getOfficeId().equals("001")){
			Office office = officeService.get(workActivityMenu.getOfficeId());
			if (office.getType().equals("2")){
				workActivityMenu.setOfficeId(office.getId());
			}else if(office.getType().equals("3")){
				workActivityMenu.setOfficeId("");
				workActivityMenu.setBranchCompanyId(office.getId());
			}else {
				workActivityMenu.setOfficeId("");
				workActivityMenu.setCompanyId(office.getId());
			}
		}else {
			workActivityMenu.setOfficeId("");
			if(!UserUtils.getUser().isAdmin()){
				workActivityMenu.setCompanyId(UserUtils.getSelectCompany().getId());
			}
		}
		logger.info(workActivityMenu.getOfficeId()+"");
		List<WorkActivityMenu> list = workActivityMenuService.findList(workActivityMenu);
		model.addAttribute("list", list);
		return "modules/workactivitymenu/workActivityMenuList";
	}

	/**
	 * 查看，增加，编辑流程表表单页面
	 */
	@RequiresPermissions(value={"workactivitymenu:workActivityMenu:view","workactivitymenu:workActivityMenu:add","workactivitymenu:workActivityMenu:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkActivityMenu workActivityMenu, Model model, RedirectAttributes redirectAttributes) {
		getSort(workActivityMenu);
		if (StringUtils.isNotBlank(workActivityMenu.getOfficeId()) && !"0".equals(workActivityMenu.getOfficeId())){
			if (StringUtils.isNotBlank(workActivityMenu.getOfficeId()) && !workActivityMenu.getOfficeId().equals("001")){
				Office office = officeService.get(workActivityMenu.getOfficeId());
				workActivityMenu.setOfficeName(office.getName());
			}
		}
		if (StringUtils.isNotBlank(workActivityMenu.getView()) && workActivityMenu.getView().equals("copy")){
			return "modules/workactivitymenu/workActivityMenuCopy";
		}
		if (UserUtils.getUser().isAdmin()){
			model.addAttribute("allRoles", systemService.findAllRoleByCompany());
		}else {
			String companyId = UserUtils.getSelectCompany().getId();
			Role roles = new Role();
			roles.setCompany(new Office(companyId));
			List<Role> roleList = UserUtils.getRoleListByCompany(roles);
			model.addAttribute("allRoles", roleList);
		}
		model.addAttribute("workActivityMenu", workActivityMenu);
		model.addAttribute("companyid", UserUtils.getSelectCompany().getId());
		if (StringUtils.isNotBlank(workActivityMenu.getView()) && workActivityMenu.getView().equals("view")){
			return "modules/workactivitymenu/workActivityMenuView";
		}
		return "modules/workactivitymenu/workActivityMenuForm";
	}

	/**
	 * 保存流程表
	 */
	@RequiresPermissions(value={"workactivitymenu:workActivityMenu:add","workactivitymenu:workActivityMenu:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkActivityMenu workActivityMenu, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workActivityMenu)){
			return form(workActivityMenu, model,redirectAttributes);
		}
		getSort(workActivityMenu);
		if(!workActivityMenu.getIsNewRecord()){//编辑表单保存
			WorkActivityMenu t = workActivityMenuService.get(workActivityMenu.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workActivityMenu, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workActivityMenuService.save(t);//保存
		}else{//新增表单保存
			Office office = officeService.get(workActivityMenu.getOfficeId());
			String[] parentIds = office.getParentIds().split(",");
			String parent = "";
			String officeIds = "";
			for (String parentId:parentIds){
				if (!parentId.equals("0")) {
					Office o = officeService.get(parentId);
					if (o.getType().equals("3")) {
						parent += o.getId() + ",";
					}else if(o.getType().equals("1")){
						officeIds += o.getId() + ",";
					}
				}
			}
			if (office.getType().equals("1")){
				officeIds+= office.getId() + ",";
			}
			if (StringUtils.isNotBlank(parent)){
				parent = parent.substring(0,parent.length()-1);
			}
			if (StringUtils.isNotBlank(officeIds)){
				officeIds = officeIds.substring(0,officeIds.length()-1);
			}
			workActivityMenu.setBranchCompanyId(parent);
			workActivityMenu.setCompanyId(officeIds);
			workActivityMenuService.save(workActivityMenu);//保存
		}
		addMessage(redirectAttributes, "保存流程表成功");
		return "redirect:"+Global.getAdminPath()+"/workactivitymenu/workActivityMenu/workActivityMenuList?repage";
	}

	public WorkActivityMenu getSort(WorkActivityMenu workActivityMenu){
		if (workActivityMenu.getParent()!=null && StringUtils.isNotBlank(workActivityMenu.getParent().getId()) && workActivityMenu.getSort()==30){
			workActivityMenu.setParent(workActivityMenuService.get(workActivityMenu.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(workActivityMenu.getId())){
				WorkActivityMenu workActivityMenuChild = new WorkActivityMenu();
				workActivityMenuChild.setParent(new WorkActivityMenu(workActivityMenu.getParent().getId()));
				workActivityMenuChild.setOfficeId(workActivityMenu.getOfficeId());
				List<WorkActivityMenu> list = workActivityMenuService.findByList(workActivityMenu);
				if (list.size() > 0){
					workActivityMenu.setSort(list.get(list.size()-1).getSort());
					if (workActivityMenu.getSort() != null){
						workActivityMenu.setSort(workActivityMenu.getSort() + 1);
					}
				}
			}
		}
		return workActivityMenu;
	}

	/**
	 * 保存流程表
	 */
	@RequestMapping(value = "copy")
	public String copy(@RequestParam(value="id", required=false) String id, @RequestParam(value="officeId", required=false) String officeId,Model model, RedirectAttributes redirectAttributes) throws Exception{
		logger.info(officeId+","+id);
		WorkActivityMenu workActivityMenu = workActivityMenuService.get(id);
		Office office = new Office(officeId);
		WorkActivityMenu oldMenu = workActivityMenuService.findByParentAndOffice(workActivityMenu.getParentId(),office);
		if (oldMenu!=null && oldMenu.getOfficeId()!=null && oldMenu.getOfficeId().equals(officeId)){
			workActivityMenu.setId(oldMenu.getId());
		}else {
			workActivityMenu.setId("");
			workActivityMenu.setSort(30);
		}
		workActivityMenu.setOfficeId(officeId);
		getSort(workActivityMenu);
		workActivityMenuService.save(workActivityMenu);
		addMessage(redirectAttributes, "同步流程数据成功");
		return "redirect:"+Global.getAdminPath()+"/workactivitymenu/workActivityMenu/workActivityMenuList?repage";
	}

	/**
	 * 删除流程表
	 */
	@RequiresPermissions("workactivitymenu:workActivityMenu:del")
	@RequestMapping(value = "delete")
	public String delete(WorkActivityMenu workActivityMenu, RedirectAttributes redirectAttributes) {
		workActivityMenuService.delete(workActivityMenu);
		addMessage(redirectAttributes, "删除流程表成功");
		return "redirect:"+Global.getAdminPath()+"/workactivitymenu/workActivityMenu/workActivityMenuList?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId,HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		WorkActivityMenu workActivityMenu = new WorkActivityMenu();
		workActivityMenu.setOfficeId("0");
		List<WorkActivityMenu> list = workActivityMenuService.findTreeData(workActivityMenu);
		for (int i=0; i<list.size(); i++){
			WorkActivityMenu e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				if (e.getParentIds() != null && "0,".equals(e.getParentIds())){
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
	
}