package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.fegin.PatrolFeign;
import com.yeejoin.equipmanage.remote.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取用户信息
 *
 * @author gaodongdong
 */
@RestController
@RequestMapping(value = "/api/user")
@Api(tags = "用户信息api")
public class UserController extends AbstractBaseController {

	private final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private RemoteSecurityService remoteSecurityService;
	@Autowired
	private AppMessagePushService appMessagePushService;
	@Autowired
	private com.yeejoin.equipmanage.remote.PushFeign PushFeign;
	private static final String appType = "APP";
	@Autowired
	private RestTemplate restTemplate;
	@Value("${security.privilege.name}")
	private String SecurityName;
	@Value("${security.systemctl.name}")
	private String systemctl;
	@Autowired
	private PatrolFeign patrolFeign;

	/**
	 * 根据部门id查询用户信息
	 *
	 * @param deptId
	 * @return
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "部门人员查询", notes = "部门人员查询")
	@RequestMapping(value = "/queryDeptUser", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<LinkedHashMap<String, Object>> queryDeptUser(
			@RequestParam(value = "deptId", required = false) String deptId) {
		List<AgencyUserModel> userModels = remoteSecurityService.listUserByDepartmentId(Long.valueOf(deptId));
		List<LinkedHashMap<String, Object>> userList = paraseData(userModels, null);

		return userList;
	}

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "部门人员树查询", notes = "部门人员树查询")
	@RequestMapping(value = "/queryDeptUserTree1", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<DepartmentUserTreeWebVo> queryDeptUserTree1() {
		ReginParams reginParams = getSelectedOrgInfo();

		CompanyModel companyModel = remoteSecurityService
				.listUserByCompanyId1(reginParams.getCompany().getSequenceNbr());

		List children = (List) companyModel.getChildren();

		List<DepartmentUserTreeWebVo> list = Lists.newArrayList();

		for (int i = 0; i < children.size(); i++) {
			Map<String, Object> map = (LinkedHashMap) children.get(i);
			JSONObject json = JSON.parseObject(JSON.toJSONString(map));
			DepartmentUserTreeWebVo deptTreeWeb = new DepartmentUserTreeWebVo();
			JSONArray childrens = json.getJSONArray("children");

			deptTreeWeb.setType("department");
			deptTreeWeb.setKey(map.get("sequenceNbr").toString());
			deptTreeWeb.setLabel(map.get("sequenceNbr").toString());
			deptTreeWeb.setTitle(map.get("departmentName").toString());
			deptTreeWeb.setValue(map.get("sequenceNbr").toString());
			if (!ObjectUtils.isEmpty(map.get("userModelList"))) {
				deptTreeWeb.setUserModelList((List) map.get("userModelList"));
			}
			list.add(deptTreeWeb);
			if (childrens != null && childrens.size() > 0) {
				buildUserDeptTreeForWebBefore(list, childrens);
			}

		}

		list = buildUserDeptTreeForWeb(list);

		return list;
	}

	/**
	 * 部门数据预处理（获取所有子节点）
	 *
	 * @param list
	 * @param children
	 */
	private void buildUserDeptTreeForWebBefore(List<DepartmentUserTreeWebVo> list, JSONArray children) {
		for (int i = 0; i < children.size(); i++) {
			JSONObject json = children.getJSONObject(i);

			DepartmentUserTreeWebVo deptTreeWeb = new DepartmentUserTreeWebVo();

			Map deptMap = JSONObject.parseObject(json.toJSONString(), Map.class);
			deptTreeWeb.setType("department");
			deptTreeWeb.setKey(deptMap.get("sequenceNbr").toString());
			deptTreeWeb.setLabel(deptMap.get("sequenceNbr").toString());
			deptTreeWeb.setTitle(deptMap.get("departmentName").toString());
			deptTreeWeb.setValue(deptMap.get("sequenceNbr").toString());
			if (!ObjectUtils.isEmpty(deptMap.get("userModelList"))) {
				deptTreeWeb.setUserModelList((List) deptMap.get("userModelList"));
			}

			if (json != null && json.size() > 0) {
				list.add(deptTreeWeb);
			} else {

				JSONArray childrens =json!=null? json.getJSONArray("children"):null;
				if (childrens != null && childrens.size() > 0) {
					buildUserDeptTreeForWebBefore(deptTreeWeb.getChildren(), childrens);
				}
				if ("0".equals(deptMap.get("parentId"))) {
					list.add(deptTreeWeb);
				}
			}
		}
	}

