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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.Collections3;
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.API.easemob.EasemobController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.iim.entity.LayGroup;
import com.jeeplus.modules.iim.service.LayGroupService;
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.entity.Company;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.CompanyService;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.workcompanyinfo.service.CompanyinfoService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.history.HistoricProcessInstance;
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.*;
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.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业管理Controller
 * @author meng
 * @version 2017-03-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/company")
public class CompanyController extends BaseController {

    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyinfoService companyinfoService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserofficeService userofficeService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private OfficeDao officeDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private LayGroupService layGroupService;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;
    @Autowired
    private UserService userService;

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

    /**
     * 企业新增列表页面
     */
    @RequiresPermissions("sys:company:list")
    @RequestMapping(value = {"companyAddList"})
    public String companyAddList(Company company, HttpServletRequest request, HttpServletResponse response, Model model) {
        company.setCreateBy(UserUtils.getUser());
        company.setUSEABLE("1");
        Page<Company> page = companyService.findPages(new Page<Company>(request, response), company);
        User user = UserUtils.getUser();
        for (Company company1:page.getList()){
            Role role = new Role();
            company1.setMaster(0);
            /*if (company1.getCompanyId().equals(UserUtils.getSelectCompany().getId())){
                role.setCompany(new Office(company1.getCompanyId()));
                role.setUser(user);
                Integer count = roleDao.getByGlyCount(role);
                company1.setMaster(count);
            }*/
        }
        model.addAttribute("page", page);
        return "modules/sys/companyAddList";
    }
    /**
     * 企业新增列表页面
     */
    @RequiresPermissions("sys:company:list")
    @RequestMapping(value = {"userAddCompany"})
    public String userAddCompany(Company company, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (StringUtils.isNotBlank(company.getName())){
            company.setUSEABLE("1");
            Page<Company> page = companyService.findPage(new Page<Company>(request, response), company);
            model.addAttribute("page", page);
        }else {
            model.addAttribute("page", companyService.findPage(new Page<Company>(request, response), null));
        }
        return "modules/sys/userAddCompany";
    }

