package com.sonic.pigeon.utils;

import com.sonic.common.enums.AppEnv;
import com.sonic.pigeon.domain.bo.ImUserBo;
import com.sonic.pigeon.lib.enums.ImUserTypeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author code
 */
@Component
public class ImGenerator {

    @Value("${spring.profiles.active}")
    private String runMode;

    /**
     * 分隔符
     */
    private static final String TEMPLATE = "@";

    /**
     * 测试环境
     */
    private static final String TEMPLATE_TEST = "t";


    /**
     * 生成IM的账号ID
     * @param userId
     * @param userType
     * @return
     */
    public String genImAccountId(Long userId, ImUserTypeEnum userType) {
        StringBuilder accountId = new StringBuilder();
        accountId.append(userId);
        if (AppEnv.product.name().equals(runMode)) {
            //eg: 10001#U
            accountId.append(TEMPLATE).append(userType);
        } else {
            //eg: 10001#U#T (第三位代表环境)
            accountId.append(TEMPLATE).append(userType).append(TEMPLATE).append(TEMPLATE_TEST);
        }
        return accountId.toString();
    }

    /**
     * 获取IM用户信息
     * @param accountId
     * @return
     */
    public ImUserBo getImUserBo(String accountId) {
        ImUserBo imUserBo = new ImUserBo();
        imUserBo.setUserId(decodeImAccountId(accountId));
        //获取用户类型
        imUserBo.setImUserType(decodeImUserType(accountId));
        return imUserBo;
    }

    /**
     * 解密IM账号ID
     * @param accountId
     * @return
     */
    public Long decodeImAccountId(String accountId) {
        return Long.valueOf(accountId.substring(0, accountId.indexOf(TEMPLATE)));
    }

    /**
     * 解析用户类型
     * @param accountId
     * @return
     */
    public ImUserTypeEnum decodeImUserType(String accountId) {
        accountId = accountId.replace(TEMPLATE + TEMPLATE_TEST, "");
        String userTypeStr = accountId.substring(accountId.indexOf(TEMPLATE) + 1);
        return ImUserTypeEnum.getImUserType(userTypeStr);
    }

    /**
     * 获取访问IM的Token
     * @param accountId
     * @return
     */
    public String genImAccountToken(String accountId) {
        return new Md5Hash(UserSaltGenerator.generateSaltByUserId(accountId) + accountId).toHex();
    }

}