	/**
	 * 重构数据，用户存放在部门的children
	 *
	 * @param list
	 * @return
	 */
	private List<DepartmentUserTreeWebVo> buildUserDeptTreeForWeb(List<DepartmentUserTreeWebVo> list) {
		list.forEach(x -> {
			List<DepartmentUserTreeWebVo> users = Lists.newArrayList();

			if (!ObjectUtils.isEmpty(x.getUserModelList())) {

				List<DepartmentUserTreeWebVo> collects = x.getUserModelList().stream().collect(Collectors.toList());
				List<Map<String, Object>> userModelList = (List) collects;

				userModelList.forEach(userModel -> {
					DepartmentUserTreeWebVo userTreeWeb = new DepartmentUserTreeWebVo();

					userTreeWeb.setType("user");
					userTreeWeb.setKey(userModel.get("userId").toString() + "*" + UUID.randomUUID().toString());
					userTreeWeb.setLabel(userModel.get("realName").toString());
					userTreeWeb.setTitle(userModel.get("realName").toString());
					userTreeWeb.setValue(userModel.get("userId").toString() + "*" + UUID.randomUUID().toString());
					users.add(userTreeWeb);
				});
				x.setChildren(users);
				collects.clear();
				x.setUserModelList(collects);
			}
		});
		return list;
	}

	private void buildUserDeptTreeForWeb(List<DepartmentUserTreeWebVo> list, JSONArray children) {
		for (int i = 0; i < children.size(); i++) {
			JSONObject json = children.getJSONObject(i);
			if (json != null && json.size() > 0) {
				if ("user".equals(json.getString("type"))) {
					DepartmentUserTreeWebVo userTreeWeb = new DepartmentUserTreeWebVo();
					userTreeWeb.setType("user");
					Map map = JSONObject.parseObject(json.getString("object"), Map.class);
					userTreeWeb.setKey(map.get("userId") + "");
					userTreeWeb.setLabel(map.get("realName") + "");
					userTreeWeb.setTitle(map.get("realName") + "");
					userTreeWeb.setValue(map.get("userId") + "");
					list.add(userTreeWeb);
				} else {

					DepartmentUserTreeWebVo deptTreeWeb = new DepartmentUserTreeWebVo();

					Map map = JSONObject.parseObject(json.getString("object"), Map.class);
					deptTreeWeb.setType("department");
					deptTreeWeb.setKey(map.get("sequenceNbr") + "");
					deptTreeWeb.setLabel(map.get("sequenceNbr") + "");
					deptTreeWeb.setTitle(map.get("departmentName") + "");
					deptTreeWeb.setValue(map.get("sequenceNbr") + "");

					JSONArray childrens = json.getJSONArray("children");
					if (childrens != null && childrens.size() > 0) {
						buildUserDeptTreeForWeb(deptTreeWeb.getChildren(), childrens);

					}
					if ("0".equals(map.get("parentId"))) {
						list.add(deptTreeWeb);
					}
				}
			}
		}
	}

