$(function() {
  var IMclassify = gobalData.IMclassify;
  var url = "";
  switch (IMclassify) {
   	case "ns":
      url = 'http://43.240.249.76:81';
      break;
    case "jn":
      url = 'http://120.227.10.75:81';
      break;
    case "my":
      url = 'http://120.227.3.238:81';
      break;
    default:
      url = 'http://class2.qdedu.net';
  }
  var JIM = new JMessage({ debug: true });
  var timestamp = new Date().getTime() + "";

  
  var username =   window.localStorage.getItem("user_name")   || "user" + Math.floor(Math.random() * 100000);;
  var vtype =      window.localStorage.getItem("vtype")   || "1";
  var data_id =    window.localStorage.getItem("data_id") || "2";
  var data_title = window.localStorage.getItem("zj_name") || "课程";

  var config = {
    get_auth_url:    url + "/jgim/bozim/jgim.php",
    get_room_id_url: url + "/jgim/bozim/jgim.php",
    auth_payload: {
      appkey: gobalData.IM_appkey,
      random_str: "4044044044044asdasd04404404404",
      signature: "",
      timestamp,
      // masterSecret:    "3312ee738b0bc7f450836100",
      // flag : 是否启用消息漫游，值为0不开启，值为1开启
      flag: 1
    },
    vtype,
    data_id,
    data_title,
    username,
    roomId: ""
  };
  var chat_app = new Vue({
    el: "#detail_im_content",
    data: {
      signature: "",
      roomId: "",
      rid: "",
      msg: "",
      logged: false,
      msgList: [],
      canSend: false
    },
    computed: {},
    methods: {
        imgOnload(){
          document.getElementById('msg-wrap').scrollTop = document.getElementById('msg-wrap').scrollHeight;
        },
      send() {
        if (!this.msg || !this.msg.trim()) {
          return;
        }
        JIM.sendChatroomMsg({
          target_rid: this.rid,
          content: this.msg.trim()
          // extras :
        })
          .onSuccess((data, msg) => {
            //data.code 返回码
            //data.message 描述
            //data.room_id 目标聊天室 id
            //data.msg_id 发送成功后的消息 id
            //data.ctime_ms 消息生成时间,毫秒
            console.log("消息发送成功~");
            this.msgList.push({
              is_me: true,
              msg_type: "text",
              from_name: config.username,
              msg_body: {
                text: this.msg.trim()
              }
            });
            this.msg = "";
            this.$nextTick(() => {
              document.getElementById(
                "msg-wrap"
              ).scrollTop = document.getElementById("msg-wrap").scrollHeight;
            });
          })
          .onFail(data => {
            //data.code 返回码
            //data.message 描述
            console.error("消息发送失败~");
          });
      },
      fileChange(e) {
        let file = e.target.files[0];
        console.log("file:", file);
        if (!file) {
          return;
        }
        var form = new FormData();
        form.append("image", file);
        JIM.sendChatroomPic({
          target_rid: this.rid,
          image: form
          // extras : 'json object'
        })
          .onSuccess((data, msg) => {
            //data.code 返回码
            //data.message 描述
            //data.room_id 目标聊天室 id
            //data.msg_id 发送成功后的消息 id
            //data.ctime_ms 消息生成时间,毫秒
            console.log("图片发送成功", data, msg);
            JIM.getResource({
              media_id: msg.content.msg_body.media_id
            }).onSuccess(res => {
              //console.log(res);
              if (res.code == 0) {
                //代表获取图片资源文件成功
                var img_url = res.url;
                this.msgList.push({
                  is_me: true,
                  msg_type: "image",
                  from_name: config.username,
                  msg_body: {
                    src: img_url
                  }
                });
                this.$nextTick(() => {
                  document.getElementById(
                    "msg-wrap"
                  ).scrollTop = document.getElementById(
                    "msg-wrap"
                  ).scrollHeight;
                });
              }
            });
          })
          .onFail(data => {
            //同发送单聊文本
            console.error("图片发送失败~");
          });
      },
      async getSignature() {
        let res = await axios.get(config.get_auth_url, {
          params: {
            op: "get_auth_payload_v2",
            appkey: config.auth_payload.appkey,
            random_str: config.auth_payload.random_str,
            timestamp: config.auth_payload.timestamp
          }
        });
        console.log("res:", res);
        if (res.data.code === 1) {
          let s = res.data.data.auth_payload.signature;
          this.signature = s;
          config.auth_payload.signature = s;
          console.log("signature:", s);
          this.JMinit();
        } else {
          console.error("获取签名失败~");
        }
      },
      async getRoomId() {
        let res = await axios.get(config.get_room_id_url, {
          params: {
            op: "get_roomid",
            vtype: config.vtype,
            data_id: config.data_id,
            data_title: config.data_title
          }
        });
        console.log("res:", res);
        if (res.data.code === 1) {
          this.roomId = res.data.data.chatroom_id;
          config.roomId = res.data.data.chatroom_id;
          console.log("roomId:", this.roomId);
        } else {
          console.error("获取roomId失败~");
        }
      },
      JMinit() {
        console.log(config.auth_payload);

        JIM.init(
          // config.auth_payload
          {
            appkey: config.auth_payload.appkey,
            random_str: config.auth_payload.random_str,
            timestamp: config.auth_payload.timestamp,
            signature: config.auth_payload.signature,
            flag: config.auth_payload.flag
          }
        )
          .onSuccess(data => {
            console.log("JIM.init Success:", data);
            this.userRegister();
            //data.code 返回码
            //data.message 描述
          })
          .onFail(data => {
            // 同上
            console.error("JIM.init Fail:", data);
          });
      },
      userRegister() {
        JIM.register({
          username: config.username,
          password: config.username,
          is_md5: false
        })
          .onSuccess(data => {
            console.log("JIM.register Success:", data);
            //data.code 返回码
            //data.message 描述
            console.log("用户注册成功，现在开始登录~");
            this.userLogin();
          })
          .onFail(data => {
            // 同上
            console.error("JIM.register Fail:", data);
            if (data.code === 882002) {
              //
              console.log("用户已存在，直接登录");
              this.userLogin();
            }
          });
      },
      userLogin() {
        JIM.login({
          username: config.username,
          password: config.username
        })
          .onSuccess(data => {
            console.log("用户登录成功");
            //data.code 返回码
            //data.message 描述
            //data.online_list[] 在线设备列表
            //data.online_list[].platform  Android,ios,pc,web
            //data.online_list[].mtime 最近一次登录时间
            //data.online_list[].isOnline 是否在线 true or false
            //data.online_list[].isLogin 是否登录 true or false
            //data.online_list[].flag 该设备是否被当前登录设备踢出 true or false
            this.logged = true;
            this.enterRoom();
          })
          .onFail(data => {
            //同上
            console.error("用户登录失败");
          });
      },
      enterRoom() {
        JIM.enterChatroom({
          id: config.roomId
        })
          .onSuccess(data => {
            console.log("用户进入课程聊天室成功", data);
            //data.code 返回码
            //data.message 描述
            //data.id 聊天室 id
            this.rid = data.id;
            this.roomMsgUpdate();
          })
          .onFail(data => {
            console.error("用户进入课程聊天室失败~");
            //data.code 返回码
            //data.message 描述
          });
      },
      roomMsgUpdate() {
        JIM.onRoomMsg(data => {
          // data.room_id 聊天室 id
          // data.msg_id 消息 id
          // data.ctime_ms 消息生成时间
          // data.content
          console.log("聊天室来消息啦~：", data.content);
          if (data.content.msg_type == "image") {
            JIM.getResource({
              media_id: data.content.msg_body.media_id
            }).onSuccess(res => {
              //console.log(res);
              if (res.code == 0) {
                //代表获取图片资源文件成功
                data.content.msg_body.src = res.url;
                this.msgList.push(data.content);
                this.$nextTick(() => {
                  document.getElementById(
                    "msg-wrap"
                  ).scrollTop = document.getElementById(
                    "msg-wrap"
                  ).scrollHeight;
                });
              }
            });
          } else {
            this.msgList.push(data.content);
            this.$nextTick(() => {
              document.getElementById(
                "msg-wrap"
              ).scrollTop = document.getElementById("msg-wrap").scrollHeight;
            });
          }
        });
      }
    },
    mounted() {
      this.getRoomId();
      this.getSignature();
    },
    watch: {
      msg: function(n) {
        if (!n || !n.trim()) {
          this.canSend = false;
        } else {
          this.canSend = true;
        }
      }
    }
  });
});
