package com.saye.hospitalgd.controller.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saye.hospitalgd.commons.JsonResult;
import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.log.ExceptionDUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.*;
import com.saye.hospitalgd.service.system.DepartService;
import com.saye.hospitalgd.service.system.RoleService;
import com.saye.hospitalgd.service.system.UsersService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Controller
public class UsersController {

	@Autowired
	private UsersService usersService;
	
	@Autowired
	private RoleService roleService;

	@Autowired
	private DepartService departService;


	/**
	 * @description 到用户管理页面
	 * @author thuang
	 * @created 2019年11月15日 上午10:12:12
	 * @return
	 */
	@RequestMapping("/toUserManager")
	public String toUserManager(ModelMap modelMap){

		//查询所有部门
		String parentId="10330001";
		List<HashMap<Object, Object>> resourceInfo = this.departService.findDepartTreeNodeList(parentId);
		modelMap.addAttribute("departInfo", resourceInfo);

		//查询所有角色
		List<Role> roleList = this.roleService.findRoleList();
		modelMap.addAttribute("roleList",roleList);


		//查询所有一级地市
		List<HashMap<Object, Object>> departList = departService.findDepartByParentId(new HashMap<String,Object>(){{put("parent_id","10330701");}});
		modelMap.addAttribute("departList",departList);
		return "system/userManager";
	}
	
