package com.zcloud.controller.system;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.service.system.*;
import com.zcloud.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.entity.system.Role;
import com.zcloud.util.Const;
import com.zcloud.util.DateUtil;
import com.zcloud.util.FileDownload;
import com.zcloud.util.FileUpload;
import com.zcloud.util.GetPinyin;
import com.zcloud.util.IdcardUtils;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.ObjectExcelRead;
import com.zcloud.util.ObjectExcelView;
import com.zcloud.util.PathUtil;
import com.zcloud.util.Smb;
import com.zcloud.util.Tools;


import net.sf.json.JSONArray;

/**
 * 说明：系统用户处理类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Controller
@RequestMapping("/user")
public class UsersController extends BaseController {

	@Autowired
    private UsersService usersService;
	@Autowired
    private RoleService roleService;
	@Autowired
	private UeditorService ueditorService;
	@Autowired
    private FHlogService FHLOG;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private PostService postService;
	@Autowired
	private DictionariesService dictionariesService;
	/**用户列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	@RequiresPermissions("user:list")
	@ResponseBody
	public Object listUsers(Page page)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		/*检索条件*/
		String ROLE_ID = pd.getString("ROLE_ID");						//角色ID
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		String DEPARTMENT_ID = pd.getString("DEPARTMENT_ID");						//关键词检索条件
		if(Tools.notEmpty(DEPARTMENT_ID))pd.put("DEPARTMENT_ID", DEPARTMENT_ID.trim());
		String STRARTTIME = pd.getString("STRARTTIME");					//开始时间
		String ENDTIME = pd.getString("ENDTIME");						//结束时间
		if(Tools.notEmpty(STRARTTIME))pd.put("STRARTTIME", STRARTTIME+" 00:00:00");
		if(Tools.notEmpty(ENDTIME))pd.put("ENDTIME", ENDTIME+" 00:00:00");
		//pd.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		pd.put("AGENCY_MANAGEMENT_ID",Jurisdiction.getAGENCY_MANAGEMENT_ID());
		List<PageData>	userList = usersService.userlistPage(page);		//列出用户列表
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);		//列出所有系统用户角色

		map.put("userList", userList);
		map.put("roleList", roleList);
		map.put("ROLE_ID", ROLE_ID);
		map.put("page", page);
		map.put("pd", pd);

		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getUserList")
	@ResponseBody
	public Object getUserList() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData> varList = new ArrayList<PageData>();
		if( !Jurisdiction.getUsername().equals("admin") && !Jurisdiction.getUsername().equals("adminsuper") ) {
			pd.put("AGENCY_MANAGEMENT_ID", Jurisdiction.getAGENCY_MANAGEMENT_ID());
		}
		varList = usersService.listbyId(pd);	//根据ID读取
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/resetPwd")
	@RequiresPermissions("corpinfo:edit")
	@ResponseBody
	public Object resetPwd (Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		String msg = "";
		PageData pd = new PageData();
		pd = this.getPageData();
//		PageData user= usersService.listAllUser(pd).get(0);
		String pwd = new SimpleHash("SHA-1", pd.getString("USERNAME"), "Aa@123456").toString();
		PageData updateUser = new PageData();
		updateUser.put("PASSWORD", pwd);
		updateUser.put("USER_ID", pd.getString("USER_ID"));
		usersService.editPassword(updateUser);


		map.put("msg", msg);
		map.put("result", errInfo);
		return map;
	}
	/**用户列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/agentUsersList")
	@RequiresPermissions("user:list")
	@ResponseBody
	public Object agentUsersList(Page page)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		/*检索条件*/
		String ROLE_ID = pd.getString("ROLE_ID");						//角色ID
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		String DEPARTMENT_ID = pd.getString("DEPARTMENT_ID");						//关键词检索条件
		if(Tools.notEmpty(DEPARTMENT_ID))pd.put("DEPARTMENT_ID", DEPARTMENT_ID.trim());
		String STRARTTIME = pd.getString("STRARTTIME");					//开始时间
		String ENDTIME = pd.getString("ENDTIME");						//结束时间
		if(Tools.notEmpty(STRARTTIME))pd.put("STRARTTIME", STRARTTIME+" 00:00:00");
		if(Tools.notEmpty(ENDTIME))pd.put("ENDTIME", ENDTIME+" 00:00:00");
		//pd.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		List<PageData>	userList = usersService.userlistPage(page);		//列出用户列表
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);		//列出所有系统用户角色

		map.put("userList", userList);
		map.put("roleList", roleList);
		map.put("ROLE_ID", ROLE_ID);
		map.put("page", page);
		map.put("pd", pd);

		map.put("result", errInfo);
		return map;
	}

	/**去新增用户页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goAddUser")
	@ResponseBody
	public Object goAddUser()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);		//列出所有系统用户角色
		map.put("roleList", roleList);
		pd = this.getPageData();
		// 查询用户基本信息
		pd = usersService.findById(pd);
		// 获取代理商各级别企业可创建数量
		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);


//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		PageData dept = new PageData();
//		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//		dept=this.departmentService.findByCorpId(dept);
//		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");
//
//		PageData node = new PageData();
//		node.put("id", dept.get("DEPARTMENT_ID"));
//		node.put("parentId", dept.get("PARENT_ID"));
//		node.put("name", dept.get("NAME"));
//		node.put("icon", "../../../assets/images/user.gif");
//		zdepartmentPdList.add(node);
//		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
//		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
//
//		//获取岗位下拉
//		PageData post = new PageData();
//		post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
//		post.put("STATUS", 0);
//		List<PageData> postList = this.postService.listAll(post);
//		map.put("postList", postList);
		map.put("dlzh", Jurisdiction.getUsername());
		map.put("result", errInfo);
		return map;
	}

	/**去修改用户页面(从系统用户页面修改)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goEditUser")
	@RequiresPermissions("user:edit")
	@ResponseBody
	public Object goEditUser() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		// 查询用户基本信息
		pd = usersService.findById(pd);
		List<String> POSSESSIONALL = new ArrayList<String>();
		if(pd.get("AGENTPROVINCE") != null && Tools.notEmpty(pd.get("AGENTPROVINCE").toString())) {
			POSSESSIONALL.add(pd.get("AGENTPROVINCE").toString());
		}
		if(pd.get("AGENTCITY") != null && Tools.notEmpty(pd.get("AGENTCITY").toString())) {
			POSSESSIONALL.add(pd.get("AGENTCITY").toString());
		}
		if(pd.get("AGENTCOUNTY") != null && Tools.notEmpty(pd.get("AGENTCOUNTY").toString())) {
			POSSESSIONALL.add(pd.get("AGENTCOUNTY").toString());
		}
		if(pd.get("AGENTVILLAGE") != null && Tools.notEmpty(pd.get("AGENTVILLAGE").toString())) {
			POSSESSIONALL.add(pd.get("AGENTVILLAGE").toString());
		}
		if(pd.get("AGENTSTREET") != null && Tools.notEmpty(pd.get("AGENTSTREET").toString())) {
			POSSESSIONALL.add(pd.get("AGENTSTREET").toString());
		}
		if(POSSESSIONALL != null && POSSESSIONALL.size() > 0) {
			pd.put("posOption", initDicTreeByNum(POSSESSIONALL.get(POSSESSIONALL.size()-1)));
		}

		pd.put("POSSESSION", POSSESSIONALL);
		map.put("pd", pd);
		map.put("dlzh", Jurisdiction.getUsername());
		map.put("result", errInfo);
		return map;
	}

	/**去修改用户页面(个人资料修改)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goEditMyInfo")
	@ResponseBody
	public Object goEditMyInfo() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);	//列出所有系统用户角色
		pd.put("USERNAME", Jurisdiction.getUsername());
		pd = usersService.findByUsername(pd);						//根据用户名读取
		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);
		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		PageData dept = new PageData();
//		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//		dept=this.departmentService.findByCorpId(dept);
//		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");
//
//		PageData node = new PageData();
//		node.put("id", dept.get("DEPARTMENT_ID"));
//		node.put("parentId", dept.get("PARENT_ID"));
//		node.put("name", dept.get("NAME"));
//		node.put("icon", "../../../assets/images/user.gif");
//		zdepartmentPdList.add(node);
//		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
//		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
//
//		String depname = null == dept?"请选择":dept.getString("NAME");
//		map.put("depname", null == depname?"请选择":depname);
//
//		//获取岗位下拉
//		PageData post = new PageData();
//		post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
//		post.put("STATUS", 0);
//		List<PageData> postList = this.postService.listAll(post);
//		map.put("postList", postList);
		map.put("pd", pd);
		map.put("roleList", roleList);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 修改用户(系统用户列表修改)
	 */
	@RequestMapping(value="/editUser")
	@RequiresPermissions("user:edit")
	@ResponseBody
	public Object editUser() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		FHLOG.save(Jurisdiction.getUsername(), "从系统用户中修改"+pd.getString("USERNAME")+"的资料");				//记录日志
		if(!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))){ //如果当前登录用户修改用户资料提交的用户名非本人
			if("admin".equals(pd.getString("USERNAME")) && !"admin".equals(Jurisdiction.getUsername())){return null;}	//非admin用户不能修改admin
		}else{	//如果当前登录用户修改用户资料提交的用户名是本人，则不能修改本人的角色ID
			PageData upd = new PageData();
			upd = usersService.findByUsername(pd);
			pd.put("ROLE_ID", upd.getString("ROLE_ID")); //对角色ID还原本人角色ID
			pd.put("ROLE_IDS", Tools.notEmpty(upd.getString("ROLE_IDS"))?upd.get("ROLE_IDS"):""); //对角色ID还原本人副职角色ID
		}
