// wx.miniProgram.postMessage({ data: 'foo' })
// wx.miniProgram.navigateTo({url: '/path/to/page'})

const $iframe = document.querySelector('#container')
let socket
let run
let data = {}

async function getHeader() {
  if (!data.code) return;
  let res = await axios({
    url: data.API_BASE_URL + '/goods/getCategoryByScene?sceneNum=' + data.code,
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      "X-Nideshop-Token": data.token
    }
  })

  let headers = res.data.list
  let $headers = document.querySelector('#headers')
  let headHTML = headers.map(item => `
    <div class="text" bindtap="selectType" data-id="${item.category_id}">
      ${item.name}<span>${'('+item.num+')'}</span>
      <div></div>
    </div>
  `).join('')

  $headers.innerHTML = headHTML


  selectType(headers[0].category_id)
  $headers.querySelectorAll('.text').forEach($dom => {
    $dom.addEventListener('click', () => selectType($dom.getAttribute('data-id')))
  })
}


function selectType(category_id) {
  let $headers = document.querySelector('#headers')

  Array.from($headers.querySelectorAll('.text')).forEach($dom => {
    let id = $dom.getAttribute('data-id')
    if (Number(id) === Number(category_id)) {
      $dom.classList.add('active')
    } else {
      $dom.classList.remove('active')
    }
  })

  getContent(category_id)
}


const iconHTML = [1,2,3].map(item => `
  <div class="brick brick-${item} enter">
    <div class="brick-top face"></div>
    <div class="brick-bottom face"></div>
    <div class="brick-left face"></div>
    <div class="brick-right face"></div>
    <div class="brick-front face"></div>
    <div class="brick-back face"></div>
  </div>
`).join('')


async function getContent(categoryId) {
  let formData = new FormData()
  formData.append('brandId', data.brandId)
  formData.append('categoryId', categoryId)
  formData.append('page', 1)
  formData.append('size', 1000)
  

  let res = await axios({
    url: data.API_BASE_URL + '/goods/list',
    method: 'POST',
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      "X-Nideshop-Token": data.token
    },
    data: formData
  })
  
  let list = res.data.data.goodsList
  let $content = document.querySelector('#content')

  // <img class="scene-icon" src="./images/img_shop_scene@2x.png" />
  let contentHTML = list.map(item => `
    <div class="commodity-item" bindtap="gotoGoods"  data-id="${item.hotIdList && item.hotIdList[0]}">
      <img class="cover" src="${item.list_pic_url}" />
      <div class="scene-icon">
        ${iconHTML}
      </div>
      <div class="item-content">
        <div class="desc">${item.name}</div>
        <div class="item-info">
          <div class="money">
            <div class="text">¥</div>
            <div class="text">${item.retail_price}</div>
          </div>
          <div class="oper">
            <div class="oper-btn add-card" catchtap="addCard" data-id="${item.id}">加入购物车</div>
            <div class="oper-btn buy-goods" catchtap="buyGoods" data-id="${item.id}">立即购买</div>
          </div>
        </div>
      </div>
    </div>
  `).join('')

  $content.innerHTML = contentHTML


  Array.from($content.querySelectorAll('.commodity-item')).forEach($item => {
    $item.addEventListener('click', function() {
      socket.emit('clientSyncAction', {
        type: 'gotoGoodsSocket',
        data: this.getAttribute('data-id')
      })

      // socket.emit('clientSyncAction', {
      //   type: 'openTag',
      //   data: Number(this.getAttribute('data-id'))
      // })
    })

    $item.querySelector('.add-card').addEventListener('click', function(ev) {
      ev.stopPropagation()
      wx.miniProgram.navigateTo({
        url: '/pages/goods/goods?id=' + this.getAttribute('data-id') + '&oper=addCard' ,
      })
      hideCommodity()
    })

    $item.querySelector('.buy-goods').addEventListener('click', function(ev) {
      ev.stopPropagation()
      wx.miniProgram.navigateTo({
        url: '/pages/goods/goods?id=' + this.getAttribute('data-id') + '&oper=buyGoods' ,
      })
      hideCommodity()
    })
  })
}


function updateSocket(options) {
  if (socket) {
    socket.close()
  }

  console.log('更新ROOM', options.roomId)

  socket = io(data.socket.socketHost, {
    path: data.socket.path,
    query: {
      ...options,
      isClient: true
    }
  })

  socket.on('clientSyncAction', data => {
    if (data.type === 'hashChange') {
      console.log(data.data)
      this.init(data.data)
    } else if (data.type === 'newRoom' && data.data && data.data.roomId) {
      console.log('新建房间', data.data)
      updateSocket(data.data)
    }
  })

  socket.emit('clientSyncAction', {
    sender: 'h5',
    type: 'loadWeb'
  })

}


function init(adata) {
  if (adata.code !== data.code) {
    setTimeout(() => getHeader())
  }
  data = adata

  if (data.reload) {
    $iframe.setAttribute('src', '')
    setTimeout(() => {
      // alert(data.url)
      $iframe.setAttribute('src', data.url)
    }, 100)

    updateSocket(data.socket.options)
  }

  console.log('postMessage ' + (data.pauseVideo ? 'pauseVideo' : 'playVideo'))
  $iframe.contentWindow.postMessage(data.pauseVideo ? 'pauseVideo' : 'playVideo', '*')

  // document.querySelector('.commodity-view').style.display = 'flex'
  document.querySelector('.commodity-view').style.display = data.open ? 'flex' : 'none'
  document.querySelector('.bgd').style.display = data.open ? 'block' : 'none'

  document.querySelector('.commodity-view').addEventListener('click', ev => ev.stopPropagation());
  document.querySelector('.layer').style.bottom = data.bottom + 'px';
}



const hideCommodity = ev => {
  socket.emit('clientSyncAction', {
    sender: 'h5',
    type: 'hideComodity'
  })
}

document.querySelector('#close-commodity').addEventListener('click', hideCommodity);
document.querySelector('.bgd').addEventListener('click', hideCommodity);


(function load() {
  init(JSON.parse(unescape(location.hash.substr(1))))
})();
