package cn.myapps.runtime.mobile.user.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.department.model.DepartmentVO;
import cn.myapps.authtime.department.service.DepartmentProcess;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.Security;
import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.mobile.common.controller.BaseController;
import cn.myapps.runtime.mobile.user.model.User;
import cn.myapps.util.ProcessFactory;

@Controller(value="UserController")
@RequestMapping(value="/runtime/app/users")
@Scope("prototype")
@Api(tags = "用户模块")
public class UserController extends BaseController{
	
	/**
	 * 获取联系人资料
	 */
	@RequestMapping(value="/getUser.action")
	@ResponseBody
	@ApiOperation(value = "获取联系人资料", notes = "获取联系人资料")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "ids",value = "联系人主键",required = true,paramType = "query",dataType = "string")
	})
	public Map<String, Object> getUserData(){
		if (getUserId() == null) {
			return addActionResult(false, "access_token invalid", null);
		}
		try {
			List<User> list = new ArrayList<User>();
			ParamsTable params = getParams();
			String ids = params.getParameterAsString("ids");
			String[] id = ids.split(",");
			for (int i = 0; i < id.length; i++) {
				UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
				UserVO user = (UserVO) userProcess.doView(id[i]);
				UserVO me = (UserVO) userProcess.doView(getUserId());
				User u = new User();
				u.setId(user.getId());
				u.setName(user.getName());
				u.setLoginNo(user.getLoginno());
				u.setEmail(user.getEmail());
				u.setMobile(user.getTelephone());
				u.setMobile2(user.getTelephone2());
				if (StringUtil.isBlank(user.getAvatarUri())) {
					u.setAvatar("");
				} else {
					u.setAvatar(user.getAvatarUri()+"?accessToken="+getAccess_token());
				}
				u.setDomain(user.getDomain().getName());
				DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
				DepartmentVO dept = (DepartmentVO) deptProcess.doView(user.getDefaultDepartment());
				if(dept!=null){
					u.setDept(dept.getName());
				}else{
					u.setDept("");
				}
				if(me.getFavoriteContacts() !=null && me.getFavoriteContacts().indexOf(user.getId())>=0){
					u.setFavoriteContact(true);
				}else{
					u.setFavoriteContact(false);
				}
				list.add(u);
			}
			
			return addActionResult(true, "ok", list);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}

	/**
	 * 获取用户资料
	 */
	@RequestMapping(value="/queryUser.action")
	@ResponseBody
	@ApiOperation(value = "", notes = "")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string")
	})
	public Map<String, Object> queryUser(){
		if (getUserId() == null) {
			return addActionResult(false, "access_token invalid", null);
		}
		try {
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			UserVO user = (UserVO) userProcess.doView(getUserId());
			User u = new User();
			u.setId(user.getId());
			u.setName(user.getName());
			u.setLoginNo(user.getLoginno());
			u.setEmail(user.getEmail());
			u.setMobile(user.getTelephone());
			u.setMobile2(user.getTelephone2());
			if (StringUtil.isBlank(user.getAvatarUri())) {
				u.setAvatar("");
			} else {
				u.setAvatar(user.getAvatarUri()+"?accessToken="+getAccess_token());
			}
			u.setDomain(user.getDomain().getName());
			DepartmentProcess deptProcess = AuthTimeServiceManager.departmentRuntimeService();
			DepartmentVO dept = (DepartmentVO) deptProcess.doView(user.getDefaultDepartment());
			if(dept!=null){
				u.setDept(dept.getName());
			}else{
				u.setDept("");
			}
			return addActionResult(true, "ok", u);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}
	
	/**
	 * 更新用户资料
	 */
	@RequestMapping(value="/save.action")
	@ResponseBody
	@ApiOperation(value = "更新用户资料", notes = "更新用户资料")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "access_token",value = "access_token",required = true,paramType = "query",dataType = "string"),
			@ApiImplicitParam(name = "content",value = "请求包体",required = true,paramType = "body",dataType = "string")
	})
	public Map<String, Object> doSave(){
		if (getUserId() == null) {
			return addActionResult(false, "access_token invalid", null);
		}
		try {
			ParamsTable params = getParams();
			String name = params.getParameterAsString("name");
			String loginno = params.getParameterAsString("loginno");
			String password = params.getParameterAsString("password");
			String oldPassword = params.getParameterAsString("oldPassword");
			String email = params.getParameterAsString("email");
			String mobile = params.getParameterAsString("mobile");
			String mobile2 = params.getParameterAsString("mobile2");
			String avatar = params.getParameterAsString("avatar");
			UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
			UserVO user = (UserVO) userProcess.doView(getUserId());
			if (avatar != null && !"".equals(avatar)) {
				user.setAvatar(avatar);
			}
			if (name != null && !"".equals(name)) {
				user.setName(name);
			}
			if (loginno != null && !"".equals(loginno)) {
				user.setLoginno(loginno);
			}
			if (password != null && !"".equals(password)) {
				if (oldPassword != null && !"".equals(oldPassword)) {
					if (oldPassword.equals(Security.decryptPassword(user.getLoginpwd()))) {
						//将新密码进行base64加密
						password = Security.encodeToBASE64(password);			
						if(password.length()>2){
							String lp = password.substring(0,2);
							String rp = password.substring(2,password.length());
							password = rp+lp;
							user.setLoginpwd(password);
						}							
					} else {
						return addActionResult(false, "原密码错误", null);
					}
				}else {
					return addActionResult(false, "原密码不能为空", null);
				}
			}
			if (email != null && !"".equals(email)) {
				user.setEmail(email);
			}
			if (mobile != null && !"".equals(mobile)) {
				user.setTelephone(mobile);
			}
			if (mobile2 != null && !"".equals(mobile2)) {
				user.setTelephone2(mobile2);
			}
			userProcess.doUpdate(user);
			return addActionResult(true, "保存成功", null);
		} catch (Exception e) {
			return addActionResult(false, e.getMessage(), null);
		}
	}
}
