package com.goafanti.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.controller.BaseApiController;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.easemob.EasemobUtils;
import com.goafanti.easemob.bo.EasemobInfo;
import com.goafanti.easemob.enums.EasemonSysUsers;

@Controller
@RequestMapping(value = "/api/admin")
public class AdminSystemController extends BaseApiController {

	@Autowired
	EasemobUtils easemobUtils;

	/**
	 * 初始化系统消息用户
	 */
	@RequestMapping(value = "/sys/initEasemob", method = RequestMethod.GET)
	public Result initEasemob() {
		if (isSuperAdmin()) {
			for (EasemonSysUsers esu : EasemonSysUsers.values()) {
				JSONObject jo = new JSONObject();
				jo.put("username", esu.getUsername());
				jo.put("nickname", esu.getNickname());
				jo.put("password", System.currentTimeMillis());
				easemobUtils.sendLater(new EasemobInfo().uri("/users").data(jo.toJSONString()).method(HttpMethod.POST));
			}
			return res().data(true);
		}
		return res().data(false);
	}

	/**
	 * 测试发送消息
	 */
	@RequestMapping(value = "/sys/sendMsg", method = RequestMethod.GET)
	public Result sendMsg(String from, String to, String msg) {
		if (isSuperAdmin()) {
			easemobUtils.sendMessage(from, to, new ModelMap("nickname", EasemonSysUsers.getNickname(from)), msg, true);
			return res().data(true);
		}
		return res().data(false);
	}

	private boolean isSuperAdmin() {
		return TokenManager.hasRole(AFTConstants.SUPERADMIN);
	}
}
