import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import ListMore from '@/c/pageDataList/listMore'
import { strTrim, arrToObj } from '@utils'
const HLKEY = '654mca0l38b489d9'
const CJ = require('crypto-js')
import './chat.scss'

class Index extends Component {

  constructor (props) {
    super(props)
    const {id: curId} = this.$router.params
    this.state = {
      page_size: 10,
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
      curId,
      curObj: {},
      commentVal: '',
      msgSocketList: [],
      uObj: {},
      chatUserObj: {},
      viewId: '',
      socketTimer: null,
    }
  }

  config = {
    navigationBarTitleText: '在线沟通',
  }

  componentWillUnmount () {
    this.closeSocket()
    let pages = getCurrentPages()
    let prevPage = pages[ pages.length - 2 ]
    if (prevPage.$component.getNotifycount) prevPage.$component.getNotifycount()
    // if (prevPage.$component.getNewData) prevPage.$component.getNewData()
  }
  
  closeSocket () {
    Taro.closeSocket()
    const { socketTimer } = this.state
    clearInterval(socketTimer)
  }

  componentDidMount () {
    const that = this
    let uObj = Taro.getStorageSync('APP_userInfo')
    const { to_user_id } = this.$router.params
    this.setState({
      uObj
    }, () => {
      let uArr = [uObj.user_id, to_user_id]
      Taro.api.base.apiuserinfolist({
        user_ids: uArr.join(',')
      }).then(res => {
        let chatUserObj = {}
        const list = res.list || []
        list.forEach(item => {
          if (item.id !== uObj.user_id) {
            Taro.setNavigationBarTitle({
              title: item.nickname
            })
          }
          chatUserObj[item.id] = item
        })
        that.setState({
          chatUserObj
        })
      })
      Taro.$AHU(this)
      this.getDataList()
      this.initSocket()    
    })
  }

  getDataList () {
    const { to_user_id } = this.$router.params
    let { page_size, page, dataList, isListEmpty } = this.state
    Taro.api.room.apiuserchatlist({
      page,
      page_size,
      to_user_id,
    }).then(res => {
      let curData = res.list || []
      curData = curData.reverse()
      let isListEnd = false
      if (curData.length > 0) {
        if (page === 1) {
          dataList = curData
        } else {
          dataList = [].concat(curData, dataList)
        }
        if (curData.length === page_size && res.total !== curData.length) {
          isListEnd = false
        } else {
          isListEnd = true
        }
      }
      if (curData.length === 0 && page === 1) {
        isListEmpty = true
        dataList = []
      } else {
        isListEmpty = false
      }
      const that = this
      this.setState({
        dataList,
        isListEnd,
        isListEmpty,
        isListLoading: false
      }, () => {
        if (page > 1) {
          setTimeout(() => {
            that.setState({
              viewId: `history11`
            })
          }, 500)
        }
      })
    })
  }
  onScrollToUpper (e) {
    let { isListEnd, isListLoading, page } = this.state
    if (!isListEnd && !isListLoading) {
      page++
      this.setState({
        page,
        isListLoading: true
      }, () => {
        this.getDataList()
      })
    }
  }

