<script lang="ts">
import RootStore from "@xkit-yx/im-store-v2";
import V2NIM, { V2NIMConst } from "nim-web-sdk-ng/dist/v2/NIM_UNIAPP_SDK";
import {
  customRedirectTo,
  customReLaunch,
  customSwitchTab,
} from "./pages/NEUIKit/utils/customNavigate";
import { getMsgContentTipByType } from "./pages/NEUIKit/utils/msg";
import { STORAGE_KEY } from "./pages/NEUIKit/utils/constants";
import { isWxApp } from "./pages/NEUIKit/utils";
import { 
  V2NIMMessage,
  V2NIMMessagePushConfig,
} from "nim-web-sdk-ng/dist/v2/NIM_UNIAPP_SDK/V2NIMMessageService";

export default {
  onLaunch() {
		// uni.request({
		//   url: 'http://192.168.3.83:8001/wyyx/startSessionJson',
		//   data: {
		// 		fromUser: 'test_user_001',
		// 		toUser: 'test_user_002'
		// 	},
		// 	timeout:60000,
		//   method: 'POST',
		//   success: (res) => {
			
				// let resData = {
				// 	appkey: "146010bdfe390e4893c854f0c50b4214",
				// 	accid :'test_user_001', 
				// 	token : 'f1257138ccbb48e667bc56b2d792aeb3'
				// }
				
				let resData = {
					appkey: "146010bdfe390e4893c854f0c50b4214",
					accid :'test_user_002', 
					token : '9d46fc00f15b93e3d0894fc5df733fc1'
				}
				
				// let resData = {
				// 	appkey: "146010bdfe390e4893c854f0c50b4214",
				// 	accid :'test_user_003', 
				// 	token : '4f77d3e55715f7e7355508a74d2a0dfe'
				// }
				
				// let resData = res.data.data;
		    const imOptions = {    
		        appkey: resData.appkey, // 请填写您的 appkey
		        account: resData.accid, // 请填写您的 account
		        token: resData.token, // 请填写您的 token
		    }
		    if (imOptions) {
		      this.initNim(imOptions);
		    } else {
		      // 需要登录, 跳转登录页
		    }
		//   },
		//   fail (error) {
		   
		//   }
		// });
  },
  methods: {
    initNim(opts) {
      // 初始化 nim sdk
      const nim = (uni.$UIKitNIM = V2NIM.getInstance(
        {
          appkey: opts.appkey,
          needReconnect: true,
          // "reconnectionAttempts": 5,
          debugLevel: "debug",
          apiVersion: "v2",
        },
        {
          V2NIMLoginServiceConfig: {
            lbsUrls: isWxApp
              ? ["https://lbs.netease.im/lbs/wxwebconf.jsp"]
              : ["https://lbs.netease.im/lbs/webconf.jsp"],
            linkUrl: isWxApp ? "wlnimsc0.netease.im" : "weblink.netease.im",
            /**
             * 使用固定设备 ID，
             */
            isFixedDeviceId: true,
          },
        }
      ));
      // 初始化 store
      const store = (uni.$UIKitStore = new RootStore(
        nim,
        {
          addFriendNeedVerify: false,
           // 是否需要显示 p2p 消息、p2p 会话列表消息已读未读，默认 false
          p2pMsgReceiptVisible: true,
          // 是否需要显示群组消息已读未读，默认 false
          teamMsgReceiptVisible: true,
          teamAgreeMode:
            V2NIMConst.V2NIMTeamAgreeMode.V2NIM_TEAM_AGREE_MODE_NO_AUTH,
          sendMsgBefore: async (options: {
            msg: V2NIMMessage;
            conversationId: string;
            serverExtension?: Record<string, unknown>;
          }) => {
            const pushContent = getMsgContentTipByType({
              text: options.msg.text,
              messageType: options.msg.messageType,
            });
            const yxAitMsg = options.serverExtension
              ? options.serverExtension.yxAitMsg
              : { forcePushIDsList: "[]", needForcePush: false };

            // 如果是 at 消息，需要走离线强推

            const { forcePushIDsList, needForcePush } = yxAitMsg
              ? // @ts-ignore
                store.msgStore._formatExtAitToPushInfo(
                  yxAitMsg,
                  options.msg.text
                )
              : { forcePushIDsList: "[]", needForcePush: false };

            console.log("forcePushIDsList: ", forcePushIDsList);

            const { conversationId } = options;
            const conversationType =
              nim.V2NIMConversationIdUtil.parseConversationType(conversationId);
            const targetId =
              nim.V2NIMConversationIdUtil.parseConversationTargetId(
                conversationId
              );

            const pushPayload = JSON.stringify({
              // oppo
              oppoField: {
                click_action_type: 4, // 参考 oppo 官网
                click_action_activity: "", // 各端不一样 TODO
                action_parameters: {
                  sessionId: targetId,
                  sessionType: conversationType,
                }, // 自定义
              },

              // vivo
              vivoField: {
                pushMode: 0, //推送模式：0 表示正式推送、1 表示测试推送。不填则默认为 0。
              },

              // huawei
              hwField: {
                click_action: {
                  type: 1,
                  action: "", // 各端不一样 TODO
                },
                androidConfig: {
                  category: "IM",
                  data: JSON.stringify({
                    sessionId: targetId,
                    sessionType: conversationType,
                  }),
                },
              },

              // 通用
              sessionId: targetId,
              sessionType: conversationType,
            });

            const pushConfig: V2NIMMessagePushConfig = {
              pushEnabled: true,
              pushNickEnabled: true,
              forcePush: needForcePush,
              forcePushContent: pushContent,
              forcePushAccountIds: forcePushIDsList,
              pushPayload: "{}",
              pushContent,
            };

            return { ...options, pushConfig };
          },
        },
        "UniApp"
      ));

      nim.V2NIMLoginService.login(opts.account, opts.token).then(() => {
        customSwitchTab({
          url: "/pages/Conversation/index",
        });
      });
    },
    logout() {
    },
  },
};
</script>
<style>
uni-page-body {
  height: 100%;
}
uni-page-body > uni-view {
  height: 100%;
}
</style>
