
import toast from '@/utils/toast'
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { store } from "@/store"
import { Decrypt, timeFormatDHM } from '@/utils/tools'
import message from "@/api/https/message"
// import { msgInfo } from '@/api/mockData/index'
import order from '@/api/https/order'
import useGlobalFunc from "@/composables/useGlobalFunc";
import { setStorage, getStorage,cleatStorage } from "@/utils/storage";

/*************************************************
 * IM消息
*/
const messageFn = function () {
  // vuex
  const { getMtStoreIMStatus } = useGlobalFunc()

  // 用户列表
  const userListData = ref<Array<AnyObject>>([])

  /*************************************************
   * 获取用户列表
  */
  onShow(async () => {
    if(getStorage('storeMessge')){
      if(store.state.storeInfo.allStoreInfo.id !== getStorage('storeID')) await store.dispatch('storeInfo/getOneStore',getStorage("storeID"))
      await getMtStoreIMStatus()  // 获取美团im单聊状态
      await getMTUserList() // 获取用户列表
      cleatStorage('storeMessge') 
    }

    
    uni.hideTabBarRedDot({ index: 2 })
    if (isFirstLogin.value) return
    userListData.value = []
    getMTUserList()
  })
  const isFirstLogin = computed(() => {
    // 是否没有登陆的状态
    return store.state.serveInfo.isFirstLogin
  })


  /**
   * 整理参数信息，避免请求出错
   */
   async function dataParams() {
    let arr:any = []
    let brr = store.getters['storeInfo/platformInfo']
    if(brr && brr.length>0){
      let mtVendorIDInfo = brr.find((item:AnyObject) => item.vendorID === 1)
      let ebVendorIDInfo = brr.find((item:AnyObject) => item.vendorID === 3)
      if(mtVendorIDInfo){
        arr.push({
          vendorStoreID: mtVendorIDInfo.vendorStoreID,
          vendorID: "1",
          appID: mtVendorIDInfo.vendorOrgCode
        })
      }

      if(ebVendorIDInfo){
        arr.push({
          vendorStoreID: ebVendorIDInfo.vendorStoreID,
          vendorID: "3",
          appID: ebVendorIDInfo.vendorOrgCode
        })
      }
    }
    return arr
  }

  // 获取美团IM
  async function getMTUserList() {
    console.log('获取美团IM')
    let arr = await dataParams()
    if(!(arr && arr.length>0)) return
    let data = {
      payLoad:JSON.stringify(arr)
    }
    let venderIDInfo = arr.find((item:AnyObject) => item.vendorID === '1')
    let ebStore = arr.find((item:AnyObject) => item.vendorID === '3')
    let jdStore = arr.find((item:AnyObject) => item.vendorID === '0')

    let res = await message.get_IM_user_list(data)
  
    // res = msgInfo.userList // 模拟数据
    if (res.code == 0) {
      if (JSON.stringify(res.data) === '{}') return
      let platformID = venderIDInfo.appID // 美团账号
      let newArr: any = []
      let fmtUserList = venderIDInfo ? res.data[`${venderIDInfo.appID}:${venderIDInfo.vendorStoreID}:1`] || [] : []  // 美团
      let febUserList = ebStore && JSON.stringify(ebStore) !== '{}' ? res.data[`${ebStore.appID}:${ebStore.vendorStoreID}:3`] || [] : [] // 饿百
      let jdUserList = jdStore && JSON.stringify(jdStore) !== '{}' ? res.data[`${jdStore.appID}:${jdStore.vendorStoreID}:0`] || [] : [] // 京东

      let reverseList = fmtUserList.reverse()
      let reverseListEb = febUserList.reverse()
      let reverseListJD = jdUserList.reverse()

      // 格式化数据
      reverseList.map((element: any) => {
        let resData = JSON.parse(element)
        let latestMsgHandler = ''
        try {
          JSON.parse(Decrypt(resData.latestMsg, platformID))
          latestMsgHandler = typeof JSON.parse(Decrypt(resData.latestMsg, platformID)) === 'number' ? Decrypt(resData.latestMsg, platformID) : '【订单】'
        } catch (error) {
          let msg = Decrypt(resData.latestMsg, platformID)
          if (msg == '') {
            latestMsgHandler = '【商品】'
          } else {
            if (!(msg.includes('https') || msg.includes('http'))) {
              latestMsgHandler = msg
            } else {
              if (msg.indexOf('.amr') == -1) {
                latestMsgHandler = '【图片】'
              } else {
                latestMsgHandler = '【语音】'
              }
            }
          }
        }

        // if (resData.userID != 0) {
          // 只展示12个小时以内的消息
          let userList = {
            ...resData,
            latestMsg: latestMsgHandler,
            latestTime: timeFormatDHM(+new Date(resData.latestTime * 1000)),
            orderInfo: {},
            orderDesc: ''
          }
          newArr.push(userList)

          // 获取订单信息
          // if (userList.orderID) getOrderInfo(userList.orderID, index)
          if (userList.orderID) getOrderInfo(userList.orderID, newArr.length - 1)

        // }

      })


      // 饿百
      reverseListEb.map((element: any, index: number) => {
        let resData = JSON.parse(element)
        // let isAddUserLiset = JSON.parse(resData.latestMsg).data && JSON.parse(JSON.parse(resData.latestMsg).data).title.includes('本次服务已经完成，会话暂停') ? false : true
        let latestMsgHandler = JSON.parse(resData.latestMsg).text ? JSON.parse(resData.latestMsg).text : JSON.parse(resData.latestMsg).duration ? '【语音】' : '【图片】'

        if (JSON.parse(resData.latestMsg).elements && JSON.parse(resData.latestMsg).elements.length > 0) {
          let findItem = JSON.parse(resData.latestMsg).elements.filter((item: { elementType: number }) => item.elementType === 1)
          latestMsgHandler = findItem && findItem.length > 0 ? JSON.parse(findItem[0].elementContent).text.replace('@商家', '') : latestMsgHandler
        }
        // 饿百参考文档：https://open-retail.ele.me/#/apidoc/me.ele.retail:im.message.send-3?aopApiCategory=IM_all&type=api_menu && isAddUserLiset
        if ((new Date().getTime() - resData.latestTime * 1000) <= (3600 * 1000 * 12 * 1)) {
          let userList = {
            ...resData,
            latestMsg: latestMsgHandler,
            latestTime: timeFormatDHM(+new Date(resData.latestTime * 1000)),
            orderInfo: {},
            orderDesc: ''
          }
          newArr.push(userList)

          // 获取订单信息
          // if (userList.orderID) getOrderInfo(userList.orderID, index)
          if (userList.orderID) getOrderInfo(userList.orderID, newArr.length - 1 )
        }

        // 京东
        if(reverseListJD && reverseListJD.length>0){
          reverseListJD.forEach((element:string) => {
            let resData = JSON.parse(element)
            // console.log('京东消息,用户列表',resData)
            let latestMsgHandler = resData.latestMsg

            let userList = {
              ...resData,
              latestMsg: latestMsgHandler,
              latestTime: timeFormatDHM(+new Date(resData.latestTime )),
              orderInfo: {},
              orderDesc: ''
            }
            newArr.push(userList)
          });
        }

      })
      userListData.value = newArr
    } else {
      toast('获取信息异常')
      userListData.value.length == 0
    }
  }

  /**
   * 获取订单信息
   */
  async function getOrderInfo(orderId: string, index: number) {
    let res = await order.get_orders({ vendorOrderID: orderId })
    if (res.code === '0') {
      userListData.value[index].orderInfo = res.data.data[0]
      userListData.value[index].orderDesc = ` #${res.data.data[0].orderSeq}`
    }
  }

  /**
   * 下拉刷新
   */
  let onPullDownRefreshTimer: any = null
  onPullDownRefresh(() => {
    clearTimeout(onPullDownRefreshTimer)
    onPullDownRefreshTimer = setTimeout(async () => {
      getMtStoreIMStatus()  // 获取美团im单聊状态
      // 获取用户列表
      getMTUserList()
      clearTimeout(onPullDownRefreshTimer)
    }, 500)
  })


  /*************************************************
   * 进入聊天页面
   */
  function charItem(item: AnyObject) {
    item.latestMsg = ""
    uni.navigateTo({
      url: `/subPages/messageChild/msgChat/msgChat?data=${JSON.stringify(item)}`,
    })
  }

  /*************************************************
   * 进入设置页面
   */
  function jumpToSetUp() {
    uni.navigateTo({
      url: `/subPages/merchantChild/setUp/setUp`,
    })
  }

  return {
    charItem,               // 进入聊天页面
    userListData,           // 用户列表
    jumpToSetUp,               // 跳到设置页面
    store
  }
}

export default messageFn