	/**
	 * 
	 * @description user表分页查询
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:06:12 
	 * @return
	 */
	@RequestMapping("/selectUser")
	@ResponseBody
	public HashMap<String, Object> searchUsers(String departId,String trueName,String isactive,String roleId,String dtRoleId,Integer page, Integer limit) {
		HashMap<Object,Object> map=new HashMap<Object,Object>();
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		try{

			String[] departIds=null;
			if (departId !=null && !"".equals(departId)) {
				departIds = departId.split(",");
			}

			map.put("departId", departIds);
			map.put("trueName", trueName);
			map.put("isactive", isactive);
			map.put("roleId", roleId);
			map.put("dtRoleId", dtRoleId);
			PageHelper.startPage(page, limit);

			PageInfo<Users> appsPageInfo = new PageInfo<Users>(usersService.searchUsers(map));

			resultMap.put("code", 0);
			resultMap.put("msg", "OK");
			resultMap.put("count", appsPageInfo.getTotal());
			resultMap.put("data", appsPageInfo.getList());
		}catch (Exception e){
			resultMap.put("code", 999);
			resultMap.put("msg", e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 
	 * @description 新增用户
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:05:10 
	 * @return
	 */
	@RequestMapping("/insertUsers")
	@ResponseBody
	public JsonResult insertUsers(@RequestBody HashMap<Object, Object> requestMap){
		
		int i;
		JsonResult j=new JsonResult();
		
		try {
			Users user = (Users) SecurityUtils.getSubject().getPrincipal();

			String userName = user.getUserName();
			String userTrueName = user.getTrueName();

			requestMap.put("userName", userName);
			requestMap.put("userTrueName", userTrueName);
		
			i = usersService.insertUser(requestMap);
			if(i>0){
				LogUtil.debug(this.getClass(),"用户"+ user.getTrueName()+"新增用户的方法：requestMap:"+requestMap.toString());
				 j.setState(true);
				 j.setMessage("新增成功！");
			}else{
				j.setState(false);
				j.setMessage("新增失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setState(false);
			j.setMessage(e.getMessage());
			LogUtil.error(this.getClass(), "新增用户失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		
		return j;
	}
	
	/**
	 * 
	 * @description 修改用户
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:04:28 
	 * @return
	 */
	@RequestMapping("/modifyUsers")
	@ResponseBody
	public JsonResult modifyUsers(@RequestBody HashMap<Object, Object> requestMap){
		JsonResult j=new JsonResult();
		try {
			Users user = (Users) SecurityUtils.getSubject().getPrincipal();
	
			String userName = user.getUserName();
			String userTrueName = user.getTrueName();
	
			requestMap.put("userName", userName);
			requestMap.put("userTrueName", userTrueName);
			String createTime = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss);
			String createDate = DateDUtil.getCurrentDate();
			/*requestMap.put("modifyTime", createTime);
			requestMap.put("createTime", createTime);*/
			requestMap.put("createDate", createDate);
			int result=usersService.modifyUsers(requestMap);
			
			if(result>0){
				LogUtil.debug(this.getClass(),"用户"+ user.getTrueName()+"修改用户的方法：requestMap:"+requestMap.toString());
				 j.setState(true);
				 j.setMessage("修改成功！");
			}else{
				j.setState(false);
				j.setMessage("修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setState(false);
			j.setMessage(e.getMessage());
			LogUtil.error(this.getClass(), "修改用户失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		return j;
	}
	
	/**
	 * 
	 * @description 密码重置
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:06:37 
	 * @return
	 */
	@RequestMapping("/reSetPassword")
	@ResponseBody
	public JsonResult reSetPassword(@RequestBody HashMap<Object, Object> requestMap){
		
		JsonResult j=new JsonResult();
		try {
			Users user = (Users) SecurityUtils.getSubject().getPrincipal();
	
			String userName = user.getUserName();
			String userTrueName = user.getTrueName();
			
			requestMap.put("modifyUserName", userName);
			requestMap.put("modifyTrueName", userTrueName);
			String createTime = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss);
			String createDate = DateDUtil.getCurrentDate();
			requestMap.put("createTime", createTime);
			requestMap.put("createDate", createDate);
			//产生6位长度的随机密码（由字母和数字组成）
			String password = StringDUtil.generateRandomCodeForLength(6);
			String addPasswordMd5 = new Md5Hash(password,"hospitalgd",2).toString();
			requestMap.put("password", addPasswordMd5);
			
			int result=usersService.reSetPassword(requestMap);
			
			if(result>0){
				LogUtil.debug(this.getClass(),"用户"+ user.getTrueName()+"重置用户的密码方法：requestMap:"+requestMap.toString());
				 j.setState(true);
				 j.setMessage("修改成功！");
				 j.setData(password);
			}else{
				j.setState(false);
				j.setMessage("修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setState(false);
			j.setMessage(e.getMessage());
			LogUtil.error(this.getClass(), "密码重置失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		return j;
	}
	/**
	 * 
	 * @description 启用/禁用
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:06:54 
	 * @return
	 */
	@RequestMapping("/unableUser")
	@ResponseBody
	public JsonResult unableUser(@RequestBody HashMap<Object, Object> requestMap){
		JsonResult j=new JsonResult();
		try{	
			Users user = (Users) SecurityUtils.getSubject().getPrincipal();

			String userName = user.getUserName();
			String userTrueName = user.getTrueName();
			
			requestMap.put("modifyUserName", userName);
			requestMap.put("modifyTrueName", userTrueName);
			String createTime = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss);
			String createDate = DateDUtil.getCurrentDate();
			requestMap.put("createTime", createTime);
			requestMap.put("createDate", createDate);
			
			int result=usersService.unableUser(requestMap);
			
			if(result>0){
				LogUtil.debug(this.getClass(),"用户"+ user.getTrueName()+"启用禁用用户的方法：requestMap:"+requestMap.toString());
				 j.setState(true);
				 j.setMessage("修改成功！");
			}else{
				j.setState(false);
				j.setMessage("修改失败！");
			}
		}catch (Exception e) {
			e.printStackTrace();
			j.setState(false);
			j.setMessage(e.getMessage());
			LogUtil.error(this.getClass(), "禁用启用失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		return j;
	}
	
	/**
	 * 
	 * @description 查询角色
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:07:09 
	 * @return
	 */
//	@RequestMapping("/findRoleList")
//	@ResponseBody
//	public JsonResult findRoleList(){
//		List<Role> list =roleService.findRoleList();
//		JsonResult j=new JsonResult();
//		j.setState(true);
//		j.setMessage("查询成功");
//		j.setData(list);
//		return j;
//	}
	
	/**
	 * 
	 * @description 新增用户名验证
	 * @author qfqi       
	 * @created 2019年11月5日 下午3:07:22 
	 * @param userName
	 * @return
	 */
	@RequestMapping("/searchByName")
	@ResponseBody
	public JsonResult searchByName(String userName){
		List<Users> list=usersService.searchByName(userName);
		JsonResult j=new JsonResult();
		j.setState(true);
		j.setMessage("查询成功");
		j.setData(list);
		
		return  j;
	}
	
	/**
	 * @description 修改密码
	 * @author thuang       
	 * @created 2019年11月27日 下午6:13:05 
	 * @param requestMap
	 * @return
	 */
	@RequestMapping("/modifyPassword")
	@ResponseBody
	public JsonResult modifyPassword(@RequestBody HashMap<Object, Object> requestMap){
		
		String password = StringDUtil.changeNullToEmpty(requestMap.get("password"));
		String key = StringDUtil.removeSpaces(requestMap.get("key"));
		String initVector = StringDUtil.removeSpaces(requestMap.get("initVector"));
		JsonResult j=new JsonResult();
		try {
			
			Subject subject = SecurityUtils.getSubject();
			Users user = (Users) subject.getPrincipal();
			String username = user.getUserName();
			String passwordMd5 = new Md5Hash(password,"hospitalgd",2).toString();
			String addPasswordMd5 = new Md5Hash(password,"hospitalgd",2).toString();
			
			String modifyTime = DateDUtil.getTheCurrentTime();
			this.usersService.modifyPassword(username,passwordMd5,modifyTime);

			user.setModifyTime(modifyTime);
			j.setState(true);
			j.setMessage("更改密码成功");
			LogUtil.debug(this.getClass(),"用户修改用户的密码方法：requestMap:"+requestMap.toString());
		} catch (Exception e) {
			j.setState(false);
			j.setMessage("更改密码失败");
			e.printStackTrace();
			LogUtil.error(this.getClass(), "修改密码失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
		}
		return j;
	}

	/**
	 * @description: 导入人员信息
	 * @author thuang
	 * @date 2021/5/19 9:57
	 * @version 1.0
	 */
	@RequestMapping("/uploadUsers")
	@ResponseBody
	public HashMap<Object, Object> uploadUsers(@RequestParam("spareFile") MultipartFile file, HttpServletRequest request, HttpServletResponse response)throws Exception{
		HashMap<Object, Object> responseMap=new HashMap<Object, Object>();
		String errCode="0";
		String errMsg="";

		if (!file.isEmpty()) {
			XSSFWorkbook workbook =null;

			//创建Excel，读取文件内容
			workbook = new XSSFWorkbook(file.getInputStream());

			//获取第一个工作表
			XSSFSheet sheet =  workbook.getSheetAt(0);
			//获取sheet中第一行行号
			int firstRowNum = sheet.getFirstRowNum();
			//获取sheet中最后一行行号
			int lastRowNum = sheet.getLastRowNum();

			try {
				//查询部门
				List<HashMap<Object,Object>> departs = departService.selectAllDeparts();
				HashMap<String,HashMap<Object,Object>> departTreeMap=new HashMap<>();
				HashMap<String,List<HashMap<Object,Object>>> parentIdMap=new HashMap<>();
				HashMap<String,HashMap<Object,Object>> departIdMap=new HashMap<>();
				//处理部门组织方便查询
				for (int i=0;i<departs.size();i++){
					HashMap<Object, Object> map = departs.get(i);
					String depart_id = StringDUtil.changeNullToEmpty(map.get("DEPART_ID"));
					String depart_name = StringDUtil.changeNullToEmpty(map.get("DEPART_NAME"));
					String parent_id = StringDUtil.changeNullToEmpty(map.get("PARENT_ID"));
					String parent_name = StringDUtil.changeNullToEmpty(map.get("PARENT_NAME"));

					//如果上级名称为空说明没有上级部门，就是第一级 当然也有错误数据的情况，不过要出问题要满足名称相同，且上级都为空
					departIdMap.put(depart_id,map);
					if ("".equals(parent_name)){
						departTreeMap.put(depart_id,map);
						continue;
					}

					List<HashMap<Object, Object>> pidList = parentIdMap.get(parent_id);
					if (pidList == null){
						pidList=new ArrayList<>();
						parentIdMap.put(parent_id,pidList);
					}
					pidList.add(map);
				}
				for (String key : parentIdMap.keySet()){
					List<HashMap<Object, Object>> list = parentIdMap.get(key);
					HashMap<Object, Object> map = departIdMap.get(key);

					map.put("childen",list);
				}

				//时间
				String create_time = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss);
				String create_date = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd);

				//添加人员
				Subject subject = SecurityUtils.getSubject();
				Users user = (Users) subject.getPrincipal();
				String modify_user_name = user.getUserName();
				String modify_true_name = user.getTrueName();

				//循环插入数据
				int errNum=0;
				List<String> errNumList=new ArrayList<String>();
				List<HashMap<Object,Object>> addList=new ArrayList<>();
				for(int i=firstRowNum+2;i<=lastRowNum;i++){//因为表格中第一行为标题，第二行为列标题
					XSSFRow row = sheet.getRow(i);
					HashMap<Object, Object> addMap=new HashMap<Object, Object>();
					//用户id
					XSSFCell user_id = row.getCell(0);
					if(user_id==null){
						errNum++;
						errNumList.add(""+(i+1));
						continue;
					}else {
						user_id.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("user_id",user_id.getStringCellValue());
						addMap.put("user_name",user_id.getStringCellValue());
					}

					//姓名
					XSSFCell true_name = row.getCell(1);
					if(true_name==null){
						errNum++;
						errNumList.add(""+(i+1));
						continue;
					}else {
						true_name.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("true_name",true_name.getStringCellValue());
					}

					//性别
					XSSFCell sex = row.getCell(2);
					if(sex==null){
						addMap.put("sex","");
					}else {
						sex.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("sex",sex.getStringCellValue());
					}

					//公司
					String companyId="";
					XSSFCell company = row.getCell(3);
					if(company==null){
						errNum++;
						errNumList.add(""+(i+1));
						continue;
					}else {
						company.setCellType(Cell.CELL_TYPE_STRING);
						String companyStr = company.getStringCellValue();

						//第一层是最上一级
						boolean isHas=false;
						for(String key:departTreeMap.keySet()){
							HashMap<Object, Object> hashMap = departTreeMap.get(key);
							List<HashMap<Object,Object>> departList = (List<HashMap<Object,Object>>)hashMap.get("childen");
							//要循环的级别
							for (int j=0;j<departList.size();j++){
								HashMap<Object, Object> departObj = departList.get(j);
								String depart_id = StringDUtil.changeNullToEmpty(departObj.get("DEPART_ID"));
								String depart_name = StringDUtil.changeNullToEmpty(departObj.get("DEPART_NAME"));
								if(companyStr.equals(depart_name)){
									addMap.put("company",depart_id);
									companyId=depart_id;
									isHas=true;
									break;
								}
							}
						}

						//判断对错 错的错误记录加1
						if (!isHas){
							errNum++;
							errNumList.add(""+(i+1));
							continue;
						}
					}

					//部门
					XSSFCell depart = row.getCell(4);
					if(depart==null){
						errNum++;
						errNumList.add(""+(i+1));
						continue;
					}else {
						depart.setCellType(Cell.CELL_TYPE_STRING);
						String departStr = depart.getStringCellValue();

						//从部门树中找到部门
						HashMap<Object, Object> hashMap = departIdMap.get(companyId);
						List<HashMap<Object,Object>> departList = (List<HashMap<Object,Object>>)hashMap.get("childen");
						List<String> data=new ArrayList<>();
						getDepartIdByMapTree(data,departStr,departList);

						if (data.size()>0){
							addMap.put("depart_id",data.get(0));
						}else{
							errNum++;
							errNumList.add(""+(i+1));
							continue;
						}
					}

					//岗位
					XSSFCell post = row.getCell(5);
					if(post==null){
						addMap.put("post","");
					}else {
						post.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("post",post.getStringCellValue());
					}

					//政治面貌
					XSSFCell policital_status = row.getCell(6);
					if(policital_status==null){
						addMap.put("policital_status","");
					}else {
						policital_status.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("policital_status",policital_status.getStringCellValue());
					}

					//专业技术资格
					XSSFCell positional_titles = row.getCell(7);
					if(positional_titles==null){
						addMap.put("positional_titles","");
					}else {
						positional_titles.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("positional_titles",positional_titles.getStringCellValue());
					}

					//学历
					XSSFCell education = row.getCell(8);
					if(education==null){
						addMap.put("education","");
					}else {
						education.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("education",education.getStringCellValue());
					}

					//职业技能名称
					XSSFCell vocational_name = row.getCell(9);
					if(vocational_name==null){
						addMap.put("vocational_name","");
					}else {
						vocational_name.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("vocational_name",vocational_name.getStringCellValue());
					}

					//职业技术等级级别
					XSSFCell level = row.getCell(10);
					if(level==null){
						addMap.put("level","");
					}else {
						level.setCellType(Cell.CELL_TYPE_STRING);
						addMap.put("level",level.getStringCellValue());
					}


					//把固定的参数添加到map 默认密码先设置123
					addMap.put("password",new Md5Hash("123","hospitalgd",2).toString());
					addMap.put("isactive", "1");
					addMap.put("modify_user_name", modify_user_name);
					addMap.put("modify_true_name", modify_true_name);
					addMap.put("create_time", create_time);
					addMap.put("create_date", create_date);

					addList.add(addMap);
				}

				if(errNum>0){
					errCode="999";
					errMsg="导入失败，有"+errNum+"行导入错误";
					responseMap.put("errNumList", errNumList);
				}else{
					try {
						usersService.insertExcelUsers(addList);//往数据库插入数据
					} catch (Exception e) {
						LogUtil.error(this.getClass(), "上传人员列表失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
					}
				}
			} catch (Exception e) {
				errCode="999";
				errMsg="上传备件列表失败！"+e.getMessage();
				e.printStackTrace();
				LogUtil.error(this.getClass(), "上传人员列表失败，原因:"+ExceptionDUtil.getDetailExceptionMsg(e));
			} finally {
				workbook.close();
			}
		}

		responseMap.put("errCode", errCode);
		responseMap.put("errMsg", errMsg);

		return responseMap;
	}

	/**
	 * @description: 根据部门id查询相关人员
	 * @author thuang
	 * @date 2021/8/3 10:15
	 * @version 1.0
	 */
	@RequestMapping("/findUserByDepartId")
	@ResponseBody
	public HashMap<Object,Object> findUserByDepartId(@RequestBody HashMap<Object,Object> map){
		HashMap<Object, Object> responseMap=new HashMap<Object, Object>();
		String errCode="0";
		String errMsg="";

		try {
			String departIds = StringDUtil.changeNullToEmpty(map.get("departIds"));

			//如果是空的就直接返回个空集合 不查询
			if ("".equals(departIds)){
				responseMap.put("userList",new ArrayList<>());
			}else {
				String[] split = departIds.split(",");

				List<String> idList=new ArrayList<>();
				for (int i = 0; i < split.length; i++) {
					idList.add(split[i]);
				}

				List<HashMap<Object, Object>> userByDepartIds = usersService.findUserByDepartIds(idList);

				//循环数据生成所要格式 list 中 {name，value}
				List<HashMap<Object, Object>> userList =new ArrayList<>();
				for (int i = 0; i < userByDepartIds.size(); i++) {
					HashMap<Object, Object> hashMap = userByDepartIds.get(i);
					HashMap<Object, Object> selectObj=new HashMap<>();

					selectObj.put("name",hashMap.get("TRUE_NAME"));
					selectObj.put("value",hashMap.get("USER_ID"));
					userList.add(selectObj);
				}
				responseMap.put("userList",userList);
			}

		}catch (Exception e){
			e.printStackTrace();
			errCode="999";
			errMsg="查询部门相关人员失败，原因："+e.getMessage();
		}

		responseMap.put("errCode", errCode);
		responseMap.put("errMsg", errMsg);

		return responseMap;
	}

	/**
	 * @description: 从上面生成的部门Map中根据部门名称获取部门id
	 * @author thuang
	 * @date 2021/7/14 13:45
	 * @version 1.0
	 * @param data
	 */
	public void getDepartIdByMapTree(List<String> data, String departStr, List<HashMap<Object, Object>> departList){

		for (int i=0;i<departList.size();i++){
			HashMap<Object, Object> departObj = departList.get(i);

			String depart_id = StringDUtil.changeNullToEmpty(departObj.get("DEPART_ID"));
			String depart_name = StringDUtil.changeNullToEmpty(departObj.get("DEPART_NAME"));
			List<HashMap<Object,Object>> departChildenList = (List<HashMap<Object,Object>>)departObj.get("childen");

			if(departStr.equals(depart_name)){
				data.add(depart_id);
				return;
			}
			if(departChildenList!=null && departChildenList.size()>0){
				getDepartIdByMapTree(data,departStr,departChildenList);
			}
		}

	}
}
