/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.modules.sys.dao.CompanyDao;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.service.CompanyService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.wexinpackage.access.entity.WxDepartment;
import com.jeeplus.modules.wexinpackage.access.util.access.AccessTokenUtil;
import com.jeeplus.modules.wexinpackage.access.util.access.AddressDepartment;
import com.jeeplus.modules.wexinpackage.access.util.access.WeChatParamsUtil;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
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.config.Global;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 机构Controller
 *
 * @author jeeplus
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

    @Autowired
    private OfficeService officeService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;
    @Autowired
    private OfficeDao officeDao;

    @ModelAttribute("office")
    public Office get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return officeService.get(id);
        } else {
            return new Office();
        }
    }

    @RequiresPermissions("sys:office:index")
    @RequestMapping(value = {"list",""})
    public String index(Office office, Model model) {
        User user=UserUtils.get(UserUtils.getUser().getId());

        List<Office> offices = new ArrayList<>();
        if (office == null || office.getParentIds() == null || office.getParentIds().equals("")) {
            offices =  officeService.findListIndex(office);
            if (offices!=null && offices.size()!=0){
                boolean b = true;
                for (Office office1:offices){
                    if (office1.getType().equals("1")){
                        office1.setParent(new Office("0"));
                        b = false;
                        break;
                    }
                }
                List<Role> roleList =  roleDao.getManagerRoleList(UserUtils.getUser().getId(),UserUtils.getSelectCompany().getId());
                if(roleList!=null&&roleList.size()>0){
                    for (Office office1:offices){
                        if (office1.getType().equals("3") && b){
                            for(Role role:roleList){
                                if(office1.getId().equals(role.getOffice().getId())){
                                    office1.setParent(new Office("0"));
                                }
                            }
                        }
                    }
                }else{
                    for (Office office1:offices){
                        if (office1.getType().equals("3") && b){
                            office1.setParent(new Office("0"));
                        }
                    }
                }
            }
        } else {
            offices = officeService.findListt(office);
        }
        model.addAttribute("list", offices);
        return "modules/sys/officeList";
    }

   /* @RequiresPermissions("sys:office:index")
    @RequestMapping(value = {"list"})
    public String list(Office office, Model model) {
        if (office == null || office.getParentIds() == null || office.getParentIds().equals("")) {
            model.addAttribute("list", officeService.findList(false));
        } else {
            model.addAttribute("list", officeService.findListt(office));
        }
        return "modules/sys/officeList";
    }*/

    @RequiresPermissions(value = {"sys:office:view", "sys:office:add", "sys:office:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(Office office, Model model, HttpSession session, HttpServletRequest request) {
        String view = request.getParameter("view");
        if (!StringUtils.isBlank(view)) {
            if (view.equals("view")) {
                if (StringUtils.isNotBlank(office.getMaster())) {
                    office.setMasterName(UserUtils.get(office.getMaster()).getName());
                }
                return "modules/sys/officeView";
            }
        }
        User user = UserUtils.getUser();
        if (office.getParent() == null || office.getParent().getId() == null) {
            office.setParent(user.getOffice());
        }
        office.setParent(officeService.get(office.getParent().getId()));
        if (office.getArea() == null) {
            office.setArea(user.getOffice().getArea());
        }
        if (!UserUtils.getSelectRole().get(0).getId().equals("1") && !user.getId().equals("1")) {
            Office selectCompany = UserUtils.getSelectCompany();
            if(!isSelectComp(selectCompany,office)){
                office.setParent(selectCompany);//非admin 只能创建部门 以及 当前公司的分公司
            }
        }
        if (StringUtils.isNotBlank(office.getMaster())) {
            office.setMasterName(UserUtils.get(office.getMaster()).getName());
        }
        // 自动获取排序号
        if (StringUtils.isBlank(office.getId()) && office.getParent() != null) {
            int size = 0;
            List<Office> list = officeService.findAll();
            for (int i = 0; i < list.size(); i++) {
                Office e = list.get(i);
                if (e.getParent() != null && e.getParent().getId() != null
                        && e.getParent().getId().equals(office.getParent().getId())) {
                    size++;
                }
            }
            office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
        }
        if (StringUtils.isBlank(office.getId())) {
            office.setType(null);
        } else if (StringUtils.isNotBlank(office.getId())) {
            session.setAttribute("state", "disabled");//禁止修改类型级别
            /*if(office.getParentIds().equals("0")||office.getCode().equals("100000")||office.getParentIds().equals("0,")){
				session.setAttribute("cname","no");//禁止修改公司名称
			}*/
        }

        model.addAttribute("office", office);
        return "modules/sys/officeForm";
    }

    private boolean isSelectComp(Office selectCompany, Office office) {
        if (office.getParent()==null||StringUtils.isBlank(office.getParent().getId())) {
            return false;
        }
        if (office.getParent().getId()==selectCompany.getId())return true;
        if(StringUtils.isNotBlank(office.getParent().getParentIds())){
            String[] split = office.getParent().getParentIds().split(",");
            for (String s : split) {
                if (s.equals(selectCompany.getId()))return true;
            }
        }
        return false;
    }

    @RequiresPermissions(value = {"sys:office:add", "sys:office:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(Office office, Model model, RedirectAttributes redirectAttributes, HttpSession session, HttpServletRequest request) throws Exception {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/office/";
        }
        Office office1 = office.getParent();
        if(office1 != null && office1.getName() != null) {
            Office o = officeService.get(office.getParent().getId());
            if (o.getType().equals("2")) {
                if (!"2".equals(office.getType())) {
                    addMessage(redirectAttributes, "部门下不能添加分公司！");
                    return "redirect:" + adminPath + "/sys/office/";
                }
            }
        }
        if (!beanValidator(model, office)) {
            return form(office, model, session, request);
        }
        Office c = UserUtils.getSelectCompany();
        if (office.getType().equals("1")) {
            if (office.getParent() == null || office.getParent().getId() == null) {
                office.setGrade("1");
            } else {
                office.setGrade("2");//分公司等级
            }
        } else if (office.getType().equals("2")) {
            office.setGrade("2");
        } else if (office.getType().equals("3")) {
            office.setGrade("2");
        } else {
            office.setGrade("3");
        }
        if (!office.getIsNewRecord()) {//编辑表单保存
            Office t = officeService.get(office.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(office, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            t.setIsSon(c.getIsSon());
            officeService.save(t);
            //微信端
            Integer wxOfficeIdByParentIdService = officeService.findWxOfficeIdByParentIdService(office.getId());
            String accessToken = AccessTokenUtil.getAccessToken(WeChatParamsUtil.corpId, WeChatParamsUtil.contactsSecret);
            Integer wxOfficeIdByIdSerice= officeService.findWxOfficeIdByIdSerice(office.getId());
            WxDepartment wxDepartment = new WxDepartment(wxOfficeIdByIdSerice,office.getName(),wxOfficeIdByParentIdService);
            AddressDepartment.updateDepartment(accessToken,wxDepartment);
            addMessage(redirectAttributes, "修改成功");
            String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
            return "redirect:" + adminPath + "/sys/office/list";
        } else {//新增表单保存
            String wxOfficeIdService = officeService.findWxOfficeIdService();
            office.setIsSon(c.getIsSon());
            office.setWxOfficeId(wxOfficeIdService);
            officeService.save(office);//保存
            Integer wxOfficeIdByParentIdService = officeService.findWxOfficeIdByParentIdService(office.getId());
            String accessToken = AccessTokenUtil.getAccessToken(WeChatParamsUtil.corpId, WeChatParamsUtil.contactsSecret);
            WxDepartment wxDepartment = new WxDepartment(new Integer(wxOfficeIdService),office.getName(),wxOfficeIdByParentIdService);
            AddressDepartment.createDepartment(accessToken,wxDepartment);
        }
        String str = "0";
        //如果是添加分公司，则分配相应部门和岗位
        try {
            Company company = new Company();
            company.setName(office.getTopCompany());
            company.setEmail(office.getEmail());
            company.setPhone(office.getPhone());
            company.setTuser(new User(office.getMaster()));
            company.setUSEABLE("1");
            String logo = "";
            if (office.getLogo() != null) {
                logo = office.getLogo();
            }
            company.setLogo(logo);
            if (office.getType().equals("1")) {
                str = companyService.applyCompanyOR(office, company, request);
            } else if (office.getType().equals("2")){
                Boolean b = companyService.applyOffice(office);
            } else if (office.getType().equals("3")) {
                Office com = new Office();
                if (!UserUtils.getUser().isAdmin()) {
                    com = UserUtils.getSelectCompany();
                } else {
                    com = office.getParent();
                }

                str = companyService.applyCompanyAnd(com, office, company, request);
            }
            if (office.getChildDeptList() != null) {

                Office childOffice = null;
                for (String id : office.getChildDeptList()) {
                    childOffice = new Office();
                    childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知"));
                    childOffice.setParent(office);
                    childOffice.setArea(office.getArea());
                    childOffice.setType("2");
                    childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade()) + 1));
                    childOffice.setUseable(Global.YES);
                    officeService.save(childOffice);
                }
            }
            if (str != null && "1".equals(str)) {
                addMessage(redirectAttributes, "保存机构'" + office.getTopCompany() + "'成功");
                logger.info("添加成功");
            } else if ("2".equals(str)) {
                addMessage(redirectAttributes, "创建公司管理员岗位失败");
                logger.info("创建公司管理员岗位失败");
            } else if ("3".equals(str)) {
                addMessage(redirectAttributes, "所选负责人数据异常");
            } else if ("0".equals(str)) {
                addMessage(redirectAttributes, "保存机构'" + office.getTopCompany() + "'成功");
            } else {
                logger.info("添加失败");
            }
        } catch (Exception e) {
            logger.info("Exception e:"+e);
            officeService.delete(office);
            addMessage(redirectAttributes, "创建公司管理员岗位失败");
        }
        String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
		/*if(UserUtils.getUser().getId().equals(office.getMaster())&&office.getType().equals("1")){
			request.getSession().invalidate();
		}*/
        return "redirect:" + adminPath + "/sys/office/?repage";
    }

    @RequiresPermissions("sys:office:del")
    @RequestMapping(value = "delete")
    public String delete(Office office, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/office/list";
        }
        if ("1".equals(office.getId())||"1".equals(office.getParentId())) {
            addMessage(redirectAttributes, "删除机构失败,不能删除当前机构！");
            //return "redirect:" + adminPath + "/sys/office/list?id=" + office.getParentId() + "&parentIds=" + office.getParentIds();
            return "redirect:" + Global.getAdminPath() + "/sys/office/?repage";
        }

        int cou = systemService.countByOffice(office);
        if (cou > 0) {
            addMessage(redirectAttributes, "删除机构失败,当前机构下存在用户！");
            return "redirect:" + Global.getAdminPath() + "/sys/office/?repage";
        }
        officeService.logicDelete(office);
        String accessToken = AccessTokenUtil.getAccessToken(WeChatParamsUtil.corpId, WeChatParamsUtil.contactsSecret);
        Integer wxOfficeIdByIdSerice= officeService.findWxOfficeIdByIdSerice(office.getId());
        AddressDepartment.deleteDepartment(accessToken,String.valueOf(wxOfficeIdByIdSerice));
        if(UserUtils.getSelectCompany().getId().equals(office.getId())){
            systemService.removeSession(UserUtils.getUser());
            return "modules/sys/sysLogin";
        }

        addMessage(redirectAttributes, "删除机构成功");
        return "redirect:" + Global.getAdminPath() + "/sys/office/?repage";
    }
    @RequiresPermissions("sys:office:del")
    @RequestMapping(value = "deleteUseable")
    public String deleteUseable(Office office, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        try{
            Office company = UserUtils.getSelectCompany();
            if ("1".equals(company.getId())) {
                if (UserUtils.getUser().isAdmin()) {
                    String[] ids = office.getParentIds().split(",");
                    if (ids.length>1) {
                        int lenght = ids.length - 1;
                        for (int i = lenght; i > 0; i--) {
                            Office o = officeService.get(ids[1]);
                            if (o.getType().equals("1")) {
                                company = o;
                                break;
                            }
                        }
                    }else{
                        company = new Office("1");
                    }
                }else {
                    addMessage(redirectAttributes, "无操作权限!");
                }
            }
            String str = "成功";
            if ("1".equals(office.getUseable())){
                officeService.updateUseable(office);
                addMessage(redirectAttributes, "该机构及所有子机构项启用"+str);
            }else {
                List<User> users = systemService.findUserByOffices(office,company);
                if (users==null||users.size()==0){
                    officeService.updateUseable(office);
                }else {
                    str = "失败,机构下存在用户不能禁用!";
                }
                addMessage(redirectAttributes, "该机构及所有子机构项禁用"+str);
            }
        }catch (Exception e){
            logger.error("Exception e:"+e);
            if ("1".equals(office.getUseable())){
                addMessage(redirectAttributes, "该机构及所有子机构项启用失败");
            }else {
                addMessage(redirectAttributes, "该机构及所有子机构项禁用失败");
            }
        }
        return "redirect:" + Global.getAdminPath() + "/sys/office/?repage";
    }

    @ResponseBody
    @RequestMapping(value = "userCompany")
    public List<Map<String, Object>> userCompany(@RequestParam(required = false) String extId, HttpServletResponse response){
        List<Map<String, Object>> maps = new ArrayList<>();
        User user = UserUtils.getUser();
        List<Office> offices = officeService.findByUserId(user.getId());
        for (Office office : offices){
            Map<String, Object> map = new HashMap<>();
            map.put("companyId",office.getId());
            map.put("companyName",office.getTopCompany());
            if (office.getId().equals(user.getComId())){
                map.put("is",true);
            }else {
                map.put("is",false);
            }
            maps.add(map);
        }
        return maps;
    }
    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                              @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = officeService.findList(isAll);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                map.put("type", e.getType());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataAll")
    public List<Map<String, Object>> treeDataAll(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                 @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office office = new Office();
        office.setParentIds(UserUtils.getSelectCompany().getId());
        List<Office> list = officeService.findByParentIdsLike(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }
    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型 公司
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataAlls")
    public List<Map<String, Object>> treeDataAlls(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                 @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office office = new Office();
        User u = UserUtils.getUser();
        office.setParent(UserUtils.getSelectOffice().getParent());
        List<Office> list = officeService.findByParentId(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }
    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataCompany")
    public List<Map<String, Object>> treeDataCompany(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                 @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office office = new Office();
        office.setParentIds(UserUtils.getSelectCompany().getId());
        List<Office> list = officeService.findByCompany(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataCompanyDSF")
    public List<Map<String, Object>> treeDataCompanyDSF(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                     @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office office = new Office();
        List<Office> list = officeService.findByCompanyDSF(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pIds", e.getParentIds());
                map.put("pId", e.getParentId());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取岗位JSON数据。
     *
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataRole")
    public List<Map<String, Object>> treeDataRole(@RequestParam(required = false) String userId,@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                  @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = new ArrayList<>();
        Office userOffice = UserUtils.getSelectOffice();
        if (UserUtils.getUser().isAdmin()){
            list = officeService.findAll();
        }else {
            Office office = new Office();
            if (StringUtils.isBlank(userOffice.getBranchOffice())){
                office.setParentIds(UserUtils.getSelectCompany().getId());
                list = officeService.findByParentIdsLike(office);
            }else {
               office.setParentIds(userOffice.getBranchOffice());
                list = officeService.findByParentIdsLike(office);
            }

        }


        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pIds", e.getParentIds());
                map.put("pId", e.getParentId());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                map.put("look", false);
                mapList.add(map);
            }
        }
        Office company = new Office();
        if (StringUtils.isNotBlank(userId)) {
            company = UserUtils.get(userId).getCompany();
        } else {
            company = UserUtils.getSelectCompany();
        }
        Role roles = new Role();
        if (!UserUtils.getUser().isAdmin()){
            roles.setCompany(company);
            roles.setBranchCompany(new Office(userOffice.getBranchOffice()));
        }
        List<Role> roleList = UserUtils.getRoleListByCompanys(roles);
        for (int i = 0; i < roleList.size(); i++) {
            Role e = roleList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("name", e.getName());
            map.put("pId", e.getOffice().getId());
            map.put("pIds", e.getOffice().getParentIds()+e.getOffice().getId()+",");
            map.put("isParent", false);
            map.put("look", true);
            mapList.add(map);
        }
        return mapList;
        /*Office company = new Office();
        if (StringUtils.isNotBlank(userId)) {
            company = UserUtils.get(userId).getCompany();
        } else {
            company = UserUtils.getSelectCompany();
        }
        Role roles = new Role();
        roles.setCompany(company);
        List<Role> roleList = UserUtils.getRoleListByCompany(roles);
        for (int i = 0; i < roleList.size(); i++) {
            Role e = roleList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("name", e.getTopCompany());
            map.put("isParent", false);
            mapList.add(map);
        }*/
    }
    /**
     * 获取角色JSON数据。
     *
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataRoleActivity")
    public List<Map<String, Object>> treeDataRoleActivity(HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office company = UserUtils.getSelectCompany();
        SysRoleActivity roleActivity = new SysRoleActivity();
        roleActivity.setCompanyId(company.getId());
        List<SysRoleActivity> roleList = UserUtils.getRoleActivityListByCompany(roleActivity);
        if (roleList!=null && roleList.size()!=0){
            for (int i = 0; i < roleList.size(); i++) {
                SysRoleActivity e = roleList.get(i);
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("isParent", false);
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取角色JSON数据。
     *
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "treeDataRoleActivitys")
    public String treeDataRoleActivitys(SysRoleActivity sysRoleActivity,String url,boolean isAll,String type,boolean isSingle,HttpServletRequest request, HttpServletResponse response, Model model) {
        Office company = UserUtils.getSelectCompany();
        sysRoleActivity.setCompanyId(company.getId());
        List<SysRoleActivity> roleList = UserUtils.getRoleActivityListByCompany(sysRoleActivity);
        //model.addAttribute("sysRoleActivity", sysRoleActivity);
        model.addAttribute("isSingle", isSingle);
        model.addAttribute("url", url);
        model.addAttribute("isAll", isAll);
        model.addAttribute("type", type);
        model.addAttribute("roleList", roleList);
        return  "modules/sys/gridSelectRole";
    }
    /**
     * 获取角色JSON数据。
     *
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataRoleActivityEnname")
    public List<Map<String, Object>> treeDataRoleActivityEnname(HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office company = UserUtils.getSelectCompany();
        SysRoleActivity roleActivity = new SysRoleActivity();
        roleActivity.setCompanyId(company.getId());
        List<SysRoleActivity> roleList = UserUtils.getRoleActivityListByCompany(roleActivity);
        for (int i = 0; i < roleList.size(); i++) {
            SysRoleActivity e = roleList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getEnname());
            map.put("name", e.getName());
            map.put("isParent", false);
            mapList.add(map);
        }
        return mapList;
    }

    @RequestMapping("compInfo")
    @ResponseBody
    public Office queryCompInfo(String id){
        Office office = officeService.get(id);
        if(office!=null) {
            office.setSimpleName(UserUtils.getSysParamByCompany("company_shortname",office.getId()));
            office.setBranchSimpleName(UserUtils.getSysParamByCompany("branch_shortname",office.getId()));
        }
        return  office;
    }
    @RequestMapping(value = "gridSelectUser")
    public String gridSelectUser(WorkStaffBasicInfo workStaffBasicInfo,String url,boolean isAll,String type,boolean isSingle, HttpServletRequest request, HttpServletResponse response, Model model){
        List<Office> list =new ArrayList<>();
        Office office=UserUtils.getSelectOffice();
        if(StringUtils.isNotBlank(office.getBranchOffice())){
            Office branchOffice=officeDao.get(office.getBranchOffice());
            workStaffBasicInfo.setBranchOffice(branchOffice);
        }else{
            workStaffBasicInfo.setBranchOffice(UserUtils.getSelectCompany());
        }
        Page<WorkStaffBasicInfo> page=new Page<>();
        if("1".equals(type)){//列表没有转正申请的员工，单选
            workStaffBasicInfo.setStatus("试用");
             page = workStaffBasicInfoService.findUserApplyPage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }else if("2".equals(type)){//劳动关系员工
            page = workStaffBasicInfoService.findUserShipList(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }else if("3".equals(type)){
            workStaffBasicInfo.setUserId(UserUtils.getUser().getId());
            page = workStaffBasicInfoService.findUserListPage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }else if("5".equals(type)){
            //人员信息库引用
            page = workStaffBasicInfoService.findAchivePage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }else if("4".equals(type)){
            //人员信息库引用
            workStaffBasicInfo.setBranchOffice(null);
            workStaffBasicInfo.setSqlStr("AND a.status in ('正式','试用','劳务') and a.office_id in (  SELECT ss.id FROM sys_office ss where ss.id='"+UserUtils.getSelectBranchOffice()+"' or ss.parent_ids  like concat('%','"+UserUtils.getSelectBranchOffice()+"','%')) ");
            page = workStaffBasicInfoService.findUserListPage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }else{
            workStaffBasicInfo.setSqlStr("AND a.status in ('正式','试用','劳务')");
             page = workStaffBasicInfoService.findUserListPage(new Page<WorkStaffBasicInfo>(request, response), workStaffBasicInfo);
        }
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
        model.addAttribute("isSingle", isSingle);
        model.addAttribute("url", url);
        model.addAttribute("isAll", isAll);
        model.addAttribute("type", type);
        model.addAttribute("page", page);
        return  "modules/sys/gridSelectUser";
    }


    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataBranchOffice")
    public List<Map<String, Object>> treeDataBranchOffice(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                     @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll,@RequestParam(required = false) String branchOffice, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = new ArrayList<>();
        if (StringUtils.isBlank(branchOffice)){
            list = officeService.findByBranchOffice();
        }else {
           list = officeService.findByBranchOfficeInfo(branchOffice);
        }
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：公司；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeDataAllOffice")
    public List<Map<String, Object>> treeDataAllOffice(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                                 @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Office office=UserUtils.getSelectOffice();
       // Office branchOffice=officeDao.get(office.getBranchOffice());
        List<Office> list = officeService.treeDataAllOffice(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getTopCompany());
                if (type != null && "3".equals(type)) {
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "validate")
    public AjaxJson validate(String id) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean inUse = officeService.validate(id);
        ajaxJson.getBody().put("inUse",inUse);
        return ajaxJson;
    }
}