  initSocket () {
    const { uObj } = this.state
    const that = this
    Taro.connectSocket({
      url: 'wss://chat.honglouplus.com/acc',
      success: function () {
        console.log('connect success')
      }
    }).then(task => {
      task.onOpen(function () {
        // console.log('onOpen')
        let token = Taro.getStorageSync('APP_token')
        task.send({ data: '{"seq":"' + that.sendId() + '","cmd":"login","data":{"userId":"' + uObj.user_id + '","appId":101,"serviceToken":"' + token + '"}}' })
        const socketTimer = setInterval(() => {
          task.send({data: '{"seq":"' + that.sendId() + '","cmd":"heartbeat","data":{}}'});
        }, 30000)
        that.setState({
          socketTimer
        })
      })
      task.onMessage(function (msg) {
        // console.log('onMessage: ', msg)
        let { msgSocketList } = that.state
        const data = JSON.parse(msg.data)
        // console.log(data)
        if (data.cmd === 'msg' || data.cmd === 'login') {
          const res = data.response || {}
          if (res.code === 200) {
            if (data.cmd === 'login') {
              msgSocketList.push({msg: '登录成功~'})
            } else {
              const { to_user_id } = that.$router.params
              if (to_user_id === res.data.from) {
                msgSocketList.push(res.data)
              } else {
                msgSocketList.push({msg: '有其他人给你发消息啦，返回消息列表查看'})
              }
            }
            that.setState({
              msgSocketList
            }, () => {
              const { qId } = that.$router.params
              if (qId) that.sendHandle('house')
              const { eTitle, eId } = that.$router.params
              if (eId) that.sendHandle('text', `我刚刚浏览了楼盘：${eTitle}，想咨询你一下`)
              setTimeout(() => {
                that.setState({
                  viewId: `item${msgSocketList.length - 1}`
                })
              }, 500)
            })
          }
        }
        if (data.cmd === 'heartbeat') {
          const res = data.response || {}
          if (res.code !== 200) {
            msgSocketList.push({msg: res.codeMsg + '|暂无法接收消息，请退出当前页面重新登录~'})
            that.setState({
              msgSocketList
            }, () => {
              setTimeout(() => {
                that.setState({
                  viewId: `item${msgSocketList.length - 1}`
                }, () => {
                  that.closeSocket()
                })
              }, 100)
            })
          }
        }
        // task.close()
      })
      task.onError(function () {
        console.log('onError')
      })
      task.onClose(function (e) {
        console.log('onClose: ', e)
      })
    })
  }
  sendId () {
    let timeStamp = +new Date()
    let randId = parseInt(Math.random() *  1000000)
    return `${timeStamp}-${randId}`
  }


  componentDidShow () { }

  componentDidHide () { }

  avatarHandle (item) {
    const { uObj } = this.state
    if (uObj.is_sale === '1') {
      Taro.navigateTo({
        url: `/pagesRoom/follow/user?uId=${item.user_id}`
      })
    }
  }