	private void buildUserDeptTreeForWeb1(List<DepartmentUserTreeWebVo> list, JSONArray children) {
		for (int i = 0; i < children.size(); i++) {
			JSONObject json = children.getJSONObject(i);
			if (json != null && json.size() > 0) {
				if (!ObjectUtils.isEmpty(json.getString("userModelList"))) {
					DepartmentUserTreeWebVo userTreeWeb = new DepartmentUserTreeWebVo();
					userTreeWeb.setType("user");
					Map map = JSONObject.parseObject(json.getString("userModelList"), Map.class);
					userTreeWeb.setKey(map.get("userId") + "");
					userTreeWeb.setLabel(map.get("realName") + "");
					userTreeWeb.setTitle(map.get("realName") + "");
					userTreeWeb.setValue(map.get("userId") + "");
					list.add(userTreeWeb);
				} else {

					DepartmentUserTreeWebVo deptTreeWeb = new DepartmentUserTreeWebVo();

					Map map = JSONObject.parseObject(json.getString("object"), Map.class);
					deptTreeWeb.setType("department");
					deptTreeWeb.setKey(map.get("sequenceNbr") + "");
					deptTreeWeb.setLabel(map.get("sequenceNbr") + "");
					deptTreeWeb.setTitle(map.get("departmentName") + "");
					deptTreeWeb.setValue(map.get("sequenceNbr") + "");

					JSONArray childrens = json.getJSONArray("children");
					if (childrens != null && childrens.size() > 0) {
						buildUserDeptTreeForWeb(deptTreeWeb.getChildren(), childrens);

					}
					if ("0".equals(map.get("parentId"))) {
						list.add(deptTreeWeb);
					}
				}
			}
		}
	}

	private void buildUserDeptTreeForWeb2(List<DepartmentUserTreeWebVo> list, JSONArray children) {
		for (int i = 0; i < children.size(); i++) {
			JSONObject json = children.getJSONObject(i);
			if (json != null && json.size() > 0) {
				if ("user".equals(json.getString("type"))) {
					DepartmentUserTreeWebVo userTreeWeb = new DepartmentUserTreeWebVo();
					userTreeWeb.setType("user");
					Map map = JSONObject.parseObject(json.getString("object"), Map.class);
					userTreeWeb.setKey(map.get("userId") + "");
					userTreeWeb.setLabel(map.get("realName") + "");
					userTreeWeb.setTitle(map.get("realName") + "");
					userTreeWeb.setValue(map.get("userId") + "");
					list.add(userTreeWeb);
				}

			}

			JSONArray childrens = json.getJSONArray("children");
			if (childrens != null && childrens.size() > 0) {
				buildUserDeptTreeForWeb(list, childrens);
			}
		}

	}

