const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px';
const util = require("../../utils/util.js");
const config = require("../../config/config.js");
const Http = require("../../utils/HttpBasics");
const imgurl = require("../../utils/imgurl");
const AUTH_MODE = 'fingerPrint';
let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight,
    merChant: {},
    focus: true,
    inputValue: '',
    cardList: [],
    arrays: [],
    showModel: false,
    showInput: false,
    ids: "",
    wmyes: imgurl.wmyes.url,
    wmclose: imgurl.wmclose.url,
    isPwd: false,
    payCheck: 0,
    pwdSw: false,
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options');
    let that = this;
    let merChant = decodeURIComponent(options.merChant)
    that.setData({
      merChant: JSON.parse(merChant),
      cardid: options.cardid,
      cardids: options.cardid,
      remainingAmount: options.remainingAmount,
      remainingAmounts: options.remainingAmount,
      payCheck: options.payCheck * 1
    })
  },
  bindKeyInput(e) {
    console.log(e)
    this.setData({
      inputValue: e.detail.value
    })
  },

  // 关闭密码框
  contentClick(e) {
    if (this.data.pwdSw && e.target.id != 'checkPwd') {
      this.setData({
        isPwd: false,
        pwdSw: false,
        password: ''
      })
    }
  },

  inputPwd(e) {
    this.setData({
      password: e.detail.value
    })
  },

  goGetPay() {
    this.startAuth()
  },

  suretoPay: function (e) {
    let that = this;
    if (e.currentTarget.dataset.sure == 'sure' && that.data.checked) {
      wx.showLoading({
        title: '加载中...',
      })
      that.gotoPayMoney();
    } else {
      wx.showModal({
        title: '提醒',
        content: '请选择消费卡',
        showCancel: false
      })
    }
  },

  checkPwd() {
    if (!this.data.inputValue) {
      wx.showToast({
        title: '金额不能为空！',
        icon: 'error'
      })
      return
    }
    if (this.data.payCheck && !this.data.pwdSw) {
      this.setData({
        isPwd: true, // 打开密码框
        pwdSw: true // 允许点击其他区域时关闭密码框
      })
    } else {
      this.startAuth()
    }
  },

  gotoPayMoney: function () {
    let that = this;
    const startSoterAuthentication = () => {
      wx.startSoterAuthentication({
        requestAuthModes: [AUTH_MODE],
        challenge: 'test',
        authContent: '请验证已有的指纹以继续',
        success: (res) => {
          console.log(res)
          that.gotoPay()
        },
        fail: (err) => {
          console.log(err);
          wx.hideLoading();
          that.setData({
            showModel: false,
            showInput: false,
            cardid: that.data.cardids,
            ids: "",
            remainingAmount: that.data.remainingAmounts
          })
          if (err.errCode == 90008 || err.errCode == 90009) {
            // 90009 指纹验证失败
            // 90008 用户已取消
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '指纹验证后才能支付'
            })
          } else {
            that.gotoPay();
          }
        }
      })
    }
    const checkIsEnrolled = () => {
      wx.checkIsSoterEnrolledInDevice({
        checkAuthMode: AUTH_MODE,
        success: (res) => {
          console.log(res)
          if (res.isEnrolled) {
            startSoterAuthentication();
          } else {
            that.gotoPay();
          }
        },
        fail: (err) => {
          console.error(err)
          that.gotoPay();
        }
      })
    }
    wx.checkIsSupportSoterAuthentication({
      success: (res) => {
        console.log(res)
        var bfingprint = false
        for (var i in res.supportMode) {
          if (res.supportMode[i] == AUTH_MODE) {
            bfingprint = true
          }
        }
        if (bfingprint) {
          checkIsEnrolled()
        } else {
          that.gotoPay()
        }
      },
      fail: (err) => {
        console.error(err);
        that.gotoPay();
      }
    })
  },
  gotoPay: function () {
    let that = this;
    console.log(that.data.cardid)
    Http.post({
      url: config.api.cardPayOrder,
      data: {
        cardId: that.data.cardid,
        merchantId: that.data.merChant.id,
        totalFee: that.data.inputValue,
        payCheck: that.data.payCheck,
        password: that.data.password
      }
    })
      .then(res => {
        if (res.code == 200) {
          wx.hideLoading();
          that.setData({
            showModel: false,
            showInput: false,
            isPwd: false,
            pwdSw: false,
            password: ''
          })

          wx.reLaunch({
            url: `/pages/paySuccess/paySuccess?data=${JSON.stringify(res.data)}`,
          })
        }
      })
      .catch(err => {
        wx.hideLoading()
        wx.showModal({
          title: "抱歉",
          content: err.message,
          showCancel: false
        })
        that.setData({
          cardid: that.data.cardids,
          ids: "",
          remainingAmount: that.data.remainingAmounts
        })
      })
  },
  check: function (e) {
    let that = this;
    console.log(e.currentTarget.dataset.id)
    if (e) {
      if (e.currentTarget.dataset.flags == 'check') {
        that.setData({
          ids: e.currentTarget.dataset.id,
          cardid: e.currentTarget.dataset.id,
          remainingAmount: e.currentTarget.dataset.remainingamount,
          checked: true
        })
      }
    }
  },
  startAuth(e) {
    let that = this;
    if (that.data.inputValue == "" || that.data.inputValue == 0) {
      wx.showModal({
        title: '抱歉',
        content: '请输入金额',
        showCancel: false
      })
    } else if (that.data.inputValue != "" && Number(that.data.remainingAmount) < Number(that.data.inputValue)) {
      that.setData({
        showModel: true,
        showInput: 'disabled'
      })
      that.getList();
      console.log("1111")
    } else if (that.data.inputValue != "" && Number(that.data.remainingAmount) >= Number(that.data.inputValue)) {
      wx.showLoading({
        title: '加载中',
      })
      console.log("222")
      setTimeout(function () {
        wx.hideLoading();
      }, 1500)
      that.gotoPayMoney();
    }
  },
  gotonewcard: function () {
    wx.navigateTo({
      url: '/pages/discountCardList/discountCardList'
    })
    this.setData({
      showModel: false,
      showInput: false
    })
  },
  getList() {
    var that = this;
    var data = {
      pageNum: 1,
      pageSize: 100,
      couponType: "7",
      couponOrderStatus: 4
    }
    Http.get({
      url: config.api.cardorderList,
      data: data
    })
      .then(res => {
        console.log(res)
        if (res.code == 200) {
          let arrays = [];
          res.data.list.map(file => {
            if (file.remainingAmount / 100 >= that.data.inputValue) {
              file.merchantVoList.map(files => {
                if (files.id == that.data.merChant.id) {
                  file.flag = true;
                  arrays.push(file);
                }
              })
            }
          })
          console.log(arrays)
          that.setData({
            showPage: true,
            cardList: res.data.list,
            arrays: arrays,
          })
        }
      })
      .catch(err => {
        wx.showModal({
          title: '提示',
          content: err.errMsg,
          showCancel: false
        })
      })
  },
  showModel: function () {
    this.setData({
      showModel: false,
      showInput: false,
      cardid: this.data.cardids,
      ids: "",
      remainingAmount: this.data.remainingAmounts
    })
    console.log(this.data.cardid)
  },
})