/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</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.beanvalidator.BeanValidators;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.json.ComNameJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.*;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.SystemConfig;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemConfigService;
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.sysimportinfo.entity.SysImportInfo;
import com.jeeplus.modules.sysimportinfo.service.SysImportInfoService;
import com.jeeplus.modules.wexinpackage.access.util.user.UserUrl;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import groovy.util.IFileNameFinder;
import io.swagger.client.model.NewPassword;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
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 redis.clients.jedis.Jedis;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 * @author jeeplus
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserService userService;

    @Autowired
    private SystemService systemService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SysImportInfoService sysImportInfoService;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;

    @ModelAttribute
    public User get(@RequestParam(required=false) String id) {
        if (StringUtils.isNotBlank(id)){
            return UserUtils.getByUserId(id);
        }else{
            return new User();
        }
    }

    @RequiresPermissions("sys:user:index")
    @RequestMapping(value = {"list", ""})
    public String index(User user, HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes attr) {
        if (user.getOffice()!=null && StringUtils.isNotBlank(user.getOffice().getId()) && StringUtils.isBlank(user.getOffice().getName())){
            Office office = officeService.get(user.getOffice().getId());
            user.setOffice(office);
        }
        user.setCompany(UserUtils.getSelectCompany());
        Page<User> page = systemService.findUserByCompany(new Page<User>(request, response), user);
        model.addAttribute("manager", UserUtils.isManager());
        model.addAttribute("page", page);
        return "modules/sys/userList";
    }

    /*@RequiresPermissions("sys:user:index")
    @RequestMapping(value = {"list", ""})
    public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes attr) {
        if (user.getOffice()!=null && StringUtils.isNotBlank(user.getOffice().getId()) && StringUtils.isBlank(user.getOffice().getName())){
            Office office = officeService.get(user.getOffice().getId());
            user.setOffice(office);
        }
        if (StringUtils.isNotBlank(officeId)){
            logger.info("---------------:"+officeId);
            user.setOffice(new Office(officeId));
        }
        Page<User> page = systemService.findUser(new Page<User>(request, response), user);
        officeId = "";
        model.addAttribute("page", page);
        return "modules/sys/userList";
    }*/


    @RequiresPermissions(value={"sys:user:view","sys:user:add","sys:user:edit"},logical=Logical.OR)
    @RequestMapping(value = "form")
    public String form(User user, Model model,HttpServletRequest request) {
/*		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}*/
//        if(user.getId()!=null){
//            User  tempUser=userDao.getUserById(user.getId());
//            tempUser.setOffice(user.getOffice());
//            tempUser.setRole(user.getRole());
//            tempUser.setCompany(user.getCompany());
//            model.addAttribute("user", tempUser);
//        }
//        else{
            List<Role> roleList = UserUtils.getSelectRole();
            user.setRoleIds(Collections3.extractToString(roleList, "id", ","));
            user.setRoleNames(Collections3.extractToString(roleList, "name", ","));
            if(!"1".equals(UserUtils.getSelectCompany().getId())){
                user.setCompany(UserUtils.getSelectCompany());
            }
            if(user.getOffice()!=null && StringUtils.isNotBlank(user.getOffice().getType()) && !"2".equals(user.getOffice().getType())){
                user.setOffice(new Office());
            }

            model.addAttribute("user", user);
//        }


        /*if (UserUtils.getUser().isAdmin()){
            model.addAttribute("allRoles", systemService.findAllRoleByCompany());
        }else {
            String companyId = UserUtils.getSelectCompany().getId();
            Role roles = new Role();
            roles.setCompany(new Office(companyId));
            List<Role> roleList = UserUtils.getRoleListByCompany(roles);
            model.addAttribute("allRoles", roleList);
        }*/
        if("view".equals(request.getParameter("dialog"))){
            String userId = user.getId();
            Role role = new Role();
            Office office = UserUtils.getSelectOffice();
            role.setBranchCompany(new Office(office.getBranchOffice()));
            role.setUserId(userId);
            role.setCompany(UserUtils.getSelectCompany());
            List<Role> roles = systemService.findListRoleByUser(role);
            WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
            workStaffBasicInfo.setUserId(userId);
            workStaffBasicInfo.setCompany(role.getCompany());
            List<WorkStaffBasicInfo> workStaffBasicInfos = workStaffBasicInfoService.getByCompanyInfo(workStaffBasicInfo);
            model.addAttribute("userId", userId);
            model.addAttribute("user", user);
            model.addAttribute("list", roles);
            model.addAttribute("workStaffBasicInfo", workStaffBasicInfos==null||workStaffBasicInfos.size()==0?new WorkStaffBasicInfo():workStaffBasicInfos.get(0));
            model.addAttribute("roleStatus", false);
            return "modules/sys/userFormView";
        }
        return "modules/sys/userForm";
    }

    @RequiresPermissions(value={"sys:user:add","sys:user:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(User user, HttpServletRequest request, Model model,MultipartFile this_upload_files, RedirectAttributes redirectAttributes) throws IOException{
//        String companyId = request.getParameter("company.id");
//        String officeId = request.getParameter("office.id");
        if(Global.isDemoMode()){
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
        if (!beanValidator(model, user)){
            addMessage(redirectAttributes, "数据验证失败");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
            addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        boolean b = userService.save(user, request,this_upload_files);
        if(b){
            addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
        }else{
            addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'失败");
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    @RequiresPermissions("sys:user:del")
    @RequestMapping(value = "delete")
    public String delete(User user, RedirectAttributes redirectAttributes) {
        if(Global.isDemoMode()){
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        if (UserUtils.getUser().getId().equals(user.getId())){
            addMessage(redirectAttributes, "移除用户失败, 不允许移除当前用户");
        }if (UserUtils.getUser().getComId().equals("1")){
            addMessage(redirectAttributes, "移除用户失败, 无操作权限");
        }else if (User.isAdmin(user.getId())){
            addMessage(redirectAttributes, "移除用户失败, 不允许移除超级管理员用户");
        }else{
//            UserUrl.deleteUser("",user.getLoginName());
            Office company = UserUtils.getSelectCompany();
            WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
            workStaffBasicInfo.setCompany(company);
            workStaffBasicInfo.setUserId(user.getId());
            Integer count = workStaffBasicInfoService.getByCompany(workStaffBasicInfo);
            if (count == 0){
                String str = userService.deleteUserByCompany(user,company,"");
                addMessage(redirectAttributes, str);
            }else{
                addMessage(redirectAttributes, "移除用户失败,不能移除该用户");
            }
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 批量删除用户
     */
    @RequiresPermissions("sys:user:del")
    @RequestMapping(value = "deleteAll")
    public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
        String idArray[] =ids.split(",");
        for(String id : idArray){
            User user = systemService.getUser(id);
            if(Global.isDemoMode()){
                addMessage(redirectAttributes, "演示模式，不允许操作！");
                return "redirect:" + adminPath + "/sys/user/list?repage";
            }
            if (UserUtils.getUser().getId().equals(user.getId())){
                addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
            }else if (User.isAdmin(user.getId())){
                addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
            }else{
                systemService.deleteUser(user);
                addMessage(redirectAttributes, "删除用户成功");
            }
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导出用户数据
     * @param user
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<User> page = systemService.findUser2(new Page<User>(request, response, -1), user);
            new ExportExcel(true,"用户数据", User.class,1).setDataList(true,page.getList()).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导入用户数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(HttpServletRequest request,MultipartFile file, RedirectAttributes redirectAttributes) {
        if(Global.isDemoMode()){
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/index?repage";
        }
        if (UserUtils.getUser().isAdmin()){
            addMessage(redirectAttributes, "误操作权限，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/index?repage";
        }
        try {
            String date = DateUtils.getDate("yyyyMMddHHmmss");
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            List<User> errlist = new ArrayList<>();
            for (User user : list){
                try{
                    if ("true".equals(checkLoginName("", user.getLoginName()))){
                        String validators = beanValidatorImport(user);
                        // 密码MD5加密
                        String password = EncrypeUtil.encrypeString("123456", "UTF-8");
                        user.setPasswordRemake(password);
                        user.setPassword(SystemService.entryptPassword(password));
                        BeanValidators.validateWithException(validator, user);
                        if (StringUtils.isNotBlank(validators)){
                            failureMsg.append("<br/>"+validators+"!");
                            failureNum++;
                            user = toWorkEntity(user,date,validators);
                            errlist.add(user);
                        }else {
                            user.setCompany(UserUtils.getSelectCompany());
                            user.setOffice(UserUtils.getSelectOffice());
                            userService.save(user,request);
                            successNum++;
                        }
                    }else{
                        failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");
                        //failureNum++;
                    }
                }catch(ConstraintViolationException ex){
                    failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList){
                        failureMsg.append(message+"; ");
                        failureNum++;
                    }
                }catch (Exception ex) {
                    logger.info("Exception ex"+ex);
                    user = toWorkEntity(user,date,ex+"!");
                    failureNum++;
                    errlist.add(user);
                    failureMsg.append(ex+"!");
                }
            }
            SysImportInfo sysImportInfo = new SysImportInfo();
            sysImportInfo.setCompanyId(UserUtils.getSelectCompany().getId());
            sysImportInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            sysImportInfo.setModular("3");
            if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 个错误信息记录。");
                ExportExcel exportExcel= new ExportExcel(false,"用户信息数据", User.class, 1).setDataList(errlist);
                OSSClientUtil ossUtil = new OSSClientUtil();

                String fileName=date+"用户信息错误导入日志.xlsx";
                String fileDir = "importInfo/userImport/";
                fileDir = fileDir+System.nanoTime()+"/";
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    exportExcel.write(os);
                    byte[] content = os.toByteArray();
                    InputStream inputStream = new ByteArrayInputStream(content);
                    ossUtil.uploadFile2OSS(inputStream,fileDir, fileName);
                }catch (IOException e){
                    e.printStackTrace();
                }catch (Exception e1){
                    e1.printStackTrace();
                    System.out.println("用户信息错误导入日志文件上传失败！");
                }

                String name = Global.getAliyunUrl()+"/"+fileDir+fileName;
                logger.info("name:"+name);
                sysImportInfo.setUrl(name);
                sysImportInfo.setFileName(fileName);
                sysImportInfo.setErrCount(failureNum+"");
                sysImportInfo.setIsTrue("0");
            }else {
                sysImportInfo.setIsTrue("1");
                sysImportInfo.setErrCount("0");
            }
			/*if(errList.size() > 0){
				failureNum = errList.size() + failureNum;
				failureMsg.insert(0, "，失败 "+failureNum+" 条客户管理记录");
			}*/
            String msg = "已成功导入 "+successNum+" 条用户"+failureMsg;
            String info = "已成功导入 "+successNum+" 条客户信息记录，失败 "+failureNum+" 个错误信息记录。";
            sysImportInfo.setErrInfo(info);
            sysImportInfoService.save(sysImportInfo);
            addMessage(redirectAttributes, msg);
           /* if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);*/
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/index?repage";
    }

    /**
     * 下载导入用户数据模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据导入模板.xlsx";
            List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser());
            new ExportExcel(true,"用户数据", User.class, 2).setDataList(true,list).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 查看导入客户管理数据信息+
     */
    //@RequiresPermissions("importInfo:importInfo:importInfoErr")
    @RequestMapping(value = "importInfoErr")
    public String importInfoErr(SysImportInfo sysImportInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
        SysImportInfo importInfo = new SysImportInfo();
        importInfo.setModular("3");
        Page<SysImportInfo> page = sysImportInfoService.findPage(new Page<SysImportInfo>(request, response), importInfo);
        model.addAttribute("page", page);
        model.addAttribute("modular", "3");
        return "modules/sysimportinfo/sysimportinfoList";
    }

    /**
     * 验证登录名是否有效
     * @param oldLoginName
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequiresPermissions(value={"sys:user:add","sys:user:edit"},logical=Logical.OR)
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName !=null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }




    /**
     * 验证工号是否重复
     * @param oldNo
     * @param no
     * @return
     */
    @ResponseBody
    @RequiresPermissions(value={"sys:user:add","sys:user:edit"},logical=Logical.OR)
    @RequestMapping(value = "checkNo")
    public String checkNo(String no,String oldNo) {
        if (no !=null && no.equals(oldNo)) {
            return "true";
        } else if (no !=null) {
            User user = systemService.findUserByNo(no);
            if(user==null)
            return "true";
        }
        return "false";
    }

    /**
     * 用户信息显示
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "info")
    public String info(HttpServletResponse response, Model model) {
        User currentUser = UserUtils.getUser();
        model.addAttribute("user", currentUser);
        model.addAttribute("Global", new Global());
        WorkStaffBasicInfo workStaffBasicInfo=new WorkStaffBasicInfo();
        workStaffBasicInfo.setAchiveId(UserUtils.getBasicInfo()==null?"":UserUtils.getBasicInfo().getId());
        workStaffBasicInfo = workStaffBasicInfoService.getAchive(workStaffBasicInfo);
        if (workStaffBasicInfo!=null) {
            workStaffBasicInfo.setAchiveId(workStaffBasicInfo.getId());
            if (StringUtils.isNotBlank(workStaffBasicInfo.getId())) {
                workStaffBasicInfoService.queryDetails(workStaffBasicInfo);
            }
        }
        model.addAttribute("workStaffBasicInfo", workStaffBasicInfo);
        return "modules/sys/userInfo";
    }

    /**
     * 用户信息显示编辑保存
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "infoEdit")
    public String infoEdit(User user, boolean __ajax, HttpServletResponse response, Model model,HttpServletRequest request) {
        User currentUser = UserUtils.getUser();
        WorkStaffBasicInfo workStaffBasicInfo =  new WorkStaffBasicInfo();
        workStaffBasicInfo.setUserId(currentUser.getId());

        if (StringUtils.isNotBlank(user.getName())){
            if(Global.isDemoMode()){
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/userInfo";
            }

            String name = user.getName();
            if(!name.equals(currentUser.getName())){
                currentUser.setName(user.getName());
                workStaffBasicInfo.setName(user.getName());

                long time = System.currentTimeMillis();
                String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
                FileUtils.createDirectory(realPathPhoto);
                String picNamePhoto =time + ".png"; // encoderImgId此处图片名
                String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
                WordToPic.TextToPic(name.substring(name.length()-2>0?name.length()-2:0,name.length()),200, 200, 55, filePathPhoto);
                String temp = request.getContextPath() + Global.USERFILES_BASE_URL + time + "/img/"+picNamePhoto;
                if (StringUtils.isNotBlank(currentUser.getDefaultPhoto()) && currentUser.getDefaultPhoto().equals("0")){
                    InputStream inputStream = null;
                    HttpURLConnection httpURLConnection;
                    try {
                        URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ temp);
                        httpURLConnection = (HttpURLConnection) url.openConnection();
                        // 设置网络连接超时时间
                        httpURLConnection.setConnectTimeout(3000);
                        // 设置应用程序要从网络连接读取数据
                        httpURLConnection.setDoInput(true);

                        httpURLConnection.setRequestMethod("GET");
                        int responseCode = httpURLConnection.getResponseCode();
                        if (responseCode == 200) {
                            // 从服务器返回一个输入流
                            inputStream = httpURLConnection.getInputStream();

                        }
                        String path = new StringBuilder("/headImg/")
                                .append(currentUser.getName()+System.currentTimeMillis()).append(".png").toString();
                        BOSClientUtil bosClientUtil = new BOSClientUtil();
                        String uploadPath = bosClientUtil.upload(path, inputStream);
                        currentUser.setPhoto(uploadPath);
                        FileUtils.delFile(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if(inputStream!=null){
                            try {
                                inputStream.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            if (StringUtils.isNotBlank(user.getEmail())) {
                currentUser.setEmail(user.getEmail());
                workStaffBasicInfo.setEmail(user.getEmail());
            }

            if (StringUtils.isNotBlank(user.getMobile())) {
                currentUser.setMobile(user.getMobile());
                workStaffBasicInfo.setMobile(user.getMobile());
            }
            if (StringUtils.isNotBlank(user.getRemarks())) {
                currentUser.setRemarks(user.getRemarks());
                workStaffBasicInfo.setRemarks(user.getRemarks());
            }

            systemService.updateUserInfo(currentUser);
            //同步sys_user和work_staff_basic_info和work_staff_achives
            workStaffBasicInfoService.updateWorkStaffBasicInfo(workStaffBasicInfo);
            if(__ajax){//手机访问
                AjaxJson j = new AjaxJson();
                j.setSuccess(true);
                j.setMsg("修改个人资料成功!");
                return renderString(response, j);
            }
            model.addAttribute("user", currentUser);
            model.addAttribute("Global", new Global());
            model.addAttribute("message", "保存用户信息成功");
            return "redirect:"+adminPath+"/sys/user/info";
        }
        model.addAttribute("user", currentUser);
        model.addAttribute("Global", new Global());
        return "modules/sys/userInfoEdit";
}

    @ResponseBody
    @RequestMapping(value = "getComName")
    public ComNameJson getComName(String userName, HttpServletResponse response, Model model) {
        StringBuffer sb =new StringBuffer();
        ComNameJson j = new ComNameJson();
        User user = userDao.getByLoginName(new User(null,userName));
        if(user == null){
            j.setMsg("用户名不存在！");
            j.setSuccess(false);
            return j;
        }
        if(user.isAdmin()){
            j.setMsg("总公司");
            j.setSuccess(true);
            return j;
        }
        Role role1 = new Role();
        role1.setUser(user);
        List<Role> roleList=systemService.findRole(role1);

        if(roleList.get(0).getId().equals("1")){
            j.setMsg("新用户");
            j.setSuccess(true);
            return j;
        }
        List<Office> companyList = UserUtils.getAllCompany(user);
        for (Office office : companyList) {
            if (!office.getId().equals("1") && !"2".equals(office.getUseable())){
                if(sb.length()==0){
                    sb.append(office.getName());
                }else{
                    sb.append(","+office.getName());
                }
            }
        }

        //获取默认公司名称
        String comId = user.getComId();
        if(comId!=null&&!"1".equals(comId)){
            Office office = officeService.get(comId);
            String comName = office.getName();
            j.setComName(comName.toString());
        }else{
            j.setComName(null);
        }

        j.setMsg(sb.toString());
        j.setSuccess(true);
        return j;

    }

    @ResponseBody
    @RequestMapping(value = "getAllCompany")
    public AjaxJson getAllCompany(String userName, HttpServletResponse response, Model model) {
        StringBuffer sb =new StringBuffer();
        AjaxJson j = new AjaxJson();
        User user = userDao.getByLoginName(new User(null,userName));
        if(user == null){
            j.setMsg("用户名不存在！");
            j.setSuccess(false);
            return j;
        }/*else{
            pwd = SystemService.encrypeString(pwd);
            if(!SystemService.validatePassword(pwd,user.getPassword())){
                j.setMsg("密码不正确！");
                j.setSuccess(false);
                return j;
            }
        }*/
        if(user.isAdmin()){
            j.setMsg("总公司");
            j.setSuccess(true);
            return j;
        }
        Role role1 = new Role();
        role1.setUser(user);
        List<Role> roleList=systemService.findRole(role1);

        if(roleList.get(0).getId().equals("1")){
            j.setMsg("新用户");
            j.setSuccess(true);
            return j;
        }
        List<Office> companyList = UserUtils.getAllCompany(user);
        for (Office office : companyList) {
            if (!office.getId().equals("1")){
                if(sb.length()==0){
                    sb.append(office.getName());
                }else{
                    sb.append(","+office.getName());
                }
            }
        }

        j.setMsg(sb.toString());
        j.setSuccess(true);
        return j;

    }

    /**
     * 用户头像显示编辑保存
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "imageEdit")
    public String imageEdit(User user, boolean __ajax, HttpServletResponse response, Model model) {
        User currentUser = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getName())){
            if(Global.isDemoMode()){
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/userInfo";
            }
            if(user.getPhoto() !=null )
                currentUser.setPhoto(user.getPhoto());
            systemService.updateUserInfo(currentUser);
            if(__ajax){//手机访问
                AjaxJson j = new AjaxJson();
                j.setSuccess(true);
                j.setMsg("修改个人头像成功!");
                return renderString(response, j);
            }
            model.addAttribute("message", "保存用户信息成功");
            return "modules/sys/userInfo";
        }
        model.addAttribute("user", currentUser);
        model.addAttribute("Global", new Global());
        return "modules/sys/userImageEdit";
    }





    /**
     * 用户头像显示编辑保存
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "imageUpload")
    public String imageUpload( HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws IllegalStateException, IOException {
        User currentUser = UserUtils.getUser();
        if(file != null && file.getSize()>0){
            String path = new StringBuilder("/headImg/")
                    .append(currentUser.getName()+System.currentTimeMillis()).append(".png").toString();
            InputStream inputStream = file.getInputStream();
            BOSClientUtil bosClientUtil = new BOSClientUtil();
            String url = bosClientUtil.upload(path, inputStream);
            currentUser.setPhoto(url);
            currentUser.setDefaultPhoto("1");
            systemService.updateUserInfo(currentUser);
        }
        return "modules/sys/userImageEdit";
    }

    /**
     * 返回用户信息
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "infoData")
    public AjaxJson infoData() {
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        j.setErrorCode("-1");
        j.setMsg("获取个人信息成功!");
        j.put("data", UserUtils.getUser());
        return j;
    }



    /**
     * 修改个人用户密码
     * @param oldPassword
     * @param newPassword
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(String oldPassword, String newPassword, Model model,HttpServletRequest request) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
            if(Global.isDemoMode()){
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/userInfo";
            }
            oldPassword = SystemService.encrypeString(oldPassword);
            if (SystemService.validatePassword(oldPassword, user.getPassword())){
                newPassword = SystemService.encrypeString(newPassword);

                NewPassword psd = new NewPassword().newpassword(newPassword);
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                model.addAttribute("message", "修改密码成功");
            }else{
                model.addAttribute("message", "修改密码失败，旧密码错误");
            }
            if("home".equals(request.getParameter("home"))){
//                model.addAttribute("message", "修改密码成功,请重新登录");
//                SecurityUtils.getSubject().logout();

                Subject subject = SecurityUtils.getSubject();
                SystemAuthorizingRealm.Principal principal = (SystemAuthorizingRealm.Principal) subject.getPrincipal();
                PrincipalCollection principalCollection = subject.getPrincipals();
                principal.setFirstFlag(false);
                String realmName = principalCollection.getRealmNames().iterator().next();
                PrincipalCollection newPrincipalCollection =
                        new SimplePrincipalCollection(principal, realmName);
                subject.runAs(newPrincipalCollection);
                return  "redirect:/a/home";
            }
            return "modules/sys/userInfo";
        }
        user.setHome(request.getParameter("home"));
        model.addAttribute("user", user);
        return "modules/sys/userModifyPwd";
    }
    /**
     * 更换手机号
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "modifyMobo")
    public String updateMobile(Model model,String mobile,String password,String randomCode,HttpServletRequest request) {
        Jedis jedis = null;
        User user = UserUtils.getUser();
        try {
            jedis = JedisUtils.getResource();
            if (StringUtils.isNotBlank(password) && StringUtils.isNotBlank(mobile)) {
                if (randomCode.equals(jedis.get(mobile))){
                    user.setLoginName(mobile);
                    user.setMobile(mobile);
                    systemService.updateUserInfo(user);
                    model.addAttribute("message", "更换手机号成功");
                    model.addAttribute("user", user);
                }else {
                    model.addAttribute("user", user);
                    model.addAttribute("message", "修改失败，验证码错误");
                }
                return "modules/sys/userInfo";
            }
            model.addAttribute("user", user);
            return "modules/sys/userModifyMobo";
        } catch (Exception e) {
            //logger.error("getActiveSessions", e);
            //释放redis对象
            JedisUtils.returnBrokenResource(jedis);
            e.printStackTrace();
            return "modules/sys/userInfo";
        } finally {
            //返还到连接池
            if (jedis != null) {
                JedisUtils.returnResource(jedis);
            }
        }
    }
    /*用户注销*/
    @RequestMapping(value = "userDelete")
    public String userDelete(Model model) {
        User user = UserUtils.getUser();
        user.setLoginFlag("0");
        user.preUpdate();
        userDao.updateLoginFlag(user);
        if (UserUtils.getUser().getId().equals(user.getId())){
            UserUtils.clearCache();
            systemService.removeSession(UserUtils.getUser());
        }else {
            UserUtils.clearCache(UserUtils.get(user.getId()));
            systemService.removeSession(user);
        }
        model.addAttribute("message", "注销成功");
        return "modules/sys/userInfo";
    }
    /**
     * 保存签名
     */
    @ResponseBody
    @RequestMapping(value = "saveSign")
    public AjaxJson saveSign(User user, boolean __ajax, HttpServletResponse response, Model model) throws Exception{
        AjaxJson j = new AjaxJson();
        User currentUser = UserUtils.getUser();
        currentUser.setSign(user.getSign());
        systemService.updateUserInfo(currentUser);
        j.setMsg("设置签名成功");
        return j;
    }
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required=false) String officeId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = systemService.findUserByOfficeId(officeId);
        for (int i=0; i<list.size(); i++){
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_"+e.getId());
            map.put("pId", officeId);
            String name = StringUtils.replace(e.getName(), " ", "");
            name = StringEscapeUtils.unescapeHtml4(name);
            map.put("name", name);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * web端ajax验证用户名是否可用
     * @param loginName
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validateLoginName")
    public boolean validateLoginName(String loginName, HttpServletResponse response) {

        User user =  userDao.findUniqueByProperty("login_name", loginName);
        if(user == null){
            return true;
        }else{
            return false;
        }

    }

    /**
     * web端ajax验证手机号是否可以注册（数据库中不存在）
     */
    @ResponseBody
    @RequestMapping(value = "validateMobile")
    public boolean validateMobile(String mobile, HttpServletResponse response, Model model) {
        User user =  userDao.findUniqueByProperty("mobile", mobile);
        if(user == null){
            return true;
        }else{
            return false;
        }
    }

    /**
     * web端ajax验证手机号是否已经注册（数据库中已存在）
     */
    @ResponseBody
    @RequestMapping(value = "validateMobileExist")
    public boolean validateMobileExist(String mobile, HttpServletResponse response, Model model) {
        User user =  userDao.findUniqueByProperty("mobile", mobile);
        if(user != null){
            return true;
        }else{
            return false;
        }
    }

    @RequestMapping(value = "resetPassword")
    public String  resetPassword(String mobile, HttpServletResponse response, Model model,String password,RedirectAttributes redirectAttributes) {
        SystemConfig config = systemConfigService.get("1");//获取短信配置的用户名和密码
        AjaxJson j = new AjaxJson();
        User user = userDao.findUniqueByProperty("mobile", mobile);
        try {
            // 密码MD5加密并修改密码
            String newpassword = EncrypeUtil.encrypeString(password, "UTF-8");
            System.out.println("newPassword：" + newpassword);
            user.setPasswordRemake(newpassword);
            user.setPassword(SystemService.entryptPassword(newpassword));

            newpassword = SystemService.encrypeString(password);
            systemService.updatePasswordById(user.getId(), user.getLoginName(), newpassword);
            addMessage(redirectAttributes, "修改用户'" + user.getLoginName() + "'成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:" + adminPath + "/login";
    }

//	@InitBinder
//	public void initBinder(WebDataBinder b) {
//		b.registerCustomEditor(List.class, "roleList", new PropertyEditorSupport(){
//			@Autowired
//			private SystemService systemService;
//			@Override
//			public void setAsText(String text) throws IllegalArgumentException {
//				String[] ids = StringUtils.split(text, ",");
//				List<Role> roles = new ArrayList<Role>();
//				for (String id : ids) {
//					Role role = systemService.getRole(Long.valueOf(id));
//					roles.add(role);
//				}
//				setValue(roles);
//			}
//			@Override
//			public String getAsText() {
//				return Collections3.extractToString((List) getValue(), "id", ",");
//			}
//		});
//	}

    @ResponseBody
    @RequestMapping(value = "queryRole")
    public HashMap<Object,Object> queryRole(@RequestParam(required=false) String officeId) {
        List list = userService.queryRole(officeId);
        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("list",list);
        return map;
    }

    /**
     * 同步WorkClientInfo
     * @return
     */
    public User toWorkEntity(User user, String date , String errInfo){
        user.setNowDate(date);
        user.setUserName(UserUtils.getUser().getName());
        user.setErrInfo(errInfo);
        return user;
    }

    @ResponseBody
    @RequestMapping(value = "formulaInfo")
    public AjaxJson strInfo(@RequestParam(required=false) String strz) throws UnsupportedEncodingException {
        String str = URLDecoder.decode(strz, "UTF-8");//编码
        AjaxJson map = new AjaxJson();
        ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
        //String str3 = "if(1==2){2*3-45/5+9+9%5};\nif(2==2){2*3-45/5+9+9%5};\nif(3>=2){2*3-45/5+9+9%5};";
        String strss = "";
        try {
            String strs1 = str;
            FormulaStatusEnum[] values = FormulaStatusEnum.values();
            for (FormulaStatusEnum value:values){
                if (str.contains(value.getDesc())){
                    str = str.replaceAll(value.getDesc(),value.getValue());
                    strs1 = strs1.replaceAll(value.getDesc(),value.getDesc()+"["+value.getValue()+"]");
                }
            }
            FormulaStrEnum[] valuestr = FormulaStrEnum.values();
            for (FormulaStrEnum value:valuestr){
                if (str.contains(value.getDesc())){
                    str = str.replaceAll(value.getDesc(),value.getValue());
                    strs1 = strs1.replaceAll(value.getDesc(),value.getDesc()+"["+value.getValue()+"]");
                }
            }
            String[] strarr = str.split("if");
            String[] strarrs = strs1.split("if");
            for (int i=0;i<strarr.length;i++){
                String strs = strarr[i];
                String strsif = strarrs[i];
                String strInfo = strs;
                if (StringUtils.isNotBlank(strs)){
                    String strIf = strs.split("\\(")[1].split("\\)")[0];
                    String strsIfs = strsif.split("\\(")[1].split("\\)")[0];
                    if (strIf.contains("&&") && !strIf.contains("||")){
                        String[] arr = strIf.split("&&");
                        for (String s:arr){
                            if (strIf.contains("==")) {
                                String str1 = s.split("==")[0];
                                String str2 = s.split("==")[1];
                                if (str1.equals(str2)) {
                                    strInfo = strInfo.replace(strIf, "1==1");
                                } else {
                                    strInfo = strInfo.replace(strIf, "1>1");
                                    break;
                                }
                            }else if (strIf.contains("包含")) {
                                String str1 = s.split("包含")[0];
                                String str2 = s.split("包含")[1];
                                if (str1.contains(str2)) {
                                    strInfo = strInfo.replace(strIf, "1==1");
                                } else {
                                    strInfo = strInfo.replace(strIf, "1>1");
                                    break;
                                }
                            }
                        }
                    }else if (strIf.contains("||") && !strIf.contains("&&")){
                        String[] arr = strIf.split("\\|\\|");
                        System.out.println("arr:"+arr.length);
                        for (String s:arr){
                            if (s.contains("==")) {
                                String str1 = s.split("==")[0];
                                String str2 = s.split("==")[1];
                                if (str1.equals(str2)) {
                                    strInfo = strInfo.replace(strIf, "1==1");
                                    break;
                                } else {
                                    strInfo = strInfo.replace(strIf, "1>1");
                                }
                            }else if (strIf.contains("包含")) {
                                String str1 = s.split("包含")[0];
                                String str2 = s.split("包含")[1];
                                if (str1.contains(str2)) {
                                    strInfo = strInfo.replace(strIf, "1==1");
                                    break;
                                } else {
                                    strInfo = strInfo.replace(strIf, "1>1");
                                }
                            }
                        }
                    }else if (strIf.contains("&&") && strIf.contains("||")){
                        String[] arr = strIf.split("&&");
                        int count = 0;
                        for (String s:arr) {
                            if (s.contains("||")) {
                                String[] arr2 = s.split("\\|\\|");
                                System.out.println("arr:"+arr.length);
                                for (String s2:arr2){
                                    if (s2.contains("==")) {
                                        String str1 = s2.split("==")[0];
                                        String str2 = s2.split("==")[1];
                                        if (str1.equals(str2)) {
                                            count++;
                                            break;
                                        }
                                    }else if (s2.contains("包含")) {
                                        String str1 = s2.split("包含")[0];
                                        String str2 = s2.split("包含")[1];
                                        if (str1.contains(str2)) {
                                            count++;
                                            break;
                                        }
                                    }else {
                                        if (se.eval(s2)!=null){
                                            if (Boolean.parseBoolean(se.eval(s).toString())){
                                                count++;
                                                break;
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (s.contains("==")) {
                                    String str1 = s.split("==")[0];
                                    String str2 = s.split("==")[1];
                                    if (str1.equals(str2)) {
                                        count++;
                                    }
                                } else if (s.contains("包含")) {
                                    String str1 = s.split("包含")[0];
                                    String str2 = s.split("包含")[1];
                                    if (str1.contains(str2)) {
                                        count++;
                                    }
                                }else {
                                    if (se.eval(s)!=null){
                                        System.out.println("se.eval(s):"+se.eval(s));
                                        if (Boolean.parseBoolean(se.eval(s).toString())){
                                            count++;
                                        }
                                    }
                                }
                            }
                        }
                        if (count == arr.length){
                            strInfo = strInfo.replace(strIf, "1==1");
                        }else {
                            strInfo = strInfo.replace(strIf, "1>1");
                        }
                    }else{
                        if (strIf.contains("==")) {
                            String str1 = strIf.split("==")[0];
                            String str2 = strIf.split("==")[1];
                            if (str1.equals(str2)) {
                                strInfo = strInfo.replace(strIf, "1==1");
                            } else {
                                strInfo = strInfo.replace(strIf, "1>1");
                            }
                        }else if (strIf.contains("包含")) {
                            String str1 = strIf.split("包含")[0];
                            String str2 = strIf.split("包含")[1];
                            if (str1.contains(str2)) {
                                strInfo = strInfo.replace(strIf, "1==1");
                            } else {
                                strInfo = strInfo.replace(strIf, "1>1");
                            }
                        }
                    }

                    strss += "如果(" +strsIfs+")那么{";
                    Object d = se.eval("if"+strInfo);
                    if (d!=null){
                        Double ds = Double.parseDouble(d.toString());
                        if (ds!=null) {
                            strss += "值为" + ds + "};\n";
                        }else {
                            strss += "};\n";
                        }
                    }else {
                        strss += "};\n";
                    }
                }
            }
            //System.out.println("strss.s----:"+strss);
            map.put("str",strss);
            map.setMsg("获取成功");
        } catch (ScriptException e) {
            map.put("str","");
            map.setSuccess(false);
            map.setMsg("公式异常");
        }
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "formulaData")
    public AjaxJson strRemark(@RequestParam(required=false) String type) throws UnsupportedEncodingException {
        AjaxJson map = new AjaxJson();
        List<String> list = new ArrayList<>();
        list.add("如果");
        list.add("(");
        list.add("基本工资");
        list.add("<");
        list.add("3");
        list.add(")");
        list.add("那么");
        list.add("基本工资");
        list.add("+");
        list.add("5");
        list.add("\n");
        list.add("如果");
        list.add("(");
        list.add("状态");
        list.add(">");
        list.add("4");
        list.add(")");
        list.add("那么");
        list.add("基本工资");
        list.add("-");
        list.add("6");
        map.put("data",list);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "formulaType")
    public AjaxJson formulaType() throws UnsupportedEncodingException {
        AjaxJson ajaxJson = new AjaxJson();
        FormulaStatusEnum[] valueStatus = FormulaStatusEnum.values();
        FormulaStrEnum[] valueStr = FormulaStrEnum.values();
        Map<String,Object> map = new HashMap<>();
        for (FormulaStatusEnum value:valueStatus){
            map.put(value.name(),value.getDesc());
        }
        for (FormulaStrEnum value:valueStr){
            map.put(value.name(),value.getDesc());
        }
        ajaxJson.put("data",map);
        return ajaxJson;
    }

}
