import {sendCouponResult} from '../server/api'
const app = getApp();
const globalData = app.globalData;
Component({
  properties: {
    maskSendCoupon: Number, // 是否是弹窗发券 1是 0 否
    /** 发券参数[{"stock_id": "98065001"//,"out_request_no": "89560002019101000121",}] */
    stocks: {
      type: Array,
      value: [],
      observer(v) {
        const coupon = []
        v.forEach(function (item) { // 过滤券数据
          coupon.push({stock_id: item.stock_id, out_request_no: item.out_request_no})
        })
        this.setData({coupon})
      }
    },
    /** 0|sign-签名,1|merchant-发券商户号 */
    signInfo: {
      type: Array,
    },
    tempCode: {
      type: String,
    },
  },
  data: {
    coupon: [] // 券列表
  },
  methods: {
    /** 领券  */
    async getcoupon(params) {
      console.log('领券插件回调', params.detail)
      // 写入剪切板
      wx.setClipboardData({
        data: this.data.tempCode || '',
        complete(res) {
          console.log('剪切板', res)
        }
      })

      if (params.detail.errcode === 'OK') { // 领券插件回调成功处理
        const data = params.detail.send_coupon_result
        const reportSuccess = await this.sendCouponResult(params.detail)
        const results = data.filter(function (g) { return g.code === 'SUCCESS' })
        const failArr = data.filter(function (g) { return g.code !== 'SUCCESS' })
        let success = false
        let coupon = failArr || []
        if (results.length > 0 && reportSuccess) {
          success = true
          coupon = results || []
        }
        wx.showToast({
          icon: 'none',
          title: '谢谢使用'
        })
        this.triggerEvent('sendCouponCallback', {success, coupon})
      } else {
        wx.showToast({icon: 'none', title: params.detail.msg})
        this.triggerEvent('sendCouponCallback', {success: false, coupon: []})
      }
    },
    /** 领券结果上报 */
    sendCouponResult(data) {
      console.log('globalData.appOrderNo',globalData.appOrderNo);
      return new Promise((resolve) => {
        const params = {
          token: wx._hwjShareData.token,
          openid: wx._hwjShareData.openid,
          loc_name: wx._hwjShareData.loc_name,
          path_way: this.data.maskSendCoupon || 0,
          stocks: data.send_coupon_result || [],
          requestId:globalData.appOrderNo
        }

        sendCouponResult(params).then(() => resolve(true)).catch(() => resolve(false))
      })
    }
  }
})
