import { setShoppingCart, _GLOBAL_UI_DATA_KEY } from '../../../utils/index'
import { fhGetNursePayInfo } from '../../../api/hospital/index'
const baseUrl = require('../../../api/index.js').config
const order = require('../../../api/order.js')
const member = require('../../../api/member.js')
const map = require('../../../utils/enumMap.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    price: '',
    orderid: '',
    successlist: [],
    typeToCNMap: {},
    luckyflag: false,
    couponid: '',
    luckylist: [],
    couponlist: [],
    couponimg: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this

    let { from, trackInfo = {}, type, orderid } = options
    const groupFlag = from === 'activityGroup'
    if (groupFlag) {
      trackInfo =
        typeof trackInfo === 'string' ? JSON.parse(trackInfo) : trackInfo
    }

    const storeid = wx.getStorageSync('storeid')
    const merchantId = wx.getStorageSync('merchantid')
    that.setData({
      price: options.price,
      orderid: options.orderid,
      storeCartKey: `cart_${merchantId}_${storeid}`,
      trackInfo
    })
    setShoppingCart(`cart_${merchantId}_${storeid}`, '')
    setShoppingCart(`cart_${merchantId}_${storeid}`, '', _GLOBAL_UI_DATA_KEY)
    wx.setStorageSync('cart', '')
    var memberId = wx.getStorageSync('memberId')
    this.tempType = type
    wx.$setGlobalData('selectedCategory', null)
    type === 'nurse'
      ? this.getNursePayInfo(orderid)
      : order.takeSuccesss(
          baseUrl.waimaiUrl +
            '/client/' +
            memberId +
            '/order/' +
            that.data.orderid +
            '/pay-success',
          {},
          {},
          '加载中',
          function(res) {
            var result = res.results
            that.setData({
              successlist: result,
              typeToCNMap: map.orderType()
            })
          },
          function(err) {
            wx.showToast({
              title: '失败'
            })
          }
        )
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    setShoppingCart(this.data.storeCartKey, {}, _GLOBAL_UI_DATA_KEY)
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    setShoppingCart(this.data.storeCartKey, {}, _GLOBAL_UI_DATA_KEY)
  },
  takeDiancan: function() {
    wx.reLaunch({
      url: '/pages/home/index'
    })
  },
  takeOrder: function() {
    wx.reLaunch({
      url: `/order/list/index?type=${this.tempType}`
    })
    wx.setStorageSync('successback', 'agree')
  },
  takelucky: function() {
    var that = this
    that.setData({
      luckyflag: false
    })
  },
  getCouponid: function() {
    var that = this
    var storeid = wx.getStorageSync('storeid')
    order.takeLuckycoupon(
      baseUrl.waimaiUrl + '/client/' + storeid + '/pay-gift',
      { orderId: that.data.orderid },
      {},
      '加载中',
      function(res) {
        var result = res.results
        if (!result && typeof result != 'undefined' && result != 0) {
          that.setData({
            couponimg: false
          })
        } else {
          var test = []
          var testid = ''
          for (var i = 0; i < result.couponDtoList.length; i++) {
            test.push(result.couponDtoList[i].couponId)
          }
          var testid = test.join(',')
          that.setData({
            couponimg: true,
            couponid: testid,
            couponlist: result
          })
          that.clickLucky()
        }
      },
      function(err) {
        wx.showToast({
          title: '失败'
        })
      }
    )
  },
  // 支付红包弹窗
  clickLucky: function() {
    var that = this
    member.takeLucky(
      baseUrl.baseUrl + '/mini/coupon-templates/' + that.data.couponid,
      {},
      {},
      '加载中',
      function(res) {
        var result = res.results
        that.setData({
          luckylist: result,
          luckyflag: true
        })
        console.log(result)
      },
      function(err) {
        wx.showToast({
          title: '失败'
        })
      }
    )
  },
  clickLuckytan: function() {
    var that = this
    that.setData({
      luckyflag: true
    })
  },
  obtainCoupon: function() {
    var that = this
    var storeid = wx.getStorageSync('storeid')
    var memberid = wx.getStorageSync('memberId')
    order.drawCoupon(
      baseUrl.waimaiUrl + '/client/' + storeid + '/pay-gift/reception',
      { orderId: that.data.orderid, memberId: memberid },
      {},
      '加载中',
      function(res) {
        if (res.code == 200) {
          var result = res.results
          wx.showToast({
            title: '领取成功',
            duration: 1000,
            mask: true,
            success: function() {
              setTimeout(function() {
                //要延时执行的代码
                wx.redirectTo({
                  url: '/pages/my/coupon/coupon'
                })
                // wx.reLaunch({
                //   url: '/pages/my/coupon/coupon',
                // })
              }, 1000) //延迟时间
            }
          })
        } else if (res.code == 6003) {
          that.setData({
            luckyflag: false
          })
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      },
      function(err) {
        wx.showToast({
          title: '失败'
        })
      }
    )
  },
  // 获取护工订单支付的信息
  async getNursePayInfo(orderId) {
    try {
      const { results } = await fhGetNursePayInfo(orderId)
      this.setData({
        successlist: results,
        typeToCNMap: map.orderType()
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  }
})
