/**
 * Description: 部门控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-14 下午 17:27:15
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.DepartmentVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.PathUtil;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.CityDepConfigListResponse;
import com.house365.ws.beans.response.DepartmentListResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.interfaces.server.ICityDepConfig;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.system.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 部门控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController {

    /**
     * 自动注入部门WS实现
     */
    @Autowired
    private IDepartment department;

    @Autowired
    private IUser user;

    @Autowired
    private ICityDepConfig cityDepConfig;

    /**
     * 去新增部门
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增部门
     *
     * @param vo     部门页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createDepartment(
            @Valid DepartmentVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        DepartmentEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                DepartmentRequest request = new DepartmentRequest();
                request.setEntity(entity);
                DepartmentResponse response = department.addDepartment(request);
                Integer id = response.getEntity().getId();
                return "redirect:/department/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除部门
     *
     * @param id 部门页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    department.deleteDepartmentById(Integer.valueOf(ids[i]));
                }
            } else {
                department.deleteDepartmentById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看部门
     *
     * @param id 部门页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "detail/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        DepartmentResponse response = department.getDepartmentById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改部门
     *
     * @param id 部门页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable(value = "id") Integer id, Model model) {
        DepartmentResponse response = department.getDepartmentById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改部门
     *
     * @param vo     部门页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    public String updateDepartment(
            @Valid DepartmentVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model, HttpServletRequest httpRequest
    ) {
        DepartmentEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                DepartmentRequest request = new DepartmentRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") DepartmentResponse rersponse = department.updateDepartment(request);

                DepartmentEntity realDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                        SessionConstants.SESSION_REAL_DEPT_KEY);
                DepartmentEntity currDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                        SessionConstants.SESSION_CURRNET_DEPT_KEY);
                DepartmentEntity originDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                        SessionConstants.SESSION_ORIGIN_DEPT_KEY);
                realDept = department.getDepartmentById(realDept.getId()).getEntity();
                currDept = department.getDepartmentById(currDept.getId()).getEntity();
                originDept = department.getDepartmentById(originDept.getId()).getEntity();
                httpRequest.getSession().setAttribute(SessionConstants.SESSION_REAL_DEPT_KEY, realDept);
                httpRequest.getSession().setAttribute(SessionConstants.SESSION_ORIGIN_DEPT_KEY, originDept);
                httpRequest.getSession().setAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY, currDept);

                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/department/detail/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询部门
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        DepartmentListRequest listRequest = new DepartmentListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        DepartmentListResponse response = department.getDepartmentList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("departments", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = {"", "main"}, method = RequestMethod.GET)
    public String main() {
        department.getRoot();
        return getAutoUrl();
    }

    @RequestMapping(value = {"inner"}, method = RequestMethod.GET)
    public String inner(HttpServletRequest request, Model model) {
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(10);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    @RequestMapping(value = {"transferDept"}, method = RequestMethod.GET)
    public String transferDept(HttpServletRequest request, Model model) {
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    @RequestMapping(value = {"transferDept/{deptId}/{userId}"}, method = RequestMethod.GET)
    @ResponseBody
    public String transferDeptAction(
            @PathVariable(value = "deptId") Integer deptId, @PathVariable(value = "userId") Integer userId,
            HttpServletRequest request, Model model
    ) {
        DepartmentEntity deptEntity = department.getDepartmentById(deptId).getEntity();
        UserEntity userEntity = user.getUserById(userId).getEntity();
        if (deptEntity == null || userEntity == null) {
            return null;
        }
        userEntity.setDeptId(deptEntity.getId());
        userEntity.setDeptUrlPath(deptEntity.getUrlPath());
        UserEntity currUser = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        userEntity.setUpdateTime(new Date());
        userEntity.setUpdateUserid(currUser.getId());
        userEntity.setUpdateUsername(currUser.getName());

        UserRequest userRequest = new UserRequest();
        userRequest.setEntity(userEntity);
        user.updateUserAndSyncToWechat(userRequest);
        return "success";
    }

    @RequestMapping(value = {"Simple"}, method = RequestMethod.GET)
    public String Simple() {
        return getAutoUrl();
    }

    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public String tree(
            HttpServletRequest request, @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "show", required = false, defaultValue = "") String show,
            @RequestParam(value = "async", required = false, defaultValue = "false") boolean async, Model model
    ) {

        List<DepartmentEntity> models = null;
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        if (!StringUtils.isEmpty(searchName)) {
            map.put("LIKE_name", searchName);
            DepartmentListResponse resp = department.getDepartmentList(listReq);
            models = resp.getObjectList();
            if (!async) { // 异步模式只查自己
                List<DepartmentEntity> children = department.findChildrenListByPath(models);
                models.removeAll(children);
                models.addAll(children);
            }
        } else {
            if (!async) { // 非异步 查自己和子子孙孙
                DepartmentListResponse resp = department.getDepartmentList(listReq);
                models = resp.getObjectList();
            } else { // 异步模式只查根 和 根一级节点
                models = department.findRootAndChild();
            }
        }

        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    @RequestMapping("ajax/autocomplete")
    @ResponseBody
    public Set<String> autocomplete(
            HttpServletRequest request, @RequestParam("term") String name,
            @RequestParam(value = "excludeId", required = false) String excludeId
    ) {
        try {
            name = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentResponse deptEntity = department.getDepartmentById(userEntity.getDeptId());
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");

        if (!Strings.isNullOrEmpty(name)) {// 按name模糊查
            map.put("LIKE_name", name);
        }
        if (!Strings.isNullOrEmpty(excludeId)) {
            map.put("NOTEQ_id", excludeId);
        }

        List<DepartmentEntity> list = department.getDepartmentList(listReq).getObjectList();
        return Sets.newHashSet(Lists.transform(list, new Function<DepartmentEntity, String>() {
            @Override
            public String apply(DepartmentEntity input) {
                return input.getName();
            }
        }));
    }

    @RequestMapping(value = "getByCity")
    @ResponseBody
    public Object getByCity(
            @RequestParam(value = "city", required = false) String city,
            @RequestParam(value = "type", required = false) String type
    ) {
        List<DepartmentEntity> departList;
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        DepartmentResponse deptEntity = department.getDepartmentById(Integer.valueOf(city));
//        map.put("EQ_urlPath", deptEntity.getEntity().getUrlPath() + "/");
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        departList = department.getDepartmentList(listReq).getObjectList();

        if ("channelReport".equalsIgnoreCase(type)) {
            CityDepConfigListRequest cityDepConfigListRequest = new CityDepConfigListRequest();
            Map<String, Object> channelReq = new HashMap<>();
            channelReq.put("EQ_city", deptEntity.getEntity().getId());
            cityDepConfigListRequest.setSearchParams(channelReq);
            CityDepConfigListResponse response = cityDepConfig.getCityDepConfigList(cityDepConfigListRequest);
            String selectedDepts = response.getObjectList().get(0).getDept();
            setPageSelectedFlag(departList, selectedDepts.split(","));
        }

        return departList;
    }

    @RequestMapping(value = "ajax/load")
    @ResponseBody
    public Object load(
            HttpServletRequest request, @RequestParam(value = "async", defaultValue = "true") boolean async,
            @RequestParam(value = "asyncLoadAll", defaultValue = "false") boolean asyncLoadAll,
            @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "id", required = false) String parentId,
            @RequestParam(value = "excludeId", required = false) Integer excludeId,
            @RequestParam(value = "onlyCheckLeaf", required = false, defaultValue = "false") boolean onlyCheckLeaf,
            @RequestParam(value = "show", required = false) String show
    ) {
        List<DepartmentEntity> models;
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(10);
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentResponse deptEntity = department.getDepartmentById(userEntity.getDeptId());
        map.put("REGEXP_urlPath", "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        try {
            searchName = URLDecoder.decode(searchName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        if (!Strings.isNullOrEmpty(searchName)) {// 按name模糊查
            map.put("LIKE_name", searchName);
            DepartmentListResponse resp = department.getDepartmentList(listReq);
            models = resp.getObjectList();
            if (!async || asyncLoadAll) {// 非异步模式 查自己及子子孙孙 但排除
                List<DepartmentEntity> children = department.findChildrenListByPath(models);
                models.removeAll(children);
                models.addAll(children);
            }
        } else {
            DepartmentListRequest req = new DepartmentListRequest();
            Map<String, Object> parameter = new HashMap<>(10);

            if (parentId != null) {
                parameter.put("EQ_parentId", parentId);
            }

            if (async && !asyncLoadAll && null != excludeId) {
                parameter.put("NOTEQ_id", excludeId);
            }

            if (null == parentId && !asyncLoadAll) {
                models = department.findRootAndChild();
            } else {
                req.setSearchParams(parameter);
                req.setOrderColumn("position");
                req.setOrderMode("asc");
                models = department.getDepartmentList(req).getObjectList();
            }
        }

        return models;
    }

    @RequestMapping(value = "ajax/{parent}/appendChild", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxAppendChild(@PathVariable("parent") Integer parent) {
        DepartmentEntity child = new DepartmentEntity();
        child.setName("新部门");
        child.setDescripition("新部门");
        child.setRoot(false);
        Date date = new Date();
        child.setCreateTime(date);
        child.setUpdateTime(date);
        try {
            child = department.appendChild(parent, child);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return child;
    }

    @RequestMapping(value = "ajax/{id}/rename", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxRename(
            HttpServletRequest httpRequest, @PathVariable("id") Integer id, @RequestParam("newName") String newName
    ) {
        DepartmentEntity dept = department.getDepartmentById(id).getEntity();
        dept.setName(newName);
        try {
            DepartmentRequest deptRequest = new DepartmentRequest();
            deptRequest.setEntity(dept);
            department.updateDepartment(deptRequest);

            DepartmentEntity realDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_REAL_DEPT_KEY);
            DepartmentEntity currDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            DepartmentEntity originDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_ORIGIN_DEPT_KEY);
            realDept = department.getDepartmentById(realDept.getId()).getEntity();
            currDept = department.getDepartmentById(currDept.getId()).getEntity();
            originDept = department.getDepartmentById(originDept.getId()).getEntity();
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_REAL_DEPT_KEY, realDept);
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_ORIGIN_DEPT_KEY, originDept);
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY, currDept);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return dept;
    }

    @RequestMapping(value = "ajax/{id}/delete", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxDelete(@PathVariable("id") Integer id) {

        DepartmentListRequest req = new DepartmentListRequest();
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_parentId", id);
        req.setSearchParams(paraMap);
        req.setPaging(new Page(Integer.MAX_VALUE));
        DepartmentResponse result = department.getDepartmentById(id);
        List<DepartmentEntity> deptList = department.getDepartmentList(req).getObjectList();
        if (deptList.size() > 0) {
            result.setResultCode(ReturnResult.CHILD_NOT_EMPTY.getResultCode());
            result.setResultMessage(ReturnResult.CHILD_NOT_EMPTY.getResultMessage());
            return result;
        }

        UserListRequest userReq = new UserListRequest();
        Map<String, Object> userParaMap = new HashMap<>(10);
        userParaMap.put("EQ_deptId", id);
        userReq.setSearchParams(userParaMap);
        userReq.setPaging(new Page(Integer.MAX_VALUE));
        List<UserEntity> userList = user.getUserList(userReq).getObjectList();
        if (userList.size() > 0) {
            result.setResultCode(ReturnResult.CHILD_NOT_EMPTY.getResultCode());
            result.setResultMessage(ReturnResult.CHILD_NOT_EMPTY.getResultMessage());
            return result;
        }

        DepartmentResponse delRsp = department.deleteDepartmentById(id);
        return delRsp;
    }

    @RequestMapping(value = "asyncDepartment")
    public void asyncDepartment() {
        DepartmentListRequest req = new DepartmentListRequest();
        Map<String, Object> paraMap = new HashMap<>();
        req.setSearchParams(paraMap);
        department.getDepartments(req);
    }

    private List<DepartmentEntity> getDepartmentEntities(String[] departmentPara, String urlPath) {
        List<DepartmentEntity> departmentEntities;
        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);
        Map<String, Object> dmap = new HashMap<>(10);
        dmap.put("EQ_urlPath", urlPath);
        dlr.setParamMap(dmap);
        dlr.setOrderColumn("id");
        dlr.setOrderMode("asc");
        dlr.setSearchParams(dmap);
        dlr.setPaging(dPage);
        departmentEntities = department.getDepartmentList(dlr).getObjectList();
        // 设置页面多选框选中效果
        setPageSelectedFlag(departmentEntities, departmentPara);
        return departmentEntities;
    }

    private void setPageSelectedFlag(List<DepartmentEntity> departmentEntities, String[] department) {
        if (department != null) {
            // 页面选中效果
            for (DepartmentEntity departmentEntity : departmentEntities) {
                departmentEntity.setType("0");
                for (String deptm : Lists.newArrayList(department)) {
                    if (deptm.equals(departmentEntity.getId().toString())) {
                        departmentEntity.setType("1");
                        break;
                    }
                }
            }
        }
    }

}
