const requireCustom = wx.requireCustom
const customRequest = requireCustom(9887)
// S.Jv 生成 returnUrl
const S = requireCustom(2012)
// ko.A.getOpenId 获取 openid
const ko = requireCustom(3816)
// Uo.JV 获取 dmChannel
const Uo = requireCustom(5059)
// 生成 s1-s7 的参数
const Oo = requireCustom(3716)

Page({
  data: {

  },
  async onLoad(options) {
    let detailResult = await this.getDetail('1001240724661')

    if (detailResult[0]) {
      this.showToast(detailResult[0].message)
      return
    }

    this.setData({
      detailResult: detailResult[1],
    })

    // let ticketPrice = await this.calcTicketPrice()

    // if (ticketPrice[0]) {
    //   this.showToast(ticketPrice[0].message)
    //   return
    // }

    // this.setData({
    //   ticketPriceResult: ticketPrice[1],
    // })

    let orderBuildResult = await this.buildOrder()

    if (orderBuildResult[0]) {
      this.showToast(orderBuildResult[0].message)
      return
    }

    this.setData({
      orderBuildResult: orderBuildResult[1],
    })

    let createOrderResult = await this.createOrder()

    if (createOrderResult[0]) {
      this.showToast(createOrderResult[0].message)
      return
    }

    this.setData({
      orderCreateResult: createOrderResult[1],
    })

    const payInfo = JSON.parse(decodeURIComponent(createOrderResult[1].alipayWapCashierUrl))

    wx.requestPayment({
      signType: 'MD5',
      timeStamp: payInfo.timeStamp + '',
      nonceStr: payInfo.nonceStr,
      package: payInfo.package,
      paySign: payInfo.paySign,
      success: function (e) {
        if ('requestPayment:ok' === e.errMsg) {
          wx.showToast({ title: '支付成功', icon: 'none' })
        } else {
          wx.showToast({ title: '支付失败', icon: 'none' })
        }
      },
      fail: function () {
        wx.showToast({ title: '拉起支付失败', icon: 'none' })
      },
    })
  },

  onReady() {},

  onShow() {},

  onHide() {},
  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
    })
  },
  getDetail(itemId) {
    const param = {
      bizCode: 'ali.china.damai',
      scenario: 'itemsku',
      itemId,
      exParams: JSON.stringify({
        dataType: 4,
        dataId: '',
        activityId: '',
      }),
    }

    return new customRequest.p({
      ...this.data.getDetailParam,
      ...param,
    }).create()
  },
  calcTicketPrice() {
    const calculatePriceControl = this.data.detailResult.actionControl.calculatePriceControl
    const itemBasicInfo = this.data.detailResult.itemBasicInfo
    const perform = this.data.detailResult.perform
    const sku = perform.skuList[perform.skuList.length - 1]

    const param = {
      itemId: itemBasicInfo.itemId,
      performId: perform.performId,
      calculateTag: calculatePriceControl.calculateTag,
      skuParamListJson: JSON.stringify([
        {
          priceId: sku.priceId,
          price: Number(sku.price),
          count: 1,
        },
      ]),
      exParams: {},
    }

    return new customRequest.p({
      ...this.data.ticketPriceParam,
      ...param,
    }).create()
  },
  buildOrder() {
    const itemBasicInfo = this.data.detailResult.itemBasicInfo
    const perform = this.data.detailResult.perform
    const exParams = {
      channel: 'damai_app',
      damai: '1',
      umpChannel: '100031002',
      subChannel: 'damai@weixin_weapp',
      atomSplit: 1,
      signKey: itemBasicInfo.t,
      rtc: this.data.detailResult.actionControl.tradeControl.rtc ? 1 : 0,
    }

    const param = {
      buyNow: true,
      exParams: JSON.stringify({
        ...exParams,
        serviceVersion: '2.0.0',
        customerType: 'default',
      }),
      buyParam: itemBasicInfo.itemId + '_' + 1 + '_' + perform.skuList[0].skuId,
    }

    this.setData({
      dataTags: param,
    })

    const currentPages = getCurrentPages()
    const lastE = currentPages.length - 1
    currentPages[lastE].options = {
      ...param,
      exParams: JSON.stringify({
        ...exParams,
        subChannel: 'weapp@damai_h5',
      }),
      spm: 'a2obt.project.bottom.dbuy',
    }

    return new customRequest.p({
      ...this.data.orderBuildParam,
      ...param,
      ext_querys: {
        ttid: this.data.ttid,
      },
      headers: {
        globalCode: this.data.globalCode,
      },
      ext_headers: {
        globalCode: this.data.globalCode,
      },
    }).create()
  },
  async createOrder() {
    const itemBasicInfo = this.data.detailResult.itemBasicInfo
    const perform = this.data.detailResult.perform
    const buildResult = this.data.orderBuildResult
    const global = buildResult.global

    const step1 = {
      subChannel: Uo.JV(),
      returnUrl: S.Jv({
        page: 'shows_pay_result',
        query: {
          itemId: itemBasicInfo.itemId,
        },
      }),
      serviceVersion: '2.0.0',
      wxOpenId: ko.A.getOpenId(),
    }

    const step2 = {
      $taroTimestamp: Date.now(),
      ...this.data.dataTags,
      isQuickBuy: false,
      isSpliceOrder: false,
      itemId: itemBasicInfo.itemId,
      quantity: '1',
      skuId: perform.skuList[0].skuId,
      spm: 'a2obt.project.buttom.dbuy',
    }

    const dataTags = this.genDataTags(step2)
    if (dataTags) {
      step1.dataTags = dataTags
    }

    const blocks = buildResult.hierarchy.structure.dmViewerBlock_DmViewerBlock
    const compName = blocks[blocks.length - 1]
    const data = buildResult.data
    data[compName]['componentDataName'] = compName
    data[compName]['componentType'] = 'dmviewer'
    data[compName]['inParentIndex'] = 1
    data[compName]['isInParentLastIndex'] = true
    data[compName]['parentComponentName'] = 'dmViewerBlock_DmViewerBlock'
    data[compName]['submit'] = true
    data[compName].fields.selectedNum = 1
    data[compName].fields.viewerList[6].isUsed = true

    const requestData = {
      params: JSON.stringify({
        data: JSON.stringify(data),
        linkage: JSON.stringify({
          common: buildResult.linkage.common,
          signature: buildResult.linkage.signature,
        }),
        hierarchy: JSON.stringify({
          structure: buildResult.hierarchy.structure,
        }),
      }),
      feature: JSON.stringify(step1),
    }

    requestData[global.secretKey] = global.secretValue

    const s17 = await Oo.A.getWasmHeader(itemBasicInfo.itemId)

    const h = JSON.stringify({
      ...s17,
      ...JSON.parse(requestData.feature),
    })

    console.log('h', h)

    const v = {
      ...requestData,
      feature: h,
    }

    const param = {
      ...this.data.orderCreateParam,
    }

    const querys = {
      isSec: 1,
      AntiCreep: true,
      ttid: this.data.ttid,
      tb_eagleeyex_scm_project: '20190509-aone2-join-test',
    }

    querys[global.secretKey] = global.secretValue

    return new customRequest.p({
      ...this.data.orderBuildParam,
      ...param,
      data: v,
      ext_querys: querys,
      headers: {
        globalCode: this.data.globalCode,
      },
      ext_headers: {
        globalCode: this.data.globalCode,
      },
    }).create()
  },
  genDataTags(param) {
    const result = []

    if (param.utm) {
      result.push('utm:'.concat(param.utm))
    }

    if (param.sqm) {
      result.push('sqm:'.concat(param.sqm))
    }

    return result.length > 0 ? result.join(';') : ''
  },
})
