const requireCustom = wx.requireCustom
const customRequest = requireCustom(9887)
const utils = requireCustom(1395);

Page({
  data: {
    keyword: '',
    searched: false,
    results: [],
    searchParam: {
      api: 'mtop.damai.mec.aristotle.get',
      v: '3.0',
      data: {},
    },
  },

  onKeywordInput(e) {
    this.setData({ keyword: e.detail.value })
  },

  async onSearch() {
    const keyword = (this.data.keyword || '').trim()
    this.setData({ searched: true })

    const param = {
      args: JSON.stringify({
        pageNo: 1,
        keyword: keyword,
        comboDamaiCityId: 852,
        comboChannel: 4,
      }),
      patternName: 'searchHome',
      patternVersion: '5.3'
    }

    const config = {
      downgradeOpt: {
        reqParam: {
          pageIndex: 1,
          patternName: 'searchHome',
          patternVersion: '5.3',
          urlElements: ['searchHome', '5.3', 'bak', 4, '3.0', keyword],
          useCdnWhenNodesNull: false
        }
      }
    }

    const result = await this.buildSearchRequest(param, config)

    if (result[0]) {
      wx.showToast({
        title: result[0].message,
        icon: 'none'
      })
      return;
    }

    const data = result[1];
    const nodes = data.nodes;
    const nodesLevel1 = nodes[0]
    const nodesLevel2 = nodesLevel1.nodes

    if (!nodesLevel2[0].nodes) {
      this.setData({
        results: []
      })
      wx.showToast({
        title: '没有搜到对应的演出~',
        icon: 'none'
      })
      return
    }

    const nodesLevel3 = nodesLevel2[0].nodes;
    const resultNodes = [];

    for (let i = 0; i < nodesLevel3.length; i++) {
      const nodeData = nodesLevel3[i].data;
      resultNodes.push({
        id: nodeData.id,
        imageUrl: nodeData.verticalPic,
        title: nodeData.cityName + '|' + nodeData.name,
        time: nodeData.showTime,
        location: nodeData.cityName + ' ' + nodeData.venueName,
        price: nodeData.priceStr,
        statusText: nodeData.showStatus.desc
      });
    }

    this.setData({
      results: resultNodes
    })
  },
  onItemTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/pages/custom/detail?id=${id}` });
  },
  buildSearchRequest(param, config) {
    return new customRequest.p({
      ...this.data.searchParam,
      ...param,
      downgradeConfig: config
    }).create();
  }
})
