import { API } from './../../../utils/network/api'
import { getTimeAgo } from './../../../utils/util'
import TIM from '../../../TUIKit/lib/tim-wx-sdk';
const api = new API()
const app = getApp()
Page({
  data: {
    navbarData: {
      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '问诊消息', //导航栏 中间的标题
    },
    height: app.globalData.height, 
    has_data: true,
    data_list_1: [],
    data_list_2: [],
    data_list_3: [],
    data_list_4: [],
    data_list_5: [],
    message_inquiry_type: 2,
    static_host: api.getStaticHost()
  },
  onLoad() {
    console.log("wenzhen onload");
    
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 1  //数字是当前页面在tabbar的索引,如我的查询页索引是2，因此这边为2，同理首页就为0，审批页面为1
      })
    }

    let session_data_list_1 = wx.getStorageSync('session_data_list_1'); 
    let session_data_list_2 = wx.getStorageSync('session_data_list_2');
    let session_data_list_3 = wx.getStorageSync('session_data_list_3');
    let session_data_list_4 = wx.getStorageSync('session_data_list_4');
    if(!session_data_list_1) wx.setStorageSync('session_data_list_1', []);
    if(!session_data_list_2) wx.setStorageSync('session_data_list_2', []);
    if(!session_data_list_3) wx.setStorageSync('session_data_list_3', []);
    if(!session_data_list_4) wx.setStorageSync('session_data_list_4', []);
    this.setData({"data_list_1": session_data_list_1});
    this.setData({"data_list_2": session_data_list_2});
    this.setData({"data_list_3": session_data_list_3});
    this.setData({"data_list_4": session_data_list_4});
    if(session_data_list_1.length == 0) this.getDoctorInquiryMessage(1);
    if(session_data_list_2.length == 0) this.getDoctorInquiryMessage(2);
    if(session_data_list_3.length == 0) this.getDoctorInquiryMessage(3);
    if(session_data_list_4.length == 0) this.getDoctorInquiryMessage(4);
    
    
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.MESSAGE_RECEIVED, this.$onMessageReceived, this);

  },
  go(e){
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          console.log(data)
        },
        someEvent: function(data) {
          console.log(data)
        }
      },
      success: function(res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
      }
    })
  },

  $onMessageReceived(value) {
    const message = value.data[0];
    console.log("message from wenzhen: ",message)
    let cloudCustomData = JSON.parse(message.cloudCustomData);
    let inquiry_type = cloudCustomData.inquiry_type;
    let order_inquiry_id = cloudCustomData.order_inquiry_id;
    let type = message.type;
    let message_txt = "新消息";
    console.log(type)
    switch (type) {
      case TIM.TYPES.MSG_TEXT:
        console.log("文本消息");
        message_txt = message.payload.text;
        break;
      case TIM.TYPES.MSG_IMAGE:
        console.log("图片消息");
        message_txt = "[图片]";
        break;
      case TIM.TYPES.MSG_AUDIO:
        console.log("音频消息")
        message_txt = "[语言]";
        break;
      case TIM.TYPES.MSG_VIDEO:
        console.log("视频消息");
        message_txt = "[视频]";
        break;
      case TIM.TYPES.MSG_FILE:
        console.log("文件消息")
        message_txt = "[文件]";
        break;
      case TIM.TYPES.MSG_CUSTOM:
        console.log("自定义消息")
        break;
      case TIM.TYPES.MSG_MERGER:
        console.log("合并消息")
        break;
      case TIM.TYPES.MSG_LOCATION:
        console.log("位置消息")
        message_txt = "[位置]";
        break;
      case TIM.TYPES.MSG_FACE:
        console.log("表情消息")
        message_txt = "[表情]";
        break;
      default:
        break;
    }
    let list_name = "data_list_" + inquiry_type;
    let _index = this.data[list_name].findIndex(item => {
      return item.order_inquiry_id == order_inquiry_id;
    })
    
    let new_list = [];
    //没有当前会话
    if(_index > -1){
      let target = list_name + "[" + _index + "].last_message_content.Text";
      let target_dot = list_name + "[" + _index + "].message_dot";
      console.log("target: ",target);
      this.setData({
        [target]: message_txt,
        [target_dot]: true
      })
      new_list.push(this.data[list_name][_index]);//先放入目标
    }else{
      let item = {};
      item.inquiry_status = message.inquiry_status;
      let txt = {};
      txt.Text= message_txt;
      item.last_message_content = txt;
      item.message_send_time = message.message_send_time;
      item.message_seq = message.message_seq;
      item.message_type = message.message_type;
      item.order_inquiry_id = message.order_inquiry_id;
      item.patient_age = message.patient_age;
      item.patient_name = message.patient_name;
      item.patient_sex = message.patient_sex;
      item.to_user_id = message.to_user_id;
      item.message_dot = true;
      new_list.push(item);
    }
    
    //置顶
    this.data[list_name].forEach((item, index) => {
      if(index != _index){
        new_list.push(item)
      }
    })

    this.setData({
      [list_name]: new_list
    })

    wx.setStorageSync('session_'+list_name, new_list);
  },
  getDoctorInquiryMessage(message_inquiry_type){
    let list_name = "data_list_" + message_inquiry_type;
    this.setData({
      [list_name]: []
    })
    //获取医生问诊消息列表
    api.getDoctorInquiryMessage({message_inquiry_type: message_inquiry_type}).then(response => {
      console.log(response);
      if(response.data){
        console.log(list_name);
        let data_list = this.data[list_name];
        response.data.forEach((item) => {
          item.message_send_time = getTimeAgo(item.message_send_time);
          data_list.push(item);
        })
        this.setData({
          [list_name]: data_list,
        })
        wx.setStorageSync('session_'+list_name, data_list);
      }
    }).catch(errors => {console.error(errors);})
  },
  onTabsChange(e){
    console.log(e);
    this.setData({
      message_inquiry_type: e.detail.value,
    })
    this.getDoctorInquiryMessage(e.detail.value)
  }
})