    /**
     * 企业信息列表页面
     */
    @RequiresPermissions("sys:company:list")
    @RequestMapping(value = {"list", ""})
    public String list(Company company, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!UserUtils.getUser().isAdmin()) {
            boolean b = UserUtils.isManager();
            if (b) {
                company.setCompanyId(UserUtils.getSelectCompany().getId());
            }else {
                Page<Company> page = new Page<Company>();
                model.addAttribute("page", page);
                return "modules/sys/userJoinCompany";
            }
        }
        Page<Company> page = companyService.findPage(new Page<Company>(request, response), company);
        model.addAttribute("page", page);
        return "modules/sys/companyList";
    }

    /**
     * 新增企业信息列表页面
     */
    @RequiresPermissions(value={"sys:company:view","sys:company:add","sys:company:edit"},logical=Logical.OR)
    @RequestMapping(value = "addForm")
    public String addForm(Company company, Model model) {
        model.addAttribute("company", company);
        return "modules/sys/companyAddForm";
    }



    /**
     * 查看，增加，编辑企业信息表单页面
     */
    @RequiresPermissions(value={"sys:company:view","sys:company:add","sys:company:edit"},logical=Logical.OR)
    @RequestMapping(value = "form")
    public String form(@RequestParam(value = "readAttr",required = false)String readAttr,Company company, Model model) {
        model.addAttribute("company", company);
        model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
        return "modules/sys/companyForm";
    }

    /**
     * 查看，增加，编辑企业信息表单页面
     */
    @RequestMapping(value = "addUserInfo")
    public String addUserInfo(User user ,Model model) {
        return "modules/sys/addUserInfo";
    }

    /**
     * 管理员邀请同事
     */
    @RequestMapping(value = "addUserToCompany")
    public String addUserToCompany(User u, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) {
        try {

            /*if(!UserUtils.isManager()){
                addMessage(redirectAttributes, "您不是管理员");
                return "redirect:"+Global.getAdminPath()+"/sys/company/companyAddList?repage";
            }*/
            if(u.getMobile()==null||"".equals(u.getMobile())){
                addMessage(redirectAttributes, "您的手机号不能为空");
                return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
            }
            User userLogin = UserUtils.getByLoginName(u.getMobile());
            if (userLogin == null) {
                addMessage(redirectAttributes, "员工添加失败,该手机号未注册");
                return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
            }
            Role role = roleDao.get(u.getRoleIds());
            List<Office> companyList = UserUtils.getAllCompany(userLogin);
            EasemobController controller = new EasemobController();
            controller.SendMessage();
            String companyId = UserUtils.getSelectCompany().getId();
            for (Office office : companyList) {
                if (role.getCompany().getId().equals(office.getId())) {
                    addMessage(redirectAttributes, "添加失败，该用户已是该企业员工");
                    return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
                }
            }
            /*EasemobInfo easemobImuser = new EasemobInfo();
            Office office = officeService.get(companyId);
            easemobImuser.setUserId(userLogin.getId());
            easemobImuser.setGroupId(office.getGroupId());
            easemobImuser.setJoinStatus("2");
            easemobImuser.setGroupName(office.getGroupName());
            List<EasemobInfo> list = easemobInfoService.findList(easemobImuser);
            if (list==null || list.size()==0){
                easemobInfoService.save(easemobImuser);
                try {
                    UserNames userNames = new UserNames();
                    UserName userList = new UserName();
                    userList.add(userLogin.getId());
                    userNames.usernames(userList);
                    easemobChatGroup.addBatchUsersToChatGroup(office.getGroupId(), userNames);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
            // 岗位数据有效性验证，过滤不在授权内的岗位
            if(!UserUtils.getUser().isAdmin()) {
                if (!role.getCompany().getId().equals(companyId) || role.getCompany().getId().equals("1")) {
                    addMessage(model, "保存用户'" + userLogin.getLoginName() + "'失败,当前公司没有这个岗位！");
                    return addUserInfo(userLogin, model);
                }
            }
            role.setOffice(u.getOffice());
            /*List<Role> roleList =systemService.getRoleList(userLogin.getId(),"");
            boolean b = true;
            for (Role r : roleList){
                Office o = r.getCompany();
                if (companyId.equals(o.getId())){
                    roleList.remove(r);
                    roleList.add(roleDao.get(roleId));
                    b = false;
                    break;
                }
            }
            if (b){
                roleList.add(roleDao.get(roleId));
            }
            userLogin.setRoleList(roleList);
            if (roleIdList==null||roleIdList.size()==0){
                addMessage(redirectAttributes, "保存用户'" + userLogin.getLoginName() + "'失败,岗位不能为空！");
                return "redirect:" + adminPath + "/sys/company/useableCompany?repage";
            }*/
            String name = userLogin.getName();
            userLogin.setNo(u.getNo());
            userLogin.setIshide(u.getIshide());
            userLogin.setName(name);
            userLogin.setOffice(u.getOffice());
            userLogin.setCompany(new Office(companyId));
            userLogin.setComId(companyId);
            systemService.saveUserInfo(userLogin);
            systemService.assignUserToRole(role, userLogin,0);
            Useroffice useroffice = new Useroffice();
            useroffice.setStatus("3");
            useroffice.setDelFlag("0");
            useroffice.setRemarks("管理员邀请");
            useroffice.setMaster(UserUtils.getUser().getId());
            useroffice.setCompanyId(companyId);
            useroffice.setUserId(userLogin.getId());
            useroffice.setOfficeId(u.getOffice().getId());
            List<Useroffice> listOffice = userofficeService.findList(useroffice);
            if(listOffice==null || listOffice.size()==0){
                userofficeService.save(useroffice);
            }else {
                Useroffice oldUseroffice = listOffice.get(0);
                oldUseroffice.setOfficeId(request.getParameter("office.id"));
                userofficeService.save(oldUseroffice);
            }
            boolean bool = systemService.outUserInRole(new Role("1"), systemService.getUser(userLogin.getId()));
            if (bool){
                systemService.saveCurrentCompanyById(userLogin.getId(), companyId, u.getOffice().getId());
            }
            Office office = officeService.get(companyId);
            layGroupService.saveUsers(office.getGroupId(),userLogin.getId());
            addMessage(redirectAttributes, "员工添加成功");
        }catch (Exception e){
            logger.info("Exception e:"+e);
            addMessage(redirectAttributes, "员工添加失败");
            return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
        }
        return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
    }

    /**
     * 申请企业信息(新增)
     */
    @RequiresPermissions(value={"sys:company:view","sys:company:add"},logical=Logical.OR)
    @RequestMapping(value = "add")
    public String add(Company company, Model model,HttpServletRequest request,
                      RedirectAttributes redirectAttributes,
                      @RequestParam("this_upload_files")MultipartFile[] this_upload_files,
                      @RequestParam("next_upload_files")MultipartFile[] next_upload_files) throws Exception{

        if (!beanValidator(model, company)){
            return form("",company, model);
        }
        StringBuilder company_licences = new StringBuilder();
        StringBuilder company_logo = new StringBuilder();

        if(!company.getIsNewRecord()){//编辑表单保存
            Company t = companyService.get(company.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(company, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            upload_company_licences_logo(this_upload_files,next_upload_files,request,company_licences,company_logo);

            if(!StringUtils.isBlank(company_licences.toString()))
                t.setLicences(company_licences.substring(0,company_licences.lastIndexOf(",")));
            if(!StringUtils.isBlank(company_logo.toString()))
                t.setLogo(company_logo.substring(0,company_logo.lastIndexOf(",")));
            companyService.addCompany(t);//保存
            if(t.getUSEABLE().equals("1")){
                Office office = officeService.get(t.getCompanyId());
                office.setLogo(t.getLogo());
                officeService.save(office);
            }
            addMessage(redirectAttributes, "修改企业信息成功");
        }else{//新增表单保存
            company.setUSEABLE("0");
            company.setUseableStatus("1");
            upload_company_licences_logo(this_upload_files,next_upload_files,request,company_licences,company_logo);

            if(!StringUtils.isBlank(company_licences.toString()))
                company.setLicences(company_licences.substring(0,company_licences.lastIndexOf(",")));
            if(!StringUtils.isBlank(company_logo.toString()))
                company.setLogo(company_logo.substring(0,company_logo.lastIndexOf(",")));
            companyService.addCompany(company);//保存
            addMessage(redirectAttributes, "申请企业成功");
        }

        String createBy = company.getUpdateBy()!=null?company.getUpdateBy().getId():null;
        return "redirect:"+Global.getAdminPath()+"/sys/company/companyAddList?createBy="+(createBy!=null?createBy:"");
    }


    /**
     * 保存企业信息(修改)
     */
    @RequiresPermissions(value={"sys:company:add","sys:company:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(Company company, Model model,HttpServletRequest request,
                       RedirectAttributes redirectAttributes,
                       @RequestParam("this_upload_files")MultipartFile[] this_upload_files,
                       @RequestParam("next_upload_files")MultipartFile[] next_upload_files) throws Exception{

        if (!beanValidator(model, company)){
            return form("",company, model);
        }
        StringBuilder company_licences = new StringBuilder();
        StringBuilder company_logo = new StringBuilder();

        if(!company.getIsNewRecord()){//编辑表单保存
            Company t = companyService.get(company.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(company, t);//将编辑表单中的非NULL值覆盖数据库记录中的值

            upload_company_licences_logo(this_upload_files,next_upload_files,request,company_licences,company_logo);

            if(!StringUtils.isBlank(company_licences.toString()))
                t.setLicences(company_licences.substring(0,company_licences.lastIndexOf(",")));
            if(!StringUtils.isBlank(company_logo.toString()))
                t.setLogo(company_logo.substring(0,company_logo.lastIndexOf(",")));

            companyService.save(t);//保存
            if(t.getUSEABLE().equals("1")){
                Office office = officeService.get(t.getCompanyId());
                office.setLogo(t.getLogo());
                officeService.save(office);
            }

        }else{
            upload_company_licences_logo(this_upload_files,next_upload_files,request,company_licences,company_logo);

            if(!StringUtils.isBlank(company_licences.toString()))
                company.setLicences(company_licences.substring(0,company_licences.lastIndexOf(",")));
            if(!StringUtils.isBlank(company_logo.toString()))
                company.setLogo(company_logo.substring(0,company_logo.lastIndexOf(",")));

            companyService.save(company);
        }

        addMessage(redirectAttributes, "保存企业信息成功");
        return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
    }

    /**
     * 上传营业执照和logo工具
     * @param this_upload_files
     * @param next_upload_files
     * @param request
     * @param company_licences
     * @param company_logo
     */
    private void upload_company_licences_logo(MultipartFile[] this_upload_files,MultipartFile[] next_upload_files, HttpServletRequest request,
                                              StringBuilder company_licences, StringBuilder company_logo){

        //--- 上传营业执照图片
        String  this_uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/company_licences/"+System.nanoTime());
        new File(this_uploadFolder).mkdirs();
        List<String> this_imgList = new ArrayList<>();
        if(this_upload_files!=null && this_upload_files.length>0){
            for(int i=0;i<this_upload_files.length;i++){
                if(this_upload_files[i]==null || this_upload_files[i].getSize()==0)
                    continue;
                String imageName = System.nanoTime()+this_upload_files[i].getOriginalFilename();
                String imageNewName = this_uploadFolder+"/"+imageName;
                this_imgList.add(imageNewName);
                try{
                    this_upload_files[i].transferTo(new File(imageNewName));
                }catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                }
            }
        }

        InputStream inputStream = null;
        for(int i=0;i<this_imgList.size();i++) {
            String filePath = this_imgList.get(i);
            try {
                inputStream = new FileInputStream(new File(filePath));
                OSSClientUtil ossUtil = new OSSClientUtil();
                String suffix = filePath.substring(filePath.lastIndexOf("."));
                String name = System.nanoTime() + suffix;
                ossUtil.uploadFile2OSS(inputStream, Global.getLogo(), name);
                company_licences.append(Global.getAliyunUrl() + "/" + Global.getLogo() + name+",");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null)
                        inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //--- 上传公司logo图片
        String  next_uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/company_logo/"+System.nanoTime());
        new File(next_uploadFolder).mkdirs();
        List<String> next_imgList = new ArrayList<>();
        if(next_upload_files!=null && next_upload_files.length>0){
            for(int i=0;i<next_upload_files.length;i++){
                if(next_upload_files[i]==null || next_upload_files[i].getSize()==0)
                    continue;
                String imageName = System.nanoTime()+next_upload_files[i].getOriginalFilename();
                String imageNewName = next_uploadFolder+"/"+imageName;
                next_imgList.add(imageNewName);
                try{
                    next_upload_files[i].transferTo(new File(imageNewName));
                }catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                }
            }
        }

        InputStream next_inputStream = null;
        for(int i=0;i<next_imgList.size();i++) {
            String filePath = next_imgList.get(i);
            try {
                next_inputStream = new FileInputStream(new File(filePath));
                OSSClientUtil ossUtil = new OSSClientUtil();
                String suffix = filePath.substring(filePath.lastIndexOf("."));
                String name = System.nanoTime() + suffix;
                ossUtil.uploadFile2OSS(next_inputStream, Global.getLogo(), name);
                company_logo.append(Global.getAliyunUrl() + "/" + Global.getLogo() + name + ",");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (next_inputStream != null)
                        next_inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 加入企业
     */
	/*@RequiresPermissions(value={"sys:company:join"},logical=Logical.OR)
	@RequestMapping(value = "join")
	public String join(Company company, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, company)){
			return form(company, model);
		}
		Role comRole = systemService.getRoleByEnname(StringUtils.getPinYinHeadChar(company.getName(),2)+"xyg");

		if(UserUtils.getUser().getId()!=null){
			List<Office> companyList = UserUtils.getAllCompany(UserUtils.getUser());
			if(companyList!=null && companyList.size()!=0 && comRole!=null){
				for (Office office : companyList) {
					if(comRole.getCompany().getId().equals(office.getId())){
						addMessage(redirectAttributes, "加入企业失败，该用户已是该企业成员");
						return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
					}
				}
			}

		}
        EasemobInfo easemobImuser = new EasemobInfo();
		List<Office> list = officeService.findList(true);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			if (e.getName().equals(company.getName()+"人力部")){
				UserUtils.getUser().setOffice(e);
			}
			if (e.getName().equals(company.getName())){
				UserUtils.getUser().setCompany(e);
                UserUtils.getUser().setComId(e.getId());
			}

		}
		Office office = UserUtils.getUser().getCompany();
		easemobImuser.setUserId(company.getTuser().getId());
		easemobImuser.setGroupId(office.getGroupId());
		easemobImuser.setJoinStatus("2");
		easemobImuser.setGroupName(office.getGroupName());
        easemobInfoService.save(easemobImuser);
		systemService.saveUser(UserUtils.getUser());
		if(comRole!=null){
			UserUtils.getUser().setComId(comRole.getCompany().getId());
			systemService.assignUserToRole(comRole, UserUtils.getUser());
		}

		systemService.outUserInRole(new Role("1"), UserUtils.getUser());

        addMessage(redirectAttributes, "加入企业成功");
		return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
	}*/


    /**
     * 审批企业信息
     */
    @RequiresPermissions(value={"sys:company:approve"},logical=Logical.OR)
    @RequestMapping(value = "approve")
    public String approve(Company company,HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
        company.setUSEABLE("1");
        if(!UserUtils.getUser().isAdmin()){
            addMessage(redirectAttributes, "企业审批失败,没有审批权限");
            return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
        }
        String  str = companyService.applyCompany(company, request);
        if (str!=null&&"1".equals(str)){
            UserUtils.pushIm(company.getTuser().getId(),"您的企业申请成功");
            addMessage(redirectAttributes, "企业审批成功");
        }else if("2".equals(str)){
            //将申请通知设置为已读
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(company.getId());
            workProjectNotifyService.readByNotifyId(notify);
            UserUtils.pushIm(company.getUserId(),"您的企业申请失败,企业名称已被注册");
            addMessage(redirectAttributes, "企业审批失败,企业名称已被注册");
        }else{
            UserUtils.pushIm(company.getUserId(),"您的企业申请失败");
            addMessage(redirectAttributes, "企业审批失败");
        }
        if(StringUtils.isBlank(company.getHome())) {
            return "redirect:" + Global.getAdminPath() + "/sys/company/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }
    }
    /**
     * 审批企业信息
     */
    @RequestMapping(value = "userJoinCompany")
    public String userJoinCompany(Company company,HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
        AjaxJson ajaxJson = companyService.userAddCompany(company);
        addMessage(redirectAttributes, ajaxJson.getMsg());
        return "redirect:"+Global.getAdminPath()+"/sys/company/userAddCompany?repage";
    }
    /**
     * 批量审批企业信息
     */
    @RequiresPermissions(value={"sys:company:approve"},logical=Logical.OR)
    @RequestMapping(value = "approveAll")
    public String approveAll(String ids,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
        if(ids!=null){
            StringBuilder failureMsg = new StringBuilder();
            int  successNum =  0;//companyService.approveAll(ids,request);
            if(successNum==-1){
                addMessage(redirectAttributes, "企业批量审批失败");
            }else{
                String idArray[] =ids.split(",");
                int numAll = idArray.length;
                int failureNum = numAll-successNum;
                if (failureNum>0){
                    failureMsg.insert(0, "，失败 "+failureNum+" 条企业审批。");
                }
                addMessage(redirectAttributes, "已成功 "+successNum+" 条企业信息审批"+failureMsg);
            }
            return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
        }else{
            addMessage(redirectAttributes, "请选择您要审批的数据");
            return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
        }
    }

    /**
     * 审批拒绝企业信息
     */
    @RequiresPermissions(value={"sys:company:refuse"},logical=Logical.OR)
    @RequestMapping(value = "refuse")
    public String refuse(Company company,RedirectAttributes redirectAttributes) throws Exception{
        company.setUSEABLE("2");
        companyService.save(company);//保存

        //驳回企业申请后，将该条通知设置为已读；
        //由于save方法是共用的，所有更改通知已读状态的操作在这里执行
        if(company!=null){
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(company.getId());
            workProjectNotifyService.readByNotifyId(notify);
        }

        addMessage(redirectAttributes, "企业审批成功");
        UserUtils.pushIm(company.getTuser().getId(),"您的企业申请被驳回");
        if(StringUtils.isBlank(company.getHome())) {
            return "redirect:" + Global.getAdminPath() + "/sys/company/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }
    }
    /**
     * 批量审批拒绝企业信息
     */
    @RequiresPermissions(value={"sys:company:refuse"},logical=Logical.OR)
    @RequestMapping(value = "refuseAll")
    public String refuseAll(String ids, RedirectAttributes redirectAttributes) throws Exception{
        String idArray[] =ids.split(",");
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for(String id : idArray){
            if("1".equals(companyService.get(id).getUSEABLE())){
                //addMessage(redirectAttributes, "审批企业失败，已审批通过，正在使用中");
                failureNum++;
            }else if("2".equals(companyService.get(id).getUSEABLE())){
                //addMessage(redirectAttributes, "审批企业失败，已审批驳回");
                failureNum++;
            }else {
                companyService.get(id).setUSEABLE("2");
                companyService.save(companyService.get(id));//保存
                successNum++;
                //addMessage(redirectAttributes, "审批企业成功");
            }
        }
        if (failureNum>0){
            failureMsg.insert(0, "，失败 "+failureNum+" 条企业审批。");
        }
        addMessage(redirectAttributes, "已成功 "+successNum+" 条企业信息审批"+failureMsg);
        //company.setUSEABLE("2");
        //companyService.save(company);//保存

        //addMessage(redirectAttributes, "企业审批成功");
        return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
    }


    /**
     * 删除企业信息
     * 修改人:hfj
     * 修改时间：2017-09-12
     * 修改原因：企业退出后删除了用户的信息，改为保留用户信息和企业信息，物理删除企业与用户管理表
     *
     */
    @RequiresPermissions("sys:company:del")
    @RequestMapping(value = "delete")
    public String delete(Company company, RedirectAttributes redirectAttributes) {
        if("1".equals(company.getUSEABLE())){
//			addMessage(redirectAttributes, "删除企业失败，已审批通过，正在使用中");
            companyService.delete(company,1);
            addMessage(redirectAttributes, "删除企业成功");
        }else{
            companyService.deleteCompanyId(company);
        }
        if(company!=null){
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(company.getId());
            workProjectNotifyService.readByNotifyId(notify);
        }
        return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
    }
    /**
     * 启用/禁用企业信息
     * 修改人:hfj
     * 修改时间：2017-09-12
     * 修改原因：企业退出后删除了用户的信息，改为保留用户信息和企业信息，物理删除企业与用户管理表
     *
     */
    @RequestMapping(value = "companyStatus")
    public String companyStatus(Company company,String status, RedirectAttributes redirectAttributes) {
        company.setUseableStatus(status);
        companyService.save(company);
        Office com = officeDao.get(company.getCompanyId());
        if(status.equals("1")) {
            com.setUseable("1");
            officeService.updateUseable(com);
            addMessage(redirectAttributes, "启用企业成功");
        }else{
            com.setUseable("2");
            officeService.updateUseable(com);
            List<User> users = systemService.findUserByCompanyId(com.getId());
            if (users!=null && users.size()!=0){
                for (User u:users){
                    User user = UserUtils.get(u.getId());
                    Useroffice useroffice = new Useroffice();
                    useroffice.setStatus("3");
                    useroffice.setUser(u);
                    useroffice.setUserId(u.getId());
                    List<Useroffice> useroffices = userofficeService.findList(useroffice);
                    if (useroffices.size()>1){
                        for (Useroffice useroffice1:useroffices){
                            if (!useroffice1.getCompanyId().equals(com.getId())){
                                systemService.saveCurrentCompanyById(user.getId(),useroffice1.getCompanyId(),useroffice1.getOfficeId());
                            }
                        }
                    }
                    UserUtils.clearCache(user);
                    systemService.removeSession(user);
                }
            }
            addMessage(redirectAttributes, "禁用企业成功");
        }
        return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
    }
    @RequiresPermissions("sys:company:del")
    @RequestMapping(value = "deleteMy")
    public String deleteMy(Company company, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        //获取当前用户公司
        Office office = UserUtils.getSelectCompany();
        if (StringUtils.isNotBlank(company.getUSEABLE()) && "0".equals(company.getUSEABLE())){
            companyDao.deleteByLogic(company);
            WorkProjectNotify workProjectNotify = new WorkProjectNotify();
            workProjectNotify.setNotifyId(company.getId());
            UserUtils.pushMeIm("1");
            workProjectNotifyService.readByNotifyId(workProjectNotify);
            addMessage(redirectAttributes, "企业删除成功");
        }else {
            Boolean b = false;
            Company companySign = companyService.getByName(office.getName());
            int sign = 0;
            //判断是否有子公司
            List<Office> office2s = officeService.getSon(company);
            if (office2s == null || office2s.size() == 0) {
                if ("1".equals(company.getUSEABLE())) {
                    //companyService.delete(company,1);
                    List<Useroffice> userOfficeList = companyService.getUserCompanyId(company);
                    List<Useroffice> userOfficeList2 = new ArrayList<Useroffice>();
                    //无用户情况
                    if (userOfficeList.size() == 0 || userOfficeList == null) {
                        //对目前公司记录数据进行逻辑删除
                        companyDao.updateCompanyId(company);
                        companyDao.deleteCompanyInfo(company);
                        //对岗位表进行逻辑删除sys_role
                        companyDao.updateRoleId(company);
                    } else {
                        //除去管理员岗位以外的用户
                        if (userOfficeList != null && userOfficeList.size() > 0) {
                            //for (Useroffice userOffice : userOfficeList) {
                            for (int i = 0; i < userOfficeList.size(); i++) {
                                Useroffice userOffice = userOfficeList.get(i);
                                User u = UserUtils.get(userOffice.getUserId());
                                List<Role> rlist = roleDao.findList(new Role(u));
                                for (Role role :
                                        rlist) {
                                    if (role.getCompany().getId().equals(company.getCompanyId())) {
                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().contains("gly")) {
                                            userOfficeList.remove(userOffice);
                                        }
                                    }
                                }
                            }
                            userOfficeList2 = userOfficeList;
                        }
                        //判断是否存在用户
                        if (userOfficeList2 != null && userOfficeList2.size() > 0) {
                            addMessage(redirectAttributes, "该企业下存在用户，禁止删除");
                        } else {
                            //执行删除操作
                            companyService.delete(company, 1);
                            if (companySign.getId().equals(company.getId())) {
                                sign++;
                            }
                            b = true;
                            addMessage(redirectAttributes, "企业删除成功");
                        }
                    }
                } else {
                    companyService.deleteCompanyId(company);
                    if (companySign.getId().equals(company.getId())) {
                        sign++;
                    }
                    b = true;
                    addMessage(redirectAttributes, "企业删除成功");
                }
            } else {
                //addMessage(redirectAttributes, "该企业下存在用户，禁止删除");

                //删除子公司
                for (Office office2:office2s){
                    Company company1 = companyService.getByName(office2.getName());
                    if ("1".equals(company1.getUSEABLE())) {
                        //companyService.delete(company,1);
                        List<Useroffice> userOfficeList = companyService.getUserCompanyId(company1);
                        List<Useroffice> userOfficeList2 = new ArrayList<Useroffice>();
                        //无用户情况
                        if (userOfficeList.size() == 0 || userOfficeList == null) {
                            //对目前公司记录数据进行逻辑删除
                            companyDao.updateCompanyId(company1);
                            companyDao.deleteCompanyInfo(company1);
                            //对岗位表进行逻辑删除sys_role
                            companyDao.updateRoleId(company1);
                        } else {
                            //除去管理员岗位以外的用户
                            if (userOfficeList != null && userOfficeList.size() > 0) {
                                //for (Useroffice userOffice : userOfficeList) {
                                for (int i = 0; i < userOfficeList.size(); i++) {
                                    Useroffice userOffice = userOfficeList.get(i);
                                    User u = UserUtils.get(userOffice.getUserId());
                                    List<Role> rlist = roleDao.findList(new Role(u));
                                    for (Role role :
                                            rlist) {
                                        if (role.getCompany().getId().equals(company1.getCompanyId())) {
                                            if (org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().contains("gly")) {
                                                userOfficeList.remove(userOffice);
                                            }
                                        }
                                    }
                                }
                                userOfficeList2 = userOfficeList;
                            }
                            //判断是否存在用户
                            if (userOfficeList2 != null && userOfficeList2.size() > 0) {
                                addMessage(redirectAttributes, "该企业下分公司存在用户，禁止删除");
                            } else {
                                //-------删除母公司------
                                if ("1".equals(company.getUSEABLE())) {
                                    //companyService.delete(company,1);
                                    List<Useroffice> userOfficeList3 = companyService.getUserCompanyId(company);
                                    List<Useroffice> userOfficeList22 = new ArrayList<Useroffice>();
                                    //无用户情况
                                    if (userOfficeList3.size() == 0 || userOfficeList3 == null) {
                                        //对目前公司记录数据进行逻辑删除
                                        companyDao.updateCompanyId(company);
                                        companyDao.deleteCompanyInfo(company);
                                        //对岗位表进行逻辑删除sys_role
                                        companyDao.updateRoleId(company);
                                    } else {
                                        //除去管理员岗位以外的用户
                                        if (userOfficeList3 != null && userOfficeList3.size() > 0) {
                                            //for (Useroffice userOffice : userOfficeList3) {
                                            for (int i = 0; i < userOfficeList3.size(); i++) {
                                                Useroffice userOffice = userOfficeList3.get(i);
                                                User u = UserUtils.get(userOffice.getUserId());
                                                List<Role> rlist = roleDao.findList(new Role(u));
                                                for (Role role :
                                                        rlist) {
                                                    if (role.getCompany().getId().equals(company.getCompanyId())) {
                                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().contains("gly")) {
                                                            userOfficeList3.remove(userOffice);
                                                        }
                                                    }
                                                }
                                            }
                                            userOfficeList22 = userOfficeList3;
                                        }
                                        //判断是否存在用户
                                        if (userOfficeList22 != null && userOfficeList22.size() > 0) {
                                            addMessage(redirectAttributes, "该企业下存在用户，禁止删除");
                                        } else {
                                            //执行删除操作
                                            companyService.delete(company1, 1);//删除分公司
                                            //执行删除操作
                                            companyService.delete(company, 1);
                                            if (companySign.getId().equals(company.getId()) || companySign.getId().equals(company1.getId())) {
                                                sign++;
                                            }
                                            b = true;
                                            addMessage(redirectAttributes, "企业删除成功");
                                        }
                                    }
                                } else {
                                    //执行删除操作
                                    companyService.delete(company1, 1);//删除分公司
                                    companyService.deleteCompanyId(company);
                                    if (companySign.getId().equals(company.getId()) || companySign.getId().equals(company1.getId())) {
                                        sign++;
                                    }
                                    b = true;
                                    addMessage(redirectAttributes, "企业删除成功");
                                }
                            }
                        }
                    } else {
                        companyService.deleteCompanyId(company1);
                        addMessage(redirectAttributes, "企业删除成功");
                    }
                }

            }
            if (b) {
                Office com = officeDao.get(company.getCompanyId());
                LayGroup layGroup = layGroupService.getNoOwner(com.getGroupId());
                if (layGroup!=null){
                    layGroupService.delete(layGroup);
                }
            }
            //删除当前登录企业时的处理
            if(sign!=0){
                request.getSession().invalidate();
            }
        }
        return   "redirect:"+Global.getAdminPath()+"/sys/company/companyAddList";
    }
    /**
     * 员工移除与企业相关的信息
     * @param companyId
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:company:del")
    @RequestMapping(value = "deletes")
    public String deletes(String companyId, RedirectAttributes redirectAttributes) {
        if(companyId!=null&&!("").equals(companyId)){
            User user = UserUtils.getUser();
            WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
            workStaffBasicInfo.setCompany(new Office(companyId));
            workStaffBasicInfo.setUserId(user.getId());
            Integer count = workStaffBasicInfoService.getByCompany(workStaffBasicInfo);
            if (count == 0){
                String str = userService.deleteUserByCompany(user,new Office(companyId),"");
                if (str.equals("移除用户信息成功")){
                    str =  "退出企业成功";
                }else if(str.equals("公司只有您一位管理员,您不能退出企业")){
                    addMessage(redirectAttributes, str);
                    return "redirect:"+Global.getAdminPath()+"/sys/company/companyAddList";
                }
                addMessage(redirectAttributes, str);
            }else{
                addMessage(redirectAttributes, "退出企业失败,不能退出企业");
            }
            /*Useroffice companyinfo =  companyinfoService.get(id);
            Company company = new Company();
            company.setCompanyId(companyinfo.getCompanyId());//公司id
            company.setUserId(companyinfo.getUserId());//用户id
            company.setId(companyinfo.getId());//基本信息id
            *//**
             * 判断当前用户是不是管理员，
             * 如果是判断用户所在公司下有几个管理员，如果有一个管理员拒绝退出企业，多个可以退出企业！！
             *//*
            //1、查询当前用户在当前公司所在的岗位是不是管理员
            List<Role> roleList = companyService.getUserRoleComManager(company);
            if(roleList != null&&roleList.size() > 0){//是管理员
                // 2、查询当前公司下所有员工对应的岗位
                List<String> roleComList = companyService.getUserRoleManager(company);
                //3、查询员工所对应的岗位有几个是管理员
                int num = 0;
                for (String role: roleComList) {
                    if(roleList.get(0).getId().equals(role)) {
                        num++;
                        if(num>1){
                            break;
                        }
                    }
                }
                if( num > 1 ){  //多个管理员
                    companyService.delete(company,2);
                    Office office = officeService.get(companyinfo.getCompanyId());
                    if (StringUtils.isNotBlank(office.getGroupId())) {
                        LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
                        if (layGroup!=null && !layGroup.getCreateBy().getId().equals(companyinfo.getUserId())) {
                            layGroupService.deleteGroupUser(layGroup, companyinfo.getUserId());
                        }
                    }
                    addMessage(redirectAttributes, "删除企业信息成功");
                }else if( num == 1 ){
                    addMessage(redirectAttributes, "公司只有您一位管理员,您不能退出企业");
                    return "redirect:"+Global.getAdminPath()+"/sys/company/joinCompany?repage";
                }
            }else{//普通用户
                String data = companyService.delete(company,2);
                if(data==null||"".equals(data) || "Success".equals(data)){
                    Office office = officeService.get(companyinfo.getCompanyId());
                    if (StringUtils.isNotBlank(office.getGroupId())) {
                        LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
                        if (layGroup!=null && !layGroup.getCreateBy().getId().equals(companyinfo.getUserId())) {
                            layGroupService.deleteGroupUser(layGroup, companyinfo.getUserId());
                        }
                    }
                    addMessage(redirectAttributes, "删除企业信息成功");
                }else if("Invalid".equals(data)){
                    //无效数据的原因是用户表和用户公司关联表数据不统一
                    addMessage(redirectAttributes, "Invalid Data");
                }
            }*/
        }else {
            addMessage(redirectAttributes, "退出企业失败,参数异常");
        }
        if(companyId.equals(UserUtils.getSelectCompany().getId())) {
            return "redirect:" + Global.getAdminPath() + "/logout";
        }else {
            return "redirect:"+Global.getAdminPath()+"/sys/company/companyAddList";
        }
    }

    /**
     * 批量删除企业信息
     */
    @RequiresPermissions("sys:company:del")
    @RequestMapping(value = "deleteAll")
    public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
        String idArray[] =ids.split(",");
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for(String id : idArray){
            if("1".equals(companyService.get(id).getUSEABLE())){
                failureNum++;
                //addMessage(redirectAttributes, "删除企业失败，已审批通过，正在使用中");
            }else{
                companyService.delete(companyService.get(id),1);
                successNum++;
                //addMessage(redirectAttributes, "删除企业成功");
            }
        }
        if (failureNum>0){
            failureMsg.insert(0, "，删除"+failureNum+" 条企业失败。");
        }
        addMessage(redirectAttributes, "已成功删除"+successNum+" 条企业"+failureMsg);
        //addMessage(redirectAttributes, "删除企业信息成功");
        return "redirect:"+Global.getAdminPath()+"/sys/company/?repage";
    }

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

    /**
     * 导入Excel数据

     */
    @RequiresPermissions("sys:company: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<Company> list = ei.getDataList(Company.class);
            for (Company company : list){
                try{
                    companyService.save(company);
                    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()+"/sys/company/?repage";
    }

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

    /**
     * 企业信息列表页面
     */
    @RequiresPermissions(value={"sys:company:list"})
    @RequestMapping(value = {"useableCompany"})
    public String useableCompany(Company company, HttpServletRequest request, HttpServletResponse response, Model model) {
        company.setUSEABLE("1");
        company.setCreateBy(null);
        if (!UserUtils.getUser().isAdmin()) {
            boolean b = UserUtils.isManager();
            if (b) {
                company.setCompanyId(UserUtils.getSelectCompany().getId());
            }else {
                Page<Company> page = new Page<Company>();
                model.addAttribute("page", page);
                return "modules/sys/userJoinCompany";
            }
        }
        Page<Company> page = companyService.findPage(new Page<Company>(request, response), company);
        model.addAttribute("page", page);
        return "modules/sys/userJoinCompany";
    }

    /**
     * 加入公司
     * @param response
     * @return
     */
    @RequiresPermissions("sys:company:applyCompany")
    @RequestMapping(value = "applyCompany")
    public String joinCompany(String id, HttpServletResponse response, Model model) {
        Company company = companyService.get(id);
        Office office = officeService.get(company.getCompanyId());
        User user = UserUtils.get(office.getMaster());
        model.addAttribute("user", user);
        model.addAttribute("office", office);
        model.addAttribute("company", company);
        return "modules/sys/applyCompany";
    }

    /**
     * 申请加入公司
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:company:applyCompany")
    @RequestMapping(value = "saveApplyCompany")
    public String saveApplyCompany(String master,
                                   String remarks, String companyId, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectAttributes) {
        Map<String, Object> variables = Maps.newHashMap();
        Useroffice companyinfo = new Useroffice();
        String delFlag = "0";
        User user = UserUtils.get(master);
        String userId = user.getId();
        variables.put("auditUserId", userId==null?"1":userId);
        companyinfo.setUserId(UserUtils.getUser().getId());
        companyinfo.setCompanyId(companyId);
        List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
        if(companyinfoList!=null && companyinfoList.size()!=0){
            logger.error("加入公司流程失败：您已申请加入企业");
            addMessage(redirectAttributes, "您已申请加入企业,不能重复加入");
            return "redirect:"+Global.getAdminPath()+"/sys/company/userJoinCompany?repage";
        }
        companyinfo.setStatus("1");
        companyinfo.setDelFlag(delFlag);
        companyinfo.setRemarks(remarks);
        companyinfo.setMaster(master);
        companyinfoService.save(companyinfo, variables);
        addMessage(redirectAttributes, "加入企业成功");
        return "redirect:"+Global.getAdminPath()+"/sys/company/userJoinCompany?repage";
    }

    /**
     * 审核通过的企业信息列表页面
     */
    @RequiresPermissions(value={"sys:company:companyList"})
    @RequestMapping(value = {"joinCompany"})
    public String companyList(Useroffice useroffice, HttpServletRequest request, HttpServletResponse response, Model model) {
        useroffice.setCreateBy(UserUtils.getUser());
        if (!UserUtils.isManager()){
            useroffice.setUserId(UserUtils.getUser().getId());
        }
        if (!UserUtils.getUser().isAdmin()) {
            boolean b = UserUtils.isManager();
            if (b) {
                useroffice.setCompanyId(UserUtils.getSelectCompany().getId());
            }else {
                useroffice.setUserId(UserUtils.getUser().getId());
            }
        }
        useroffice.setDelFlag("0");
        Page<Useroffice> page = companyinfoService.find(new Page<Useroffice>(request, response), useroffice);
        List<Role> roles = UserUtils.getSelectRole();
        Boolean b = UserUtils.isManager();
        model.addAttribute("page", page);
        model.addAttribute("gly", b);
        model.addAttribute("companyinfo", useroffice);
        return "modules/sys/joinCompany";
    }

    /**
     * 待办任务列表页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions(value={"sys:company:companyOnList"})
    @RequestMapping(value = {"joinOnCompany"})
    public String companyOnList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
        act.setProcDefKey("joincompany");
        List<Act> list = actTaskService.todoList(act);
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        //List<Act> lists = new ArrayList<Act>();
        List<Useroffice> lists = new ArrayList<Useroffice>();
        for (Act a : list) {
            Useroffice companyinfo = companyinfoService.getByProcessInstanceId(a.getTask().getProcessInstanceId());
            if (companyinfo != null && companyinfo.getCompanyId().equals(companyId) && StringUtils.isNotBlank(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().equals("modifyApply")) {
                if (a.getVars().getMap().get("applyUserId")!=null){
                    a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                }
                companyinfo.setAct(a);
                if (StringUtils.isNotBlank(companyinfo.getMaster())){
                    companyinfo.setMasterName(UserUtils.getUser().getName());
                }
                if (StringUtils.isNotBlank(companyinfo.getId())){
                    companyinfo.setName(officeService.get(companyinfo.getCompanyId()).getName());
                }
                lists.add(companyinfo);
            }
        }
        model.addAttribute("list", lists);
        return "modules/sys/joinOnCompany";
    }

    /**
     * 审核企业信息
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "applyOnCompany")
    public String applyOnCompany(Act act,String id, HttpServletResponse response, Model model) {
        // 获取流程XML上的表单KEY
        String formKey = "/sys/company/applyOnCompanys";
        Useroffice useroffice = userofficeService.get(id);
        if (act != null && act.getProcInsId() != null){
            if(actTaskService.getProcIns(act.getProcInsId())!=null){
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            }else{
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }else {
            act = useroffice.getAct();
            if(actTaskService.getProcIns(act.getProcInsId())!=null){
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            }else{
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }

        return "redirect:" + ActUtils.getFormUrl(formKey, act);
    }

    /**
     * 审核企业信息
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("sys:company:applyOnCompany")
    @RequestMapping(value = "applyOnCompanys")
    public String applyCompanyForm(Useroffice companyinfo, HttpServletResponse response, Model model) {
        actTaskService.claim(companyinfo.getAct().getTaskId(), UserUtils.getUser().getId());
        String view = "applyOnCompany";
        Act act = companyinfo.getAct();
        // 查看审批申请单
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyinfo.getId())){//.getAct().getProcInsId())){
            // 环节编号
            String taskDefKey = companyinfo.getAct().getTaskDefKey();
            // 审核环节
            if ("apply_end".equals(taskDefKey)){
                view = "applyOnCompany";
            }
        }
        companyinfo = companyinfoService.getByProcessInstanceId(act.getProcInsId());
        Office office = officeService.get(companyinfo.getCompanyId());
        User user = UserUtils.get(UserUtils.getUser().getId());
        model.addAttribute("user", user);
        model.addAttribute("office", office);
        companyinfo.setAct(act);

        User master =  UserUtils.getUser();
        companyinfo.setMasterName(master.getName());

        model.addAttribute("companyinfo", companyinfo);
        String companyId = UserUtils.getSelectCompany().getId();
        Role roles = new Role();
        roles.setCompany(new Office(companyId));
        List<Role> roleList = UserUtils.getRoleListByCompany(roles);
        Useroffice com = companyinfoService.get(companyinfo.getId());
        com.setMaster(UserUtils.getUser().getId());
        companyinfoService.save(com);
        return "modules/sys/" + view;
    }

    /**
     * 保存审核加入的企业
     * @param model
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "saveApplyOnCompany")
    public String saveApplyOnCompany(Useroffice companyinfo, Model model, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        String joinUserId = companyinfo.getUserId();
        String companyId = companyinfo.getCompanyId();
        String roleIds = companyinfo.getUser().getRoleIds();
        String officeId = companyinfo.getUser().getOffice().getId();
        //remarks"丢失"的问题
        Useroffice uo = companyinfoService.get(companyinfo.getId());
        if(uo!=null && StringUtils.isNotBlank(uo.getRemarks())){
            companyinfo.setRemarks(uo.getRemarks());
        }
        companyinfoService.auditSave(companyinfo,joinUserId,companyId,roleIds,officeId);
        addMessage(redirectAttributes, "审核企业员工成功");
        if ("home".equals(companyinfo.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/sys/company/joinCompany?repage";
        }
    }

    /**
     * 已办任务
     * @param act
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions(value = {"sys:company:joinOnShenHeCompany"})
    @RequestMapping(value = {"joinOnShenHeCompany"})
    public String joinYiShenHeCompany (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
        act.setProcDefKey("joincompany");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
        List<Act> list = page.getList();
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<Useroffice> lists = new ArrayList<Useroffice>();
        for (Act a : list) {
            Useroffice companyinfo = companyinfoService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
            if (companyinfo != null && companyinfo.getCompanyId().equals(companyId)) {
                if (a.getVars().getMap().get("applyUserId")!=null){
                    a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString())==null?"":UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                }
                if (StringUtils.isNotBlank(companyinfo.getMaster())){
                    companyinfo.setMasterName(UserUtils.get(companyinfo.getMaster()).getName());
                }
                if (StringUtils.isNotBlank(companyinfo.getId())){
                    companyinfo.setName(officeService.get(companyinfo.getCompanyId()).getName());
                }
                companyinfo.setAct(a);
                if (companyinfo.getCreateDate()!=null){
                    companyinfo.setTime(sdf.format(companyinfo.getCreateDate()));
                }

                lists.add(companyinfo);
            }
        }
        model.addAttribute("list", lists);

        return "modules/sys/joinOnShenHeCompany";
    }

    /**
     * 查看企业信息
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions(value={"sys:company:companyinfoView"},logical=Logical.OR)
    @RequestMapping(value = "companyinfoView")
    public String view(@RequestParam(value = "readAttr",required = false)String readAttr ,  String id,  Model model) {
        Useroffice companyinfo =  companyinfoService.get(id);
        Office office = officeService.get(companyinfo.getCompanyId());
        User user = systemService.getUser(companyinfo.getUserId());
        if(StringUtils.isNotBlank(companyinfo.getMaster())){
            User master =  UserUtils.get(companyinfo.getMaster());
            companyinfo.setMasterName(master.getName());
        }

        model.addAttribute("companyinfo", companyinfo);
        model.addAttribute("office", office);
        model.addAttribute("user", user);
        model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
        return "modules/sys/companyinfoView";
    }
    /**
     * 验证手机号是否被注册
     * @param mobile
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "registerUser",method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
    @ResponseBody
    public String registerUser(String mobile,String comId, RedirectAttributes redirectAttributes) {
        //验证手机号是否已经注册
        String  msg =   companyService.findUniqueBymobile(mobile,comId);
        return msg;
    }

    /**
     * 验证公司名称是否可以申请（数据库中不存在）
     */
    @ResponseBody
    @RequestMapping(value = "validateCompany")
    public boolean validateCompany(String oldName, String name) {
        Office office  = new Office();
        office.setName(name);
        office.setType("1");
        List<Office> list =  officeDao.findListByCompanyNamee(office);
       /* if(list.size()==0){
            return true;
        }else{
            return false;
        }*/
        if (name!=null && name.equals(oldName)) {
            return true;
        } else if (name!=null && list.size()==0) {
            return true;
        }
        return false;
    }

    /**
     * 验证公司名称是否可以申请（数据库中不存在）
     */
    @ResponseBody
    @RequestMapping(value = "checkNumber")
    public boolean checkNumber(String number) {
        boolean msg =   companyService.checkNumber(number);
        return msg;
    }
}