//		if(pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))){
//			pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
//		}
		usersService.editUser(pd);	//执行修改
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 修改用户(系统用户列表修改)
	 */
	@RequestMapping(value="/editUserFuns")
	@RequiresPermissions("user:edit")
	@ResponseBody
	public Object editUserFuns() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		FHLOG.save(Jurisdiction.getUsername(), "从系统用户中修改"+pd.getString("USERNAME")+"的小程序菜单权限");				//记录日志
		usersService.editUserFuns(pd);	//执行修改
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 修改用户(个人资料修改)
	 */
	@RequestMapping(value="/editUserOwn")
	@ResponseBody
	public Object editUserOwn() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))){ //如果当前登录用户修改用户资料提交的用户名非本人
			FHLOG.save(Jurisdiction.getUsername(), "恶意修改用户资料："+pd.getString("USERNAME"));
			return null;//不能修改非本人的资料
		}else{			//如果当前登录用户修改用户资料提交的用户名是本人，则不能修改本人的角色ID
			PageData upd = new PageData();
			upd = usersService.findByUsername(pd);
			pd.put("USER_ID", upd.getString("USER_ID")); //对ID还原本人ID，防止串改
			pd.put("ROLE_ID", upd.getString("ROLE_ID")); //对角色ID还原本人角色ID
			pd.put("ROLE_IDS", Tools.notEmpty(upd.getString("ROLE_IDS"))?upd.get("ROLE_IDS"):""); //对角色ID还原本人副职角色ID
		}
		if(pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))){
			pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
		}
		usersService.editUser(pd);	//执行修改
		FHLOG.save(Jurisdiction.getUsername(), "从个人资料中修改"+pd.getString("USERNAME")+"的资料");				//记录日志
		map.put("result", errInfo);
		return map;
	}

	/**判断用户名是否存在
	 * @return
	 */
	@RequestMapping(value="/hasUser")
	@ResponseBody
	public Object hasUser() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = usersService.findByUsername(pd);
		if(pd != null){
			map.put("pd",pd);
			errInfo = "fail";
			map.put("msg", "用户名已存在");
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**判断邮箱是否存在
	 * @return
	 */
	@RequestMapping(value="/hasEmail")
	@ResponseBody
	public Object hasEmail() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(usersService.findByEmail(pd) != null){
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**判断编码是否存在
	 * @return
	 */
	@RequestMapping(value="/hasNumber")
	@ResponseBody
	public Object hasNumber() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(usersService.findByNumbe(pd) != null){
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**检验身份证号是否有效
	 * @return
	 */
	@RequestMapping(value="/validateIdentity")
	@ResponseBody
	public Object validateIdentity() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("ISVALIDATE", IdcardUtils.validateCard(pd.getString("IDENTITY_NUMBER")));
		map.put("pd",pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**保存用户
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveUser")
	@RequiresPermissions("user:add")
	@ResponseBody
	public Object saveUser() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("USER_ID", this.get32UUID());			//ID 主键
		pd.put("LAST_LOGIN", "");						//最后登录时间
		pd.put("IP", "");								//IP
		pd.put("STATUS", "0");							//状态
		pd.put("ISMAIN", "0");
		pd.put("ISDELETE", "0");
		pd.put("RIGHTS", "3245474264");
		pd.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");		//用户默认皮肤
		pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), "Aa@123456").toString());			//密码加密
//		pd.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
		if(null == usersService.findByUsername(pd)){	//判断用户名是否存在
			if(!Tools.isEmpty(Jurisdiction.getAGENCY_MANAGEMENT_ID())){
				pd.put("ISAGENT","1");
				pd.put("AGENCY_MANAGEMENT_ID",Jurisdiction.getAGENCY_MANAGEMENT_ID());
			}else {
				pd.put("ISAGENT","0");
			}
			usersService.saveUser(pd); 					//执行保存
//			agentNumberServic

		}else{
			map.put("result","failed");
		}
		FHLOG.save(Jurisdiction.getUsername(), "新增用户："+pd.getString("USERNAME"));				//记录日志
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**删除用户
	 * @return
	 */
	@RequestMapping(value="/deleteUser")
	@RequiresPermissions("user:del")
	@ResponseBody
	public Object deleteUser() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		String errInfo = "success";
		pd = this.getPageData();
		FHLOG.save(Jurisdiction.getUsername(), "删除用户ID："+pd.getString("USER_ID"));				//记录日志
		usersService.deleteUser(pd);			//删除用户
//		ueditorService.delete(pd);				//删除副文本关联数据
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**
	 * 批量删除
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAllUser")
	@RequiresPermissions("user:del")
	@ResponseBody
	public Object deleteAllUser() throws Exception{
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		pd = this.getPageData();
		String USER_IDS = pd.getString("USER_IDS");
		String errInfo = "success";
		if(Tools.notEmpty(USER_IDS)){
			String ArrayUSER_IDS[] = USER_IDS.split(",");
			FHLOG.save(Jurisdiction.getUsername(), "批量删除用户");				//记录日志
			usersService.deleteAllUser(ArrayUSER_IDS);	//删除用户
//			ueditorService.deleteAll(ArrayUSER_IDS);	//删除副文本关联数据
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**导出用户信息到EXCEL
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	@RequiresPermissions("toExcel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{

			/*检索条件*/
			String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
			if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
			String STRARTTIME = pd.getString("STRARTTIME");					//开始时间
			String ENDTIME = pd.getString("ENDTIME");						//结束时间
			if(Tools.notEmpty(STRARTTIME))pd.put("STRARTTIME", STRARTTIME+" 00:00:00");
			if(Tools.notEmpty(ENDTIME))pd.put("ENDTIME", ENDTIME+" 00:00:00");

			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("用户名"); 		//1
			titles.add("编号");  		//2
			titles.add("姓名");			//3
			titles.add("职位");			//4
			titles.add("手机");			//5
			titles.add("邮箱");			//6
			titles.add("最近登录");		//7
			titles.add("上次登录IP");	//8
			dataMap.put("titles", titles);
			List<PageData> userList = usersService.listAllUser(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<userList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", userList.get(i).getString("USERNAME"));		//1
				vpd.put("var2", userList.get(i).getString("NUMBER"));		//2
				vpd.put("var3", userList.get(i).getString("NAME"));			//3
				vpd.put("var4", userList.get(i).getString("ROLE_NAME"));	//4
				vpd.put("var5", userList.get(i).getString("PHONE"));		//5
				vpd.put("var6", userList.get(i).getString("EMAIL"));		//6
				vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));	//7
				vpd.put("var8", userList.get(i).getString("IP"));			//8
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
		}
		return mv;
	}

	/**下载模版
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/downExcel")
	public void downExcel(HttpServletResponse response)throws Exception{
		FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");
	}

	/**从EXCEL导入到数据库
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/readExcel")
	@RequiresPermissions("fromExcel")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public Object readExcel(@RequestParam(value="excel",required=false) MultipartFile file) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		String  ffile = DateUtil.getDays(), fileName = "";
		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE;								//文件上传路径
//			String fileName =  FileUpload.fileUp(file, filePath, "userexcel");								//执行上传
			fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			Smb.sshSftp(file, fileName,Const.FILEPATHFILE + ffile);
			List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);			//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			pd.put("LAST_LOGIN", "");				//最后登录时间
			pd.put("IP", "");						//IP
			pd.put("STATUS", "0");					//状态
			pd.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");					//默认皮肤
			pd.put("ROLE_ID", "fhadminzhuche");		//默认角色注册用户
			pd.put("ROLE_IDS", "");					//副职角色
			/**
			 * var0 :编号
			 * var1 :姓名
			 * var2 :手机
			 * var3 :邮箱
			 * var4 :备注
			 */
			for(int i=0;i<listPd.size();i++){
				pd.put("USER_ID", this.get32UUID());										//ID
				pd.put("NAME", listPd.get(i).getString("var1"));							//姓名
				String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"));	//根据姓名汉字生成全拼
				pd.put("USERNAME", USERNAME);
				if(usersService.findByUsername(pd) != null){								//判断用户名是否重复
					USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"))+Tools.getRandomNum();
					pd.put("USERNAME", USERNAME);
				}
				pd.put("BZ", listPd.get(i).getString("var4"));								//备注
				if(Tools.checkEmail(listPd.get(i).getString("var3"))){						//邮箱格式不对就跳过
					pd.put("EMAIL", listPd.get(i).getString("var3"));
					if(usersService.findByEmail(pd) != null){								//邮箱已存在就跳过
						continue;
					}
				}else{
					continue;
				}
				pd.put("NUMBER", listPd.get(i).getString("var0"));							//编号已存在就跳过
				pd.put("PHONE", listPd.get(i).getString("var2"));							//手机号

				pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "Aa@123456").toString());	//默认密码123
				if(usersService.findByNumbe(pd) != null){
					continue;
				}
				usersService.saveUser(pd);
			}
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**去修改用户页面(在线管理页面打开)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goEditUfromOnline")
	@ResponseBody
	public Object goEditUfromOnline() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if("admin".equals(pd.getString("USERNAME"))){return null;}	//不能查看admin用户
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);	//列出所有系统用户角色
		map.put("fx", "user");
		pd = usersService.findByUsername(pd);						//根据ID读取
		String ROLE_IDS = pd.getString("ROLE_IDS");					//副职角色ID
		if(Tools.notEmpty(ROLE_IDS)){
			String arryROLE_ID[] = ROLE_IDS.split(",");
			for(int i=0;i<roleList.size();i++){
				Role role = roleList.get(i);
				String roleId = role.getROLE_ID();
				for(int n=0;n<arryROLE_ID.length;n++){
					if(arryROLE_ID[n].equals(roleId)){
						role.setRIGHTS("1");	//此时的目的是为了修改用户信息上，能看到副职角色都有哪些
						break;
					}
				}
			}
		}
		map.put("pd", pd);
		map.put("roleList", roleList);
		map.put("result", errInfo);
		return map;
	}

	/**查看用户
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/view")
	@ResponseBody
	public Object view() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String USERNAME = pd.getString("USERNAME");
		if("admin".equals(USERNAME)){return null;}					//不能查看admin用户
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);	//列出所有系统用户角色
		pd = usersService.findByUsername(pd);						//根据ID读取
		map.put("msg", "1");
		if(null == pd){
			PageData rpd = new PageData();
			rpd.put("RNUMBER", USERNAME);							//用户名查不到数据时就把数据当作角色的编码去查询角色表
			rpd = roleService.getRoleByRnumber(rpd);
			map.put("rpd", rpd);
			map.put("msg", "2");
		}
		map.put("pd", pd);
		map.put("roleList", roleList);
		map.put("result", errInfo);
		return map;
	}

	/**显示用户列表(弹窗选择用)
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/listUsersForWindow")
	@ResponseBody
	public Object listUsersForWindow(Page page)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		String STRARTTIME = pd.getString("STRARTTIME");					//开始时间
		String ENDTIME = pd.getString("ENDTIME");						//结束时间
		if(Tools.notEmpty(STRARTTIME))pd.put("STRARTTIME", STRARTTIME+" 00:00:00");
		if(Tools.notEmpty(ENDTIME))pd.put("ENDTIME", ENDTIME+" 00:00:00");
		page.setPd(pd);
		List<PageData>	userList = usersService.listUsersBystaff(page);	//列出用户列表(弹窗选择用)
		pd.put("ROLE_ID", "1");
		List<Role> roleList = roleService.listAllRolesByPId(pd);		//列出所有系统用户角色
		map.put("userList", userList);
		map.put("roleList", roleList);
		map.put("page", page);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/listAll")
	@ResponseBody
	public Object listAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData>	userList = usersService.listAllUser(pd);	//列出Post列表
		map.put("userList", userList);
		map.put("result", errInfo);
		return map;
	}
	/**
	 * 显示列表listCascader
	 * @return
	 */
	@RequestMapping(value="/listCascader")
	@ResponseBody
	public Object listCascader()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		List<PageData> pdList = new ArrayList<PageData>();
		List<Dictionaries> dictList = dictionariesService.listSubDictByParentId("532282f9c48346b8b646531909c739df"); //获取在线考试适用人员的子列表数据
		PageData pd = new PageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		List<PageData> userList = this.usersService.listCascader(pd);	//获取单位下的所有人员

		PageData other = new PageData();
		other.put("value", "-");
		other.put("label", "其他");
		List<PageData> otherChildrenList = new ArrayList<PageData>();
		for (Dictionaries dict : dictList ) {
			PageData pd0 = new PageData();
			pd0.put("value", dict.getBIANMA());
			pd0.put("label", dict.getNAME());
			List<PageData> childrenList = new ArrayList<PageData>();
			for (PageData user : userList ) {
				if (user.get("LEARNERCATEGORY") != null && dict.getBIANMA().equals(user.getString("LEARNERCATEGORY"))) {
					PageData pd1 = new PageData();
					pd1.put("value", user.getString("USER_ID"));
					pd1.put("label", user.getString("USERNAME")+" [" + user.getString("DEPARTMENTNAME") + " ]");
					childrenList.add(pd1);
				}
			}
			if (childrenList.size() > 0) {
				pd0.put("children", childrenList);
				pdList.add(pd0);
			}
		}
		//未设置人员在线学习分类的放到其他里
		for (PageData user : userList ) {
			if (user.get("LEARNERCATEGORY") == null) {
				PageData pd1 = new PageData();
				pd1.put("value", user.getString("USER_ID"));
				pd1.put("label", user.getString("USERNAME")+" [" + user.getString("DEPARTMENTNAME") + " ]");
				otherChildrenList.add(pd1);
			}
		}
		if (otherChildrenList.size() > 0) {
			other.put("children", otherChildrenList);
			pdList.add(other);
		}

		JSONArray arr = JSONArray.fromObject(pdList);
		String json = arr.toString();
		map.put("USER_ID", Jurisdiction.getUSER_ID());
		map.put("CascaderNodes", json);
		map.put("result", errInfo);
		return map;
	}


	/**
	 * 初始化数据字典懒加载下拉树（根据编码）
	 * @param dictionaries_bianma
	 * @return
	 * @throws Exception
	 */
	public List<PageData> initDicTreeByNum(String dictionaries_bianma) throws Exception{
		PageData dic = new PageData();
		dic.put("BIANMA", dictionaries_bianma);
		dic = dictionariesService.findByBianma(dic);
		dic.put("value", dic.get("DICTIONARIES_ID"));
		dic.put("numValue", dic.get("BIANMA"));
		dic.put("id", dic.get("DICTIONARIES_ID"));
		dic.put("label", dic.get("NAME"));
		List<PageData> industryOption = dictionariesService.getTreeFromBelow(new ArrayList<PageData>(),dic);
		return industryOption;
	}
	/**从EXCEL导入到数据库
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/readExcel2")
//	@RequiresPermissions("fromExcel")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@Transactional
	public Object readExcel2(@RequestParam(value="FFILE",required=false) MultipartFile file) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		StringBuffer errorStr = new StringBuffer();

		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + "user/";
			String fileName =  FileUpload.fileUp(file, filePath, this.get32UUID());//执行上传
			List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 1, 0, 0);			//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			/**
			 * var0 :用户名
			 * var1 :用户角色
			 * var2 :姓名
			 * var3 :性别
			 * var4	:手机号
			 * var5 :邮箱
			 * var6 :备注
			 */

			List<String> header = new ArrayList<String>();
			header.add("用户名");header.add("用户角色");header.add("姓名");header.add("性别");header.add("手机号");header.add("邮箱");header.add("备注");
			try{

				if(listPd.size()>0) {

					/** 获取所有岗位信息结束 */

					/** 获取所有用户信息 用于判断姓名是否重复 */
					PageData userPd = new PageData();
					List<PageData> userList = usersService.findUserNameAll(userPd);
					Map<String, Object> userMap = new HashMap<>();
					for (PageData pageData : userList) {
						userMap.put(pageData.getString("USERNAME"), "");
					}

					/**
					 *  判断是否填写必填
					 *  判断excel是有有重复数据
					 *  判断数据库是否有重复数据
					 *  导入 Page
					 *
					 *  企业分级账号
					 */
					Map<String, Object> hasUserNameChongfu = new HashMap<>();//判断重复数据

//					Map<String, Object> emailChongfu = new HashMap<>();//判断重复数据
					Integer number =0;//行数，用于提示用户
					List<PageData> addUserList = new ArrayList<>();
					for(PageData lpd:listPd) {
						number++;
						for(int i=0;i<5;i++) {
							if(i>5) {
								continue;
							}
							if(!lpd.containsKey("var"+i)) {
								errorStr.append("第"+number+"行的\""+header.get(i)+"\"无数据;\n");
								continue;
							}
							if(Tools.isEmpty(lpd.get("var"+i))) {
								errorStr.append("第"+number+"行的\""+header.get(i)+"\"无数据;\n");
								continue;
							}
						}

						String userName  = Tools.isEmpty(lpd.get("var0"))?"":Tools.excelHandle(lpd.get("var0"));//用户名
						String ROLE_ID = Tools.isEmpty(lpd.get("var1"))?"":lpd.get("var1").toString();//用户角色
						String NAME = Tools.isEmpty(lpd.get("var2"))?"":lpd.get("var2").toString();//姓名
						String SEX = Tools.isEmpty(lpd.get("var3"))?"":lpd.get("var3").toString();//性别
						String PHONE = Tools.isEmpty(lpd.get("var4"))?"":lpd.get("var4").toString();//手机号
						String eMail = Tools.isEmpty(lpd.get("var5"))?"":lpd.get("var5").toString();//邮箱
						String bz = Tools.isEmpty(lpd.get("var6"))?"":lpd.get("var6").toString();//备注
			/*
						if(Tools.isEmpty(dept) || Tools.isEmpty(postName) || Tools.isEmpty(userName) ||Tools.isEmpty(name)  ) {
							errInfo = "error";
							errorStr.append("第"+number+"行,公司级部门,岗位,用户名,姓名为信息必填项,请重新确认数据");
							break;
						}
						*/
			/*			if(!departMap.containsKey(dept)) {
							errorStr.append("第"+number+"行的"+header.get(0)+"未找到名称为\""+dept+"\"的部门"+";\n");
							continue;
						}*/
						Pattern patternPhone = Pattern.compile(RegexPatterns.PHONE_REGEX);
						Matcher matcher = patternPhone.matcher(PHONE);
						if(!matcher.matches()) {
							errorStr.append("第"+number+"行,");
							errorStr.append("手机号格式不正确,请重新确认数据;\n");
							continue;
						}
						Pattern patternUsername = Pattern.compile(RegexPatterns.USERNAME_REGEX);
						Matcher matchername = patternUsername.matcher(userName);
						if(!matchername.matches()) {
							errorStr.append("第"+number+"行,");
							errorStr.append("用户名不可为汉字,请重新确认数据;\n");
							continue;
						}


						/** 岗位  结束**/
						if(userMap.containsKey(userName)) {
							System.out.println(userMap.containsKey(userName));
							errorStr.append("第"+number+"行,");
							errorStr.append("用户名“"+userName+"”已经存在，请勿重复导入;\n");
							continue;
						}
						if(hasUserNameChongfu.containsKey(userName)) {
							errorStr.append("第"+number+"行,");
							errorStr.append("用户名重复,请重新确认数据;\n");
							continue;
						}
						PageData yonghujuese = new PageData();
						if(!Tools.isEmpty(ROLE_ID)){//人员类型
							yonghujuese = roleService.findByName(ROLE_ID,"eee570eff038464cbdfac5f8579bbace");//用户角色
							if(null == yonghujuese ){
								errorStr.append("第"+number+"行,");
								errorStr.append("未找到用户角色信息,请重新确认数据;\n");
								continue;
							}

						}
						PageData xingbei = dictionariesService.findByNames(SEX,"21501808bbc344d593fbf9ccfe6c4531");//性别
						if(null == xingbei ){
							errorStr.append("第"+number+"行,");
							errorStr.append("未找到该性别信息,请重新确认数据;\n");
							continue;
						}

						PageData user = new PageData();
						user.put("USER_ID", this.get32UUID());
						user.put("USERNAME", userName);
						user.put("PASSWORD",  new SimpleHash("SHA-1", userName, "Aa@123456").toString());
						user.put("NAME", NAME);
						user.put("ROLE_ID", yonghujuese.get("ROLE_ID"));
						user.put("LAST_LOGIN", "");
						user.put("SEX", xingbei.get("DICTIONARIES_ID"));
						user.put("IP", "");
						user.put("STATUS", "0");
						user.put("ISDELETE", "0");
						user.put("BZ", bz);
						user.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");
						user.put("EMAIL", eMail);
						user.put("NUMBER", "");
						user.put("PHONE", PHONE);
						user.put("ROLE_IDS", "");
						user.put("ISMAIN", "0");
						user.put("FUN_IDS", "");
						if(!Tools.isEmpty(Jurisdiction.getAGENCY_MANAGEMENT_ID())){
							user.put("ISAGENT","1");
							user.put("AGENCY_MANAGEMENT_ID",Jurisdiction.getAGENCY_MANAGEMENT_ID());
						}else {
							user.put("ISAGENT","0");
						}
						user.put("RIGHTS", "3245474264");

						addUserList.add(user);
					}
					if(Tools.isEmpty(errorStr.toString())) {
						for (PageData pageData : addUserList) {
							usersService.saveUser(pageData);
//								userInfoService.save(pageData);
						}

						errorStr.append("成功导入"+addUserList.size()+"条数据!");
					}else {
						errInfo = "error";
					}
					File old = new File(filePath, fileName);
					old.delete();
				}else {
					map.put("result", "error");				//返回结果
					map.put("msg", "Excel数据为空，请检查数据后，重新上传！");
					File old = new File(filePath, fileName);
					old.delete();
					return map;
				}
			}catch (Exception e) {
				map.put("result", "fail");				//返回结果
				map.put("msg", e.toString());
				e.printStackTrace();
				return map;
			}

		}
		map.put("result", errInfo);				//返回结果
		map.put("msg",errorStr.toString());				//返回结果
		map.put("isExcel","1");				//返回类型
		map.put("resultStr", errorStr.toString());
		return map;
	}
}
