package com.izouma.awesomeadmin.web;

import com.izouma.awesomeadmin.constant.RongConstant;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.model.RongYunToken;
import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.RongYunTokenService;
import com.izouma.awesomeadmin.service.UserInfoService;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import io.rong.RongCloud;
import io.rong.models.CheckOnlineResult;
import io.rong.models.SMSSendCodeResult;
import io.rong.models.SMSVerifyCodeResult;
import io.rong.models.TokenResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/rong")
public class RongCloudController {

    @Autowired
    private RongYunTokenService rongYunTokenService;

    @Autowired
    private UserInfoService userService;


    private RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));

    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    @ResponseBody
    public Result sendCode(@RequestParam("phone") String mobile, HttpServletRequest request) {
        try {
            SMSSendCodeResult smsSendCodeResult = rongCloud.sms.sendCode(mobile, RongConstant.VERIFY_TEMPLATEID, "86", null, null);

            if (200 == smsSendCodeResult.getCode()) {

                String sessionId = smsSendCodeResult.getSessionId();

                return new Result(true, new StringBuilder(sessionId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, "发送失败，请稍后重试");
    }


    @RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
    @ResponseBody
    public Result verifyCode(@RequestParam("sessionId") String sessionId,
                             @RequestParam("code") String code) {
        try {
            SMSVerifyCodeResult sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
            if (200 == sMSVerifyCodeResult.getCode()) {

                Boolean success = sMSVerifyCodeResult.getSuccess();
                if (success) {

                    return new Result(true, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, "验证失败");
    }


    @RequestMapping(value = "/sendNotify", method = RequestMethod.GET)
    @ResponseBody
    public Result sendNotify(@RequestParam(required = true, value = "mobile") String mobile) {

        String result;
        try {
            SMSSendCodeResult smsSendCodeResult = rongCloud.sms.sendNotify(mobile, RongConstant.NOTIFY_TEMPLATEID, "86", null, null, null);
            if (200 == smsSendCodeResult.getCode()) {

                String sessionId = smsSendCodeResult.getSessionId();
                return new Result(true, sessionId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, "发送失败，请稍后重试");
    }

    @RequestMapping(value = "/getToken", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getToken(@RequestParam("rongKey") String rongKey) {

        Map<String, Object> token = new HashMap<String, Object>();

        String userToken = "";
        RongYunToken ryt = rongYunTokenService.getRongToken(rongKey);
        if (ryt != null) {
            userToken = ryt.getToken();
        } else {

            try {
                UserInfo userInfo = userService.getUserInfoById(rongKey);
                TokenResult userGetTokenResult = rongCloud.user.getToken(rongKey, rongKey, userInfo != null ? userInfo.getIcon() : "http://www.rongcloud.cn/images/logo.png");
                userToken = userGetTokenResult.getToken();

                RongYunToken rong = new RongYunToken();

                rong.setUserId(rongKey);
                rong.setToken(userToken);
                rongYunTokenService.saveRongToken(rong);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        token.put("token", userToken);
        token.put("appKey", PropertiesFileLoader.getProperties("rongyunappkey"));
        return token;
    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUserInfo(@RequestParam(required = true, value = "targetId") String targetId) {

        Map<String, Object> token = new HashMap<String, Object>();

        UserInfo uinfo = userService.getUserInfoById(targetId);
        token.put("name", uinfo.getNickname());
        token.put("portraitUri", uinfo.getIcon());
        return token;
    }

    /**
     * 检查是否在线
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/checkOnline", method = RequestMethod.GET)
    @ResponseBody
    public CheckOnlineResult checkOnline(@RequestParam(required = true, value = "userId") String userId) {

        try {
            CheckOnlineResult checkOnlineResult = rongCloud.user.checkOnline(userId);

            return checkOnlineResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