  renderList () {
    const { chatUserObj, uObj, viewId } = this.state
    const { dataList, isListEnd, isListLoading, isListEmpty } = this.state
    const itemList = dataList.map((item, index) => {
      let tObj = {}
      if (item.type === 'house') tObj = JSON.parse(item.content)
      return (
        <View className="sl-item" key={index} id={`history${index}`}>
          <View className={item.user_id === uObj.user_id ? 'sl-wrap t2' : 'sl-wrap'}>
            {
              item.user_id === uObj.user_id
              ?
              <View className="sl-img">
                <Image className="img" src={chatUserObj[item.user_id].avatar}></Image>
              </View>
              :
              <View className="sl-img" onClick={this.avatarHandle.bind(this, item)}>
                <Image className="img" src={chatUserObj[item.user_id].avatar}></Image>
              </View>
            }
            <View className="sl-right">
              <View className="sign"></View>
              {
                item.type === 'house'
                ?
                <View className="sl-text">你好，我想咨询一下 <Navigator url={`/pagesRoom/dtl?id=${tObj.id}`} className="v">#{tObj.name}#</Navigator></View>
                : ''
              }
              {
                item.type === 'image'
                ? 
                <View className="sl-content-img" onClick={this.previewImageHandle.bind(this, item.content, [item.content])}>
                  <Image src={item.content} className="img" mode="aspectFit"></Image>
                </View>
                : ''
              }
              {
                item.type === 'text'
                ? 
                <View className="sl-text" onClick={this.copyHandle.bind(this, item.content)}>{item.content}</View>
                : ''
              }
              <View className="sl-time">{item.create_at}</View>
            </View>
          </View>
        </View>
      )
    })
    return (
      <ScrollView
        className='l-scroll-view'
        scrollY
        scrollWithAnimation
        upperThreshold="10"
        scrollIntoView={viewId}
        onScrollToUpper={this.onScrollToUpper.bind(this)}
      >
        <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} text="暂无历史消息" />
        <View className="scoped-list">
          {itemList}
        </View>
        {/* {
          dataList.length > 0
          &&
          <AtDivider content="以上为历史消息"  fontColor='#ccc' lineColor='#ccc' />
        } */}
        {this.renderMsgList()}
        <View id="msgId"></View>
      </ScrollView>
    )
  }

  previewImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }


  renderMsgList () {
    const { msgSocketList } = this.state
    const { chatUserObj, uObj } = this.state
    const curItems = msgSocketList.map((item, index) => {
      let tObj = {}
      if (item.type === 'house') tObj = JSON.parse(item.msg)
      return (
        <View className="sl-item" key={index} id={`item${index}`}>
          {
            item.from
            ?
            <View className={item.from === uObj.user_id ? 'sl-wrap t2' : 'sl-wrap'}>
              <View className="sl-img" onClick={this.avatarHandle.bind(this, item)}>
                <Image className="img" src={chatUserObj[item.from].avatar}></Image>
              </View>
              <View className="sl-right">
                <View className="sign"></View>
                {
                  item.type === 'house'
                  ?
                  <View className="sl-text">你好，我想咨询一下 <Navigator url={`/pagesRoom/dtl?id=${tObj.id}`} className="v">#{tObj.name}#</Navigator></View>
                  : ''
                }
                {
                  item.type === 'image'
                  ? 
                  <View className="sl-content-img" onClick={this.previewImageHandle.bind(this, item.content, [item.content])}>
                    <Image src={item.content} className="img" mode="aspectFit"></Image>
                  </View>
                  : ''
                }
                {
                  item.type === 'text'
                  ? 
                  <View className="sl-text" onClick={this.copyHandle.bind(this, item.msg)}>{item.msg}</View>
                  : ''
                }
              </View>
            </View>
            :
            <View className="scoped-msg-tips">{item.msg}</View>
          }
        </View>
      )
    })
    return (
      <View className="scoped-list">
        {curItems}
      </View>
    )
  }


  copyHandle (msg) {
    Taro.setClipboardData({
      data: msg,
      success: function (res) {
        Taro.getClipboardData({
          success: function (res) {
            console.log(res.data)
          }
        })
      }
    })
  }


  sendHandle (type, curMsg) {
    const that = this
    const { uObj } = this.state
    const { commentVal } = this.state
    let { msgSocketList } = this.state
    const { to_user_id } = this.$router.params
    let apiStr = 'apiusersendmessage'
    let msg = commentVal
    if (type === 'house') {
      const { qTitle, qId } = that.$router.params
      msg = JSON.stringify({
        name: qTitle,
        id: qId,
      })
    }
    if (curMsg && type === 'image') msg = curMsg
    if (typeof(curMsg) === 'string' && type === 'text') msg = curMsg
    if (msg) {
      Taro.api.room[apiStr]({
        message: msg,
        type,
        to_user: to_user_id,
      }).then(res => {
        msgSocketList.push({
          from: uObj.user_id,
          type,
          msg
        })
        this.setState({
          msgSocketList,
          commentVal: '',
        }, () => {
          setTimeout(() => {
            that.setState({
              viewId: `item${msgSocketList.length - 1}`
            })
          }, 100)
        })
      })
    } else {
      Taro.$msg('请输入')
    }
  }

  changeInput (e) {
    const val = strTrim(e.target.value)
    this.setState({
      commentVal: val
    })
  }




  uploadImgHandle () {
    let token = Taro.getStorageSync('APP_token')
    const that = this
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths
        Taro.uploadFile({
          url: `https://api.honglouplus.com/api/upload/cloud`,
          filePath: tempFilePaths[0],
          name: 'upload',
          formData: {
            'token': token
          },
          success (res){
            const msg = res.data || ''
            const key = CJ.enc.Utf8.parse(HLKEY)
            const bytes = CJ.AES.decrypt(msg, key, {
              mode: CJ.mode.ECB,
              padding: CJ.pad.Pkcs7
            })
            const originalText = bytes.toString(CJ.enc.Utf8)
            const cData = JSON.parse(originalText)
            const curImg = cData.data.url || ''
            that.sendHandle('image', curImg)
          }
        })
      }
    })
  }



  renderFooter () {
    const { commentVal } = this.state
    const bgImg = require('./img/img_uploads.png')
    return (
      <View className="l-floor-footer">
        <View className="scoped-footer">
          <View className="sf-input">
            <Input className="input" placeholder={`请输入`} value={commentVal}  onInput={this.changeInput.bind(this)} />
            <Image src={bgImg} className="img" onClick={this.uploadImgHandle.bind(this)}></Image>
            <View className="btn" onClick={this.sendHandle.bind(this, 'text')}>发送</View>
          </View>
        </View>
      </View>
    )
  }


  render () {
    return (
      <View className="l-box has-footer">
        {this.renderList()}
        {this.renderFooter()}
      </View>
    )
  }
}

export default Index