	/**
	 * 查询用户权限人员
	 *
	 * @return
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "人员查询", notes = "人员查询")
	@RequestMapping(value = "/queryAuthUsers", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<LinkedHashMap<String, Object>> queryAllUser() {
		ReginParams reginParams = getSelectedOrgInfo();
		String loginOrgCode = getOrgCode(reginParams);
		List<AgencyUserModel> userModels = remoteSecurityService.listUserByOrgCode(loginOrgCode);
		List<LinkedHashMap<String, Object>> userList = paraseData(userModels, null);
		return userList;
	}

	/**
	 * 查询用户部门人员树
	 *
	 * @return
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "部门人员树查询", notes = "部门人员树查询")
	@RequestMapping(value = "/queryDeptUserTree", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<LinkedHashMap<String, Object>> queryDeptUserTree() {
		ReginParams reginParams = getSelectedOrgInfo();
		Long departmentId = Long.valueOf(getDepartmentId(reginParams));
		List<AgencyUserModel> userModels = remoteSecurityService.listUserByDepartmentId(departmentId);
		List<LinkedHashMap<String, Object>> userList = paraseData(userModels, null);
		return userList;
	}

	/**
	 * 查询用户部门人员树
	 *
	 * @return
	 * @RequestParam userName 用户名
	 */

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "通讯录(<font color='blue'>手机app</font>)", notes = "通讯录(<font color='blue'>手机app</font>)")
	@RequestMapping(value = "/queryUserAddressList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<LinkedHashMap<String, Object>> queryUserAddressListTree(
			@ApiParam(value = "用户名") @RequestParam(value = "userName", required = false) String userName) {
		ReginParams reginParams = getSelectedOrgInfo();
		Long companyId = Long.valueOf(getCompanyId(reginParams));
		List<DepartmentModel> treeBos = remoteSecurityService.getDepartmentTreeByCompanyId(companyId);
		List<LinkedHashMap<String, Object>> content = new ArrayList<>();
		return content;
	}

	private List<LinkedHashMap<String, Object>> paraseData(List<AgencyUserModel> list, String userNmae) {
		List<LinkedHashMap<String, Object>> userList = new ArrayList<>();
		if (!ObjectUtils.isEmpty(list)) {
			for (AgencyUserModel userModel : list) {
				LinkedHashMap<String, Object> user = new LinkedHashMap<>();
				user.put("id", userModel.getUserId());
				user.put("key", userModel.getUserId());
				user.put("value", userModel.getUserId());
				user.put("checked", false);
				user.put("state", "open");
				user.put("name", userModel.getRealName());
				user.put("desc", null);
				user.put("writeable", 0);
				user.put("userName", userModel.getUserId());
				user.put("mobile", userModel.getMobile());
				user.put("telephone", userModel.getLandlinePhone());
				user.put("departmentName", "其他");
				userList.add(user);
			}
		}

		return userList;
	}

	private List<LinkedHashMap<String, Object>> filterUser(List<LinkedHashMap<String, Object>> tempChildren,
			String userNmae) {
		List<LinkedHashMap<String, Object>> userList = new ArrayList<LinkedHashMap<String, Object>>();
		if (ObjectUtils.isEmpty(tempChildren)) {
			return userList;
		}
		userList.forEach((item) -> {
			if (!ObjectUtils.isEmpty(userNmae) && item.get("label").toString().indexOf(userNmae) != -1) {
				userList.add(item);
			}
		});
		return userList;
	}

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "用户登录成功之后数据初始化(<font color='blue'>手机app</font>)", notes = "用户登录成功之后数据初始化")
	@RequestMapping(value = "/initData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public ResponseModel initUserApp() {
		try {
			ReginParams reginParams = getSelectedOrgInfo();
			CommonResponse secResponse = remoteSecurityService
					.searchPermissionTree(Long.valueOf(reginParams.getRole().getSequenceNbr()), appType);
			if (!secResponse.isSuccess()) {
				return CommonResponseUtil.failure("权限获取失败");
			}
			List<LinkedHashMap<String, Object>> response = new ArrayList<>();
			HashMap<String, Object> resp = new HashMap<>();
			resp.put("permissionitems", secResponse.getDataList());
			resp.put("companys", response);
			return CommonResponseUtil.success(resp);
		} catch (Exception e) {
			return CommonResponseUtil.failure("数据初始化失败");
		}
	}

	/////////////////////////////// 2019-11-18安全服务升级///////////////////////////////

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "通讯录", notes = "通讯录")
	@RequestMapping(value = "/mobile/addressList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public ResponseModel addressList() {
		try {

			ReginParams reginParams = getSelectedOrgInfo();
			CompanyBo companyBo = reginParams.getCompany();
			JSONArray arr = remoteSecurityService.listDepartmentUserTree(companyBo.getSequenceNbr());
			DepartmentUserTreeAppVo departmentUserTreeDto = new DepartmentUserTreeAppVo();
			if (arr != null && arr.size() > 0) {

				buildUserDeptTree(departmentUserTreeDto, arr);
			}
			DepartmentUserTreeAppVo qi = new DepartmentUserTreeAppVo();
			List<DepartmentUserTreeAppVo> list = departmentUserTreeDto.getChildren();
			List<DepartmentUserTreeAppVo> listdate = new ArrayList<>();
			for (DepartmentUserTreeAppVo departmentUserTreeAppVo : list) {
				if ("其他".equals(departmentUserTreeAppVo.getName())) {
					qi = departmentUserTreeAppVo;
					qi.setId("-0");
					qi.setType("dep");
				} else {
					listdate.add(departmentUserTreeAppVo);
				}
			}
			if (qi != null) {
				listdate.add(qi);
			}
			return CommonResponseUtil.success(listdate);
		} catch (Exception e) {
			logger.error("通讯录异常", e);
			return CommonResponseUtil.failure("系统繁忙，请稍后再试");
		}
	}

	private void buildUserDeptTree(DepartmentUserTreeAppVo deptUser, JSONArray childs) {
		for (int i = 0; i < childs.size(); i++) {
			JSONObject json = childs.getJSONObject(i);
			DepartmentUserTreeAppVo treeDto = new DepartmentUserTreeAppVo();
			treeDto.setName(json.getString("departmentName"));
			treeDto.setId(json.getString("sequenceNbr"));

			treeDto.setType(json.getString("level"));

			JSONArray childrens = json.getJSONArray("children");
			if (childrens != null && childrens.size() > 0) {
				buildUserDeptTree(treeDto, childrens);
			}
			JSONArray userModelList = json.getJSONArray("userModelList");
			if (userModelList != null && userModelList.size() > 0) {

				UserDeptTree(treeDto, userModelList);
			}

			deptUser.getChildren().add(treeDto);
		}
	}

	// 部门下用户

	private void UserDeptTree(DepartmentUserTreeAppVo deptUser, JSONArray childs) {

		for (int i = 0; i < childs.size(); i++) {
			JSONObject json = childs.getJSONObject(i);
			DepartmentUserTreeAppVo treeDto = new DepartmentUserTreeAppVo();
			treeDto.setName(json.getString("realName"));
			treeDto.setId(json.getString("userId"));
			treeDto.setType("user");
			Map<String, String> user = Maps.newHashMap();
			user.put("telephone", json.getString("mobile"));
			user.put("email", json.getString("email"));
			treeDto.setObject(user);
			deptUser.getChildren().add(treeDto);
		}
	}

	/**
	 * APP登录
	 */
	@TycloudOperation(ApiLevel = UserType.PUBLIC, needAuth = false)
    @ApiOperation(value = "APP登录", notes = "APP登录")
	@PostMapping(value = "/mobile/login")
	public ResponseModel mobileLogin(@ApiParam(value = "账号", required = true) @RequestBody AppLoginUserParam param) {

		try {
			JSONObject jsonObject = remoteSecurityService.loginFromApp(param.getUserName(), param.getPassword());
			if (jsonObject != null) {
				JSONObject result = new JSONObject();
				result.put("token", jsonObject.getString("token"));
				result.put("userId", jsonObject.getString("userId"));
				result.put("appKey", jsonObject.getString("appKey"));
				result.put("product", jsonObject.getString("product"));
				result.put("jpushUserKey", AppMessagePushService.buildJpushUserKey(jsonObject.getString("userId")));
				return CommonResponseUtil.success(result);
			}
			return CommonResponseUtil.failure("登录失败");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("APP登录异常", e);
			return CommonResponseUtil.failure("系统繁忙，请稍后再试");
		}
	}

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "别名关联设备", notes = "别名关联设备")
	@PostMapping(value = "/PushDeviceRegistration/{registrationId}/{alias}")
	public ResponseModel pushDevice(@PathVariable String registrationId, @PathVariable String alias) {
		try {
			CommonResponse commonResponse = PushFeign.PushDeviceRegistration(registrationId, alias);
			if ("SUCCESS".equals(commonResponse.getResult())) {
				return CommonResponseUtil.success("成功");
			}
			return CommonResponseUtil.failure("失败");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure("失败");
		}
	}

	/**
	 * APP登出
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "APP登出", notes = "APP登出")
	@PostMapping(value = "/mobile/loginOut")
	public ResponseModel mobileLoginOut() {
		try {
			if (remoteSecurityService.loginOutFromApp(getToken(), getProduct(), getAppKey())) {
				return CommonResponseUtil.success();
			} else {
				throw new RuntimeException("APP登出失败");

			}
		} catch (Exception e) {
			logger.error("APP登出异常", e);
			throw new RuntimeException("系统繁忙，请稍后再试");
		}
	}

	/**
	 * 获取公司选择信息
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取公司选择信息", notes = "获取公司选择信息")
	@GetMapping(value = "/selectInfo")
	public JSONObject selectInfo() {
		try {
			JSONObject result = new JSONObject();
			AgencyUserModel user = getUserInfo();
			if (user != null) {
				List<CompanyModel> list = user.getCompanys();
				Map<Long, List<DepartmentModel>> mapDepartments = user.getCompanyDepartments();
				Map<String, List<Map<String, Object>>> mapdate = new HashMap<String, List<Map<String, Object>>>();
				List<Map> listCompanyModel = new ArrayList();
				if (list != null && list.size() > 0) {
					for (CompanyModel article : list) {
						Map<String, Object> map = objectToMap(article);
						map.put("companySeq", map.get("sequenceNbr") + "");
						map.put("parentId", map.get("parentId") + "");
						listCompanyModel.add(map);
						long key = Long.valueOf(map.get("sequenceNbr").toString());
						List<DepartmentModel> listdep = mapDepartments.getOrDefault(key,new ArrayList<>());
						List<Map<String, Object>> dep = new ArrayList();
						for (DepartmentModel departmentModel : listdep) {
							if (departmentModel != null) {
								Map<String, Object> mapo = objectToMap(departmentModel);
								mapo.put("sequenceNbr", mapo.get("sequenceNbr").toString());
								dep.add(mapo);
							}
						}
						mapdate.put(map.get("sequenceNbr").toString(), dep);
					}
				}
				Map<String, Object> mapRoles = objectToMap(user.getOrgRoles());

				result.put("userModel", user);
				result.put("companys", listCompanyModel);
				result.put("orgRoles", user.getOrgRoles());
				result.put("companyDepartments", mapdate);
				return result;
			} else {
				throw new RuntimeException("请重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取公司选择信息异常", e);
			throw new RuntimeException(e.getMessage());
		}
	}

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "部门人员树查询", notes = "部门人员树查询")
	@RequestMapping(value = "/queryDeptUserTree2", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public List<DepartmentUserTreeWebVo> queryDeptUserTree2() {
		ReginParams reginParams = getSelectedOrgInfo();
		CompanyModel companyModel = remoteSecurityService
				.listUserByCompanyId1(reginParams.getCompany().getSequenceNbr());
		List children = (List) companyModel.getChildren();
		List<DepartmentUserTreeWebVo> list = Lists.newArrayList();
		for (int i = 0; i < children.size(); i++) {
			Map<String, Object> map = (LinkedHashMap) children.get(i);
			JSONObject json = JSON.parseObject(JSON.toJSONString(map));
			DepartmentUserTreeWebVo deptTreeWeb = new DepartmentUserTreeWebVo();
			JSONArray childrens = json.getJSONArray("children");
			deptTreeWeb.setType("department");
			deptTreeWeb.setKey(map.get("sequenceNbr").toString());
			deptTreeWeb.setLabel(map.get("sequenceNbr").toString());
			deptTreeWeb.setTitle(map.get("departmentName").toString());
			deptTreeWeb.setValue(map.get("sequenceNbr").toString());
			if (!ObjectUtils.isEmpty(map.get("userModelList"))) {
				deptTreeWeb.setUserModelList((List) map.get("userModelList"));
			}
			list.add(deptTreeWeb);
			if (childrens != null && childrens.size() > 0) {
				buildUserDeptTreeForWebBefore(list, childrens);
			}
		}
		list = buildUserDeptTreeForWeb(list);
		return list;
	}

	// 对象转map

	public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
		Map<String, Object> map = new HashMap<String, Object>();
		if (obj != null) {
			Class<?> clazz = obj.getClass();
			for (Field field : clazz.getDeclaredFields()) {
				ReflectionUtils.makeAccessible(field);
				String fieldName = field.getName();
				Object value = nvl(field.get(obj));

				if (fieldName.equals("sequenceNbr")) {
					map.put(fieldName, value + "");
				} else if (fieldName.equals("companySeq")) {
					map.put(fieldName, value + "");
				} else if (fieldName.equals("children")) {
					map.put(fieldName, value);
				} else {
					map.put(fieldName, value);
				}

			}
			return map;
		}
		return map;
	}

	public static Object nvl(Object param) {
		return param != null ? param : "";
	}

	/**
	 * 保存登陆用户选择公司信息
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "保存登陆用户选择公司信息", notes = "保存登陆用户选择公司信息")
	@PostMapping(value = "/save/curCompany")
	public JSONObject saveCurCompany(
			@ApiParam(value = "当前登陆用户所选单位机构编号", required = true) @RequestBody SelectUserInfo selectUserInfo) {
		try {
			AgencyUserModel user = getUserInfo();

			CompanyBo company = new CompanyBo();
			DepartmentBo department = new DepartmentBo();
			RoleBo role = new RoleBo();
			if(ObjectUtils.isEmpty(selectUserInfo.getCompanyModel())){
				CompanyModel companyM = user.getCompanys().get(0);
				Bean.copyExistPropertis(companyM,company);

				Map<Long, List<DepartmentModel>> mapDepartments = user.getCompanyDepartments();
				DepartmentModel departmentM = mapDepartments.get(companyM.getSequenceNbr()).get(0);
				Bean.copyExistPropertis(departmentM,department);
				Map<Long, List<RoleModel>> roles = user.getOrgRoles();
				RoleModel roleM = roles.get(departmentM.getSequenceNbr()).get(0);

				Bean.copyExistPropertis(roleM,role);
				selectUserInfo.setCompanyModel(company);
				selectUserInfo.setDepartmentModel(department);
				selectUserInfo.setRoleModel(role);
			}else{
				company = selectUserInfo.getCompanyModel();
				role = selectUserInfo.getRoleModel();
				department = selectUserInfo.getDepartmentModel();
			}
			ReginParams reginParams = new ReginParams();
			reginParams.setUserModel(user);
			reginParams.setCompany(company);
			reginParams.setRole(role);
			reginParams.setDepartment(department);
			saveSelectedOrgInfo(reginParams);
			return buildCurCompany(selectUserInfo, user);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存登陆用户选择公司信息异常", e);
			throw new RuntimeException("系统繁忙，请稍后再试");
		}
	}

	private JSONObject buildCurCompany(SelectUserInfo selectUserInfo, AgencyUserModel user) {
		JSONObject result = new JSONObject();
		result.put("userId", user.getUserId());
		result.put("realName", user.getRealName());
		result.put("userMobile", user.getMobile());
		result.put("userName", user.getUserName());
		result.put("email", user.getEmail());

		CommonResponse secResponse = remoteSecurityService
				.searchPermissionTree(selectUserInfo.getRoleModel().getSequenceNbr(), appType);
		List<JSONObject> listp = new ArrayList<>();
		if (secResponse.isSuccess() && secResponse.getDataList() != null) {
			JSONArray arr = JSON.parseArray(JSONArray.toJSONString(secResponse.getDataList()));
			Map<String, JSONObject> map = Maps.newHashMap();

			if (arr != null && arr.size() > 0) {
				JSONObject obj = arr.getJSONObject(0);
				if (obj != null) {
					JSONArray childrens = obj.getJSONArray("children");
					if (childrens != null && childrens.size() > 0) {
						for (int i = 0; i < childrens.size(); i++) {
							JSONObject child = childrens.getJSONObject(i);
							// map.put(child.getString("path"), child);
							listp.add(child);
						}
					}
				}

				// result.put("userPower", map.get("app"));
			}
		}
//		LinkedHashMap <String,HashMap<String,Object>> map = (LinkedHashMap<String, HashMap<String, Object>>) patrolFeign.getPatrolCount(RequestContext.getAppKey(),RequestContext.getProduct(),RequestContext.getToken());
//		if(Constant.RESULT_SUCCESS.equals(map.get("result"))){
//			result.put("userHaveToDo", map.get("dataList"));
//		}else{
//			result.put("userHaveToDo", new ArrayList<>());
//		}
		result.put("userPower", JSON.toJSON(listp));
		result.put("companyModel", selectUserInfo.getCompanyModel());
		result.put("departmentModel", selectUserInfo.getDepartmentModel());
		result.put("roleModel", selectUserInfo.getRoleModel());
		return result;
	}

	/**
	 * 修改密码
	 */
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = " 修改密码", notes = " 修改密码")
	@PostMapping(value = "editPassword")
	public ResponseModel editPassword(@ApiParam(value = "旧密码", required = true) @RequestParam String password,
			@ApiParam(value = "新密码", required = true) @RequestParam String newPassword) {

		AgencyUserModel userModel = getUserInfo();
		boolean flag = false;
		if (password.equals(newPassword)) {
			throw new RuntimeException("新密码不能跟旧密码相同！");
		}
		try {

			AgencyUserModel agencyUserModel = new AgencyUserModel();
			agencyUserModel.setPassword(newPassword);
			agencyUserModel.setRePassword(newPassword);
			agencyUserModel.setOriginalPassword(password);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.set("Content-Type", "application/json");
			headers.set("product", getProduct());
			headers.set("token", getToken());
			headers.set("appKey", getAppKey());
			HttpEntity httpEntity = new HttpEntity<>(agencyUserModel, headers);
			ResponseEntity<FeignClientResult> feignClientResult = restTemplate.exchange(
					"http://" + SecurityName + "/privilege/v1/agencyuser/" + userModel.getUserId() + "/password",
					HttpMethod.PUT, httpEntity, FeignClientResult.class);
			if (feignClientResult.getBody().getStatus() == 200) {
				ResponseModel dates = CommonResponseUtil.success();
				dates.setMessage("修改成功！");
				return dates;
			} else {
				throw new RuntimeException(feignClientResult.getBody().getMessage());
			}

		} catch (Exception e) {
			logger.error("修改密码异常", e);
			throw new RuntimeException("修改密码异常");
		}
	}

	/**
	 *
	 * 获取字典
	 *
	 */

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询指定的字典信息", notes = "查询指定的字典信息")
	@GetMapping(value = "listDictionaryByDictCode/{dictCode}")
	public List<DictionarieValueModel> listDictionaryByDictCode(@PathVariable String dictCode) {
		try {
			List<DictionarieValueModel> list = remoteSecurityService.listDictionaryByDictCode(dictCode);

			return list;
		} catch (Exception e) {

			throw new RuntimeException();
		}
	}

	/**
	 *
	 *
	 * 上传图片到平台
	 *
	 **/
	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "文件上传(<font color='blue'>release</font>)", notes = "文件上传")
	@RequestMapping(value = "/upload-file", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ResponseModel uploadFile(@RequestParam("file") MultipartFile file) {

		FeignClientResult<Map<String, String>> date = remoteSecurityService.fileImage(file);
		Map<String, String> map1 = new HashMap<>();
		if (date != null) {
			Map<String, String> map = date.getResult();
			Iterator<String> it = map.keySet().iterator();

			while (it.hasNext()) {
				map1.put("url", it.next());
			}

		}
		return CommonResponseUtil.success(map1);
	}

	    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "文件上传(<font color='blue'>release</font>)", notes = "文件上传")
	@RequestMapping(value = "/upload-files", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ResponseModel uploadFile(@RequestParam("files") MultipartFile[] files) throws IOException {

		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("multipart/form-data");
		headers.setContentType(type);
		headers.set("product", getProduct());
		headers.set("token", getToken());
		headers.set("appKey", getAppKey());
		// 设置请求体，注意是LinkedMultiValueMap
		MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
		List<Object> fileList = new ArrayList<>();
		for (MultipartFile file : files) {
			ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) {
				@Override
				public String getFilename() throws IllegalStateException {
					return file.getOriginalFilename();
				}
			};
			fileList.add(byteArrayResource);
		}

		form.put("files", fileList);

		// 用HttpEntity封装整个请求报文
		HttpEntity<MultiValueMap<String, Object>> files1 = new HttpEntity<>(form, headers);

		ResponseEntity<String> responseEntity = restTemplate.exchange(
				"http://" + systemctl + "/systemctl/v1/filestorage/image", HttpMethod.POST, files1, String.class);

		JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
		Integer status = jsonObject.getInteger("status");
		if (status!= 200){
			return CommonResponseUtil.failure();
		}

		Map<String, String> map1 = new HashMap<>();
		if (jsonObject != null && !"".equals(jsonObject.get("result"))) {
			Map<String, String> map = JSON.parseObject(jsonObject.get("result").toString(), Map.class);
			Iterator<String> it = map.keySet().iterator();
			String url = "";
			while (it.hasNext()) {
				url = url + it.next() + ",";
			}
			map1.put("url", url);
		}
		return CommonResponseUtil.success(map1);
	}

}