package cn.myapps.runtime.usersetup.controller;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.domain.model.DomainVO;
import cn.myapps.authtime.user.UserUtil;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.data.DataPackage;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.model.sysconfig.LoginConfig;
import cn.myapps.common.model.workflow.BillDefiVO;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.Security;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.workflow.definition.service.BillDefiDesignTimeService;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.workflow.storage.runtime.proxy.ejb.WorkflowProxyProcess;
import cn.myapps.runtime.workflow.storage.runtime.proxy.ejb.WorkflowProxyProcessBean;
import cn.myapps.runtime.workflow.storage.runtime.proxy.ejb.WorkflowProxyVO;
import cn.myapps.support.weixin.WeixinServiceProxy;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.saas.core.utils.RSAUtils;
import com.bcxin.saas.core.utils.SecurityUtil;
import com.bcxin.saas.core.utils.encrypt.PasswordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.jayway.jsonpath.JsonPath.parse;

/**
 * 个人设置
 * @author spy
 */
@Api(tags = "个人设置执行模块")
@Component
@RequestMapping(path = "/api/runtime", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserSetupController extends AbstractRuntimeController{

	/**
	 * 更新密码
	 * @param jsonStr 请求包体
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/usersetups/password")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "更新密码", notes = "更新密码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "jsonStr",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Resource setUserPassword(@RequestBody String jsonStr) throws Exception{
		WebUser user = getUser();

		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		String oldPassword = jsonObject.getString("oldPassword");
		try {
			oldPassword = RSAUtils.decrypt(oldPassword);
		}catch (Exception e){
			String oldPasswordLp = oldPassword.substring(0, oldPassword.length() - 2);
			String oldPasswordRp = oldPassword.substring(oldPassword.length() - 2, oldPassword.length());
			oldPassword = Security.decodeBASE64(oldPasswordRp + oldPasswordLp);
		}


		String newpassword = jsonObject.getString("newpassword");
		try {
			newpassword = RSAUtils.decrypt(newpassword);
		}catch (Exception e){
			String newpasswordLp = newpassword.substring(0, newpassword.length() - 2);
			String newpasswordRp = newpassword.substring(newpassword.length() - 2, newpassword.length());
			newpassword = Security.decodeBASE64(newpasswordRp + newpasswordLp);
		}

		//newpassword = Security.decodeBASE64(newpassword);

		String confirmPassword = jsonObject.getString("confirmPassword");
		try {
			confirmPassword = RSAUtils.decrypt(confirmPassword);
		}catch (Exception e){
			String confirmPasswordLp = confirmPassword.substring(0, confirmPassword.length() - 2);
			String confirmPasswordRp = confirmPassword.substring(confirmPassword.length() - 2, confirmPassword.length());
			confirmPassword = Security.decodeBASE64(confirmPasswordRp + confirmPasswordLp);
		}

		//confirmPassword = Security.decodeBASE64(confirmPassword);

		UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
		UserVO userVO = (UserVO) userProcess.doView(user.getId());

		PropertyUtil.reload("passwordLegal");
		String passwordArrayLengthString = PropertyUtil
				.get(LoginConfig.LOGIN_PASSWORD_UPADTE_TIMES);
		int passwordArrayLength = StringUtil
				.isNumber(passwordArrayLengthString)
				? StringUtil.parseInt(passwordArrayLengthString)
				: 0;
		if(passwordArrayLength!=0){
			UserVO po = (UserVO) userProcess.doView(userVO.getId());
			String oldPasswordArray = "";
			oldPasswordArray = po.getPasswordArray();

			String pwda[] = null;
			int oldpasswordArrayLength = 0;
			if (oldPasswordArray != null) {
				pwda = oldPasswordArray.split(",");
				oldpasswordArrayLength = oldPasswordArray.split(",").length;
			}

			String passwordArray = null;

			if(!StringUtil.isBlank(newpassword) && !newpassword.trim().equals(Web.DEFAULT_SHOWPASSWORD)){
				if(!newpassword.trim().equals(confirmPassword)){//密码二次确认验证
					return error(4001, "{*[cn.myapps.core.personalsettings.basic.lable.ComfirmAndPasswordNotSame]*}", null);
				}
				String password = po.getLoginpwd();
				boolean oldPasswordFlag = false;
				if(PasswordUtils.initVerify(oldPassword.trim(), password)){//原密码验证
					oldPasswordFlag = true;
				}
				if(oldPassword.trim().equals(decrypt(password))){
					oldPasswordFlag = true;
				}
				if(PasswordUtils.validatePassword(oldPassword.trim(), password)){
					oldPasswordFlag = true;
				}
				if(!oldPasswordFlag){
					if(!oldPassword.trim().equals(decrypt(password))){//原密码验证
						return error(4001, "{*[cn.myapps.core.personalsettings.basic.lable.originalPasswordError]*}", null);
					}
				}
			}
			if ((!PasswordUtils.initVerify(newpassword.trim(), po.getLoginpwd())||!PasswordUtils.validatePassword(newpassword.trim(), po.getLoginpwd()) || !newpassword.trim().equals(decrypt(po.getLoginpwd())))
					&& !newpassword.trim().equals(Web.DEFAULT_SHOWPASSWORD)) {
				if (oldPasswordArray != null) {
					for (int i = 0; i < oldpasswordArrayLength; i++) {
						if (newpassword.equals(decrypt(pwda[i]))) {
							return error(4001, "{*[ModifyPasswordNotSame]*}：" + passwordArrayLengthString, null);
						}
					}
					passwordArray = oldPasswordArray + "," + encrypt(newpassword);
				} else {
					passwordArray = po.getLoginpwd() + ","
							+ encrypt(newpassword);
				}
				userVO.setLastModifyTime(new Date());

			} else {
				passwordArray = po.getPasswordArray();
				userVO.setLastModifyTime(po.getLastModifyTime());
			}
			if (oldpasswordArrayLength + 1 > passwordArrayLength) {
				int i1 = passwordArray.split(",").length;
				String passwordArraytmp = "";
				for (int i = i1 - passwordArrayLength - 1; i < i1; i++) {
					passwordArraytmp += "," + passwordArray.split(",")[i];
				}
				passwordArray = passwordArraytmp.substring(1);
			}

			String passwordLength = PropertyUtil.get(LoginConfig.LOGIN_PASSWORD_LENGTH);
			if (!StringUtil.isBlank(newpassword) && passwordLength != null && !passwordLength.trim().equals("")) {
				int length = Integer.parseInt(passwordLength);
				if(newpassword.length()<length){                         //判断密码长度
					return error(4001, "{*[PasswordLengthCanNotLow]*}"+length, null);
				}
			}
			String legal = PropertyUtil.get(LoginConfig.LOGIN_PASSWORD_LEGAL);
			if (legal.equals("1") || legal == "1") {

				//修改密码策略为数字、字母、特殊字符(#@!~%^&*?.)
				// Pattern p = Pattern.compile("[a-zA-Z0-9]*[a-zA-Z]+[0-9]+[a-zA-Z0-9]*");
				// Pattern p1 = Pattern.compile("[a-zA-Z0-9]*[0-9]+[a-zA-Z]+[a-zA-Z0-9]*");
				// 数字、字母、特殊字符
				// Pattern p2 = Pattern.compile("(?=.*[a-zA-Z])(?=.*\\d)(?=.*[#@!~%^$&*\\?\\.])[a-zA-Z\\d#@!~%^$&*\\?\\.]*");
				Pattern p = Pattern.compile("^(?=.*\\d)(?=.*[a-z]).{8,}$");
				Matcher matcher = p.matcher(newpassword);
				//Matcher matcher1 = p1.matcher(password);
				//Matcher matcher2 = p2.matcher(password);

				boolean result = matcher.matches();
				//boolean result1 = matcher1.matches();
				//boolean result2 = matcher2.matches();

				if ((!result)) {
					return error(4001, "密码必须由英文,特殊字符和数字构成", null);
				}

			}

			userVO.setPasswordArray(passwordArray);
		}

		String encodePwd = Security.encodeToBASE64(newpassword);
		String lp = encodePwd.substring(0,2);
		String rp = encodePwd.substring(2, encodePwd.length());
		userVO.setLoginpwd(rp+lp);
		userProcess.doPersonalUpdate(userVO);

		//数据同步到微信端
		if(!DomainVO.WEIXIN_PROXY_TYPE_NONE.equals(userVO.getDomain().getWeixinProxyType())){
			final UserVO _user = userVO ;
			new Thread(new Runnable() {
				public void run() {
					try {
						WeixinServiceProxy.createOrUpdateUser2Weixin(_user);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						try {
							PersistenceUtils.closeSessionAndConnection();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
		//同步其他域
		UserUtil.synUser(userVO, true);
		// 把用户设置赋给webuser
		user.setLoginpwd(userVO.getLoginpwd());
		WebUser.setWebUser(user, request);
		return success("ok", "" );
	}

	/**
	 * 更新个人信息
	 * @param jsonStr 请求包体
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/usersetups/detail")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "更新个人信息", notes = "更新个人信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "jsonStr",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Resource setUserDetail(@RequestBody String jsonStr) throws Exception{
		WebUser user = getUser();
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		String name = jsonObject.getString("name");
		String email = jsonObject.getString("email");
		String telephone = jsonObject.getString("telephone");
		UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
		UserVO userVO = (UserVO) userProcess.doView(user.getId());
		userVO.setName(name);
		userVO.setEmail(email);
		userVO.setTelephone(telephone);
		userProcess.doPersonalUpdate(userVO);

		//数据同步到微信端
		if(!DomainVO.WEIXIN_PROXY_TYPE_NONE.equals(userVO.getDomain().getWeixinProxyType())){
			final UserVO _user = userVO ;
			new Thread(new Runnable() {
				public void run() {
					try {
						WeixinServiceProxy.createOrUpdateUser2Weixin(_user);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						try {
							PersistenceUtils.closeSessionAndConnection();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}

		// 把用户设置赋给webuser
		user.setName(name);
		user.setEmail(email);
		user.setTelephone(telephone);

		WebUser.setWebUser(user, request);

		return success("ok", "");
	}

	/**
	 * 获取代理列表
	 * @param applicationId
	 * 			软件id
	 * @param flowName
	 * 			流程名称
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/usersetups/proxys")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取代理列表", notes = "获取代理列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "flowName",value = "流程名称",required = false,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "pageNo",value = "当前页",required = false,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "linesPerPage",value = "每页显示条数",required = false,paramType = "query",dataType = "string")
	})
	public Resource getUserProxys(@PathVariable String applicationId, @RequestParam(required=false) String flowName, @RequestParam(required=false) String linesPerPage, @RequestParam(required=false) String pageNo) throws Exception{
		ParamsTable params = getParams();
		params.setParameter("application", applicationId);
		params.setParameter("_flowName", flowName);
		if(!StringUtil.isBlank(linesPerPage)){
			int newPageSize = Integer.parseInt(linesPerPage);
			params.setParameter("_pagelines", newPageSize);
		}
		if(!StringUtil.isBlank(pageNo)){
			int newPageNum = Integer.parseInt(pageNo);
			params.setParameter("_currpage", newPageNum);
		}
		WorkflowProxyProcess workflowProcess = new WorkflowProxyProcessBean(applicationId);
		DataPackage<WorkflowProxyVO> result = workflowProcess.doQuery(params, getUser());
		return success("ok", result);
	}

	/**
	 * 获取代理
	 * @param applicationId 软件id
	 * @param id 代理id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/usersetups/proxys/{id}")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取代理", notes = "获取代理")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "id",value = "代理id",required = true,paramType = "path",dataType = "string")
	})
	public Resource getUserProxy(@PathVariable String applicationId, @PathVariable String id) throws Exception{
		WorkflowProxyProcess workflowProcess = new WorkflowProxyProcessBean(applicationId);
		WorkflowProxyVO result = (WorkflowProxyVO) workflowProcess.doView(id);
		return success("ok", result);
	}

	/**
	 * 获取流程列表
	 * @param applicationId 软件id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{applicationId}/usersetups/proxys/flows")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取流程列表", notes = "获取流程列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string")
	})
	public Resource getUserProxyFlowName(@PathVariable String applicationId) throws Exception{
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
//		map.put("", "");
		BillDefiDesignTimeService bp = DesignTimeServiceManager.billDefiDesignTimeService();

		ParamsTable params = getParams();
		String subject = params.getParameterAsString("subject");
		if(StringUtil.isBlank(subject)){
			subject ="";
		}
		Collection<BillDefiVO> flows = bp.getBillDefiByApplication(applicationId);
		for(BillDefiVO bv : flows){
			if(bv.getSubject().contains(subject)) {
				map.put(bv.getId(), bv.getSubject());
			}
		}
		return success("ok", map);
	}

	/**
	 * 保存代理
	 * @param applicationId 软件id
	 * @param id 代理id
	 * @param content 请求包体
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/{applicationId}/usersetups/proxys/save")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "保存代理", notes = "保存代理")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "id",value = "代理id",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "content",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Resource saveUserProxy(@PathVariable String applicationId, @RequestParam(required=false) String id, @RequestBody String content) throws Exception{
		WorkflowProxyProcess workflowProcess = new WorkflowProxyProcessBean(applicationId);
		JSONObject jsonObject = JSONObject.parseObject(content);
		String flowName = jsonObject.getString("flowName");
		String flowId = jsonObject.getString("flowId");
		String description = jsonObject.getString("description");
		String state = jsonObject.getString("state");
		String agents = jsonObject.getString("agents");
		String agentsName = jsonObject.getString("agentsName");
		String owner = jsonObject.getString("owner");
		Date startProxyTime = jsonObject.getDate("startProxyTime");
		Date endProxyTime = jsonObject.getDate("endProxyTime");
		int proxyMode = jsonObject.getIntValue("proxyMode");
		if(!StringUtil.isBlank(flowId)){
			String[] flowIdArr = flowId.split(";");
			String[] flowNameArr = flowName.split(";");
			for (int i = 0; i < flowNameArr.length; i++) {
				WorkflowProxyVO vo;
				if (!StringUtil.isBlank(id)) {
					vo = (WorkflowProxyVO) workflowProcess.doView(id);
				} else {
					vo = new WorkflowProxyVO();
				}
				if (!StringUtil.isBlank(description)) {
					vo.setDescription(description);
				}
				if (!StringUtil.isBlank(state)) {
					vo.setState(state);
				}
				if (!StringUtil.isBlank(agents)) {
					vo.setAgents(agents);
				}
				if (!StringUtil.isBlank(agentsName)) {
					vo.setAgentsName(agentsName);
				}
				if (!StringUtil.isBlank(owner)) {
					vo.setOwner(owner);
				}
				if (startProxyTime!=null && !startProxyTime.equals("")) {
					vo.setStartProxyTime(startProxyTime);
				}
				if (endProxyTime!=null && !endProxyTime.equals("")) {
					vo.setEndProxyTime(endProxyTime);
				}
				vo.setProxyMode(proxyMode);
				vo.setApplicationid(applicationId);
				vo.setDomainid(getUser().getDomainid());
				if(vo.getOwner()==null || vo.getOwner().trim().length()<=0){
					vo.setOwner(getUser().getId());//设置流程代理配置的所有者为当前登陆用户
				}
				vo.setFlowName(flowNameArr[i]);
				vo.setFlowId(flowIdArr[i]);

				if(vo.getId() ==null || vo.getId().trim().length()<=0){
					if(!((WorkflowProxyProcess)workflowProcess).onlyCheckOnFlow(vo)){//流程配置的唯一校验
						return error(40014, "该流程的代理配置信息已存在:" + flowNameArr[i] , null);
					}
					workflowProcess.doCreate(vo);
				}else{
					workflowProcess.doUpdate(vo);
				}
			}
		} else {
			WorkflowProxyVO vo;
			if (!StringUtil.isBlank(id)) {
				vo = (WorkflowProxyVO) workflowProcess.doView(id);
			} else {
				vo = new WorkflowProxyVO();
			}
			if (!StringUtil.isBlank(description)) {
				vo.setDescription(description);
			}
			if (!StringUtil.isBlank(state)) {
				vo.setState(state);
			}
			if (!StringUtil.isBlank(agents)) {
				vo.setAgents(agents);
			}
			if (!StringUtil.isBlank(agentsName)) {
				vo.setAgentsName(agentsName);
			}
			if (!StringUtil.isBlank(owner)) {
				vo.setOwner(owner);
			}
			if (startProxyTime!=null && !startProxyTime.equals("")) {
				vo.setStartProxyTime(startProxyTime);
			}
			if (endProxyTime!=null && !endProxyTime.equals("")) {
				vo.setEndProxyTime(endProxyTime);
			}
			vo.setProxyMode(proxyMode);
			vo.setApplicationid(applicationId);
			vo.setDomainid(getUser().getDomainid());
			if(vo.getOwner()==null || vo.getOwner().trim().length()<=0){
				vo.setOwner(getUser().getId());//设置流程代理配置的所有者为当前登陆用户
			}
			vo.setFlowName("所有流程");
			vo.setFlowId("");
			if(vo.getId() ==null || vo.getId().trim().length()<=0){
				if(!workflowProcess.onlyCheckOnFlow(vo)){//流程配置的唯一校验
					return error(40014, "该流程的代理配置信息已存在", null);
				}
				workflowProcess.doCreate(vo);
			}else{
				workflowProcess.doUpdate(vo);
			}
		}

		return success("ok", "");
	}

	/**
	 * 删除代理
	 * @param applicationId 软件id
	 * @param jsonStr 请求包体
	 * @return
	 * @throws Exception
	 */
	@DeleteMapping("/{applicationId}/usersetups/proxys")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "删除代理", notes = "删除代理")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "applicationId",value = "软件id",required = true,paramType = "path",dataType = "string"),
			@ApiImplicitParam(name = "jsonStr",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Resource deleteUserProxy(@PathVariable String applicationId, @RequestBody String jsonStr) throws Exception{
		List<String> ids= parse(jsonStr).json();
		String[] pks = {};
		pks = ids.toArray(pks);
		WorkflowProxyProcess workflowProcess = new WorkflowProxyProcessBean(applicationId);
		workflowProcess.doRemove(pks);
		return success("ok", "");
	}

	/**
	 * 获取用户所属企业域
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/usersetups/domains")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取用户所属企业域", notes = "获取用户所属企业域")
	public Resource getDomains() throws Exception{
		WebUser webUser = getUser();
		String loginNo = webUser.getLoginno();
		String loginPwd = Security.decryptPassword(webUser.getLoginpwd());
		UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
		DataPackage<UserVO> users = userProcess.queryDataByParamsTable("All", "", loginNo, "", "", "", "", 1, "", null, null, 1, Integer.MAX_VALUE);

		List<DomainVO> result = new ArrayList<DomainVO>();
		for(Iterator<UserVO> iterator = users.datas.iterator();iterator.hasNext();) {
			UserVO user = iterator.next();
			if (StringUtils.hasLength(loginPwd) && loginPwd.equals(Security.decryptPassword(user.getLoginpwd()))) {
				DomainVO domain = user.getDomain();
				if (domain != null && domain.getStatus() == DomainVO.STATE_ACTIVATED) {
					result.add(user.getDomain());
				}
			}
		}

		return success("ok", result);
	}

	/**
	 * 切换企业域
	 * @return
	 * @throws Exception
	 */
	@PutMapping("/usersetups/domains/switch")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "切换企业域", notes = "切换企业域")
	public Resource switchDomain(@RequestParam String domain, HttpServletResponse response) throws Exception{
		WebUser webUser = getUser();
		UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
		UserVO user = userProcess.getUserByLoginnoAndDoaminName(webUser.getLoginno(), domain);
		String token = Security.getToken(user.getId());
		// 存放到cookie
		Cookie cookie = new Cookie(Security.ACCESS_TOKEN, token);
		Cookie isFromLogin = new Cookie("isFromLogin","1");
		cookie.setPath("/");
		cookie.setMaxAge(7200);
		isFromLogin.setPath("/");
		response.addCookie(cookie);
		response.addCookie(isFromLogin);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(Security.ACCESS_TOKEN, token);
		return success("ok", jsonObject);
	}

	/**
	 * 新的密码加密机制
	 *
	 * @param s
	 * @return
	 * @throws Exception
	 */
	private String encrypt(final String s) throws Exception {
		return Security.encryptPassword(s);
	}

	/**
	 * 新的密码解密机制
	 *
	 * @param s
	 * @return
	 * @throws Exception
	 */
	private String decrypt(final String s) {
		String pwd = Security.decryptPassword(s);
		return Security.decryptPassword(s);
	}
}
