const config = require('../../config/config.js')
const Http = require('../../utils/HttpBasics.js')
const app = getApp();
Page({
  data: {
    recentlyList: [],
    Switch: true,
    todayTimer: '',
    todayMoney: '',
    money: '',
    loading: false,
    flag: true,
    submitText: '应收0元',
    submitDisabled: false,
    timeCount: 0,
    showDetailIf: false,
    discount: null,
    message: null,
    val: '',
    haveData: '',
  },
  hideKey() {
    this.setData({
      flag: false
    })
  },
  search() {
    this.setData({
      flag: true
    })
  },
  countChange(e) {
    console.log(e)
    let a = [];
    a = e.detail.value.split('.');
    if (a.length > 1) {
      a[1] = a[1].substring(0, 2)
    }
    this.setData({
      val: a.join('.')
    })
    if (this.data.val.split('.')[0] && Number(this.data.val) > 0.01) {
      if (this.data.discountRate != '暂无折扣') {
        let submitText = (this.data.val * this.data.discountRate / 10).toFixed(2)
        this.setData({
          submitText: "应收" + submitText + '元',
          money: submitText
        })
        console.log(this.data.submitText)
      } else {
        this.setData({
          submitText: "应收" + this.data.val + '元',
          money: this.data.val
        })
      }
    }
    if (this.data.val == 0 || this.data.val == '') {
      this.setData({
        submitText: "应收0元",
        submitDisabled: false
      })
    }
  },
  searchDetail() {
    wx.redirectTo({
      url: '../record/list/index',
    })
  },
  //扫码支付
  submit(e) {
    let _this = this;
    if (_this.data.val.split('.')[0] && Number(_this.data.val) > 0.01 && Number(_this.data.val) <= 10000000) {
      wx.scanCode({
        onlyFromCamera: true,
        success(res) {
          let postData = {
            authCode: res.result,
            totalFee: _this.data.money
          }
          wx.showLoading({
            title: '收款中',
          })
          if (res.result) {
            _this.orderCreate(_this, postData)
          } else {
            console.log(333)
          }
        }
      })
    } else {
      wx.showToast({
        title: '请输入有效金额',
        icon: "none"
      })
    }

  },
  // 刷卡支付订单
  orderCreate(_this, postData) {
    Http.post({
      url: config.api.orderCreate,
      data: postData
    })
      .then(res => {
        let postData = {
          payOrderId: res.data.payOrderId,
          orderId: res.data.orderId
        }
        _this.orderQuery(_this, postData)
      })
      .catch(err => {
        console.log(err);
        let postData = {
          payOrderId: err.data.payOrderId,
          orderId: err.data.orderId
        }
        if (err.data.err_code == 'USERPAYING') {
          console.log(err.data.err_code)
          setTimeout(function () {
            _this.orderQuery(_this, postData);
            // 调用超过三次
            _this.setData({
              timeCount: _this.data.timeCount + 1
            })
          }, 3000);
        } else if (err.data.err_code == 'SYSTEMERROR' || err.data.err_code == 'BANKERROR') {
          setTimeout(function () {
            _this.orderQuery(_this, postData);
            // 调用超过三次
            _this.setData({
              timeCount: _this.data.timeCount + 1
            })
          }, 1000);
        } else {
          _this.orderReverse(_this, postData)
          wx.showModal({
            title: '提示',
            content: err.message,
            showCancel: false
          })
        }
      });
  },
  //  查询刷卡支付订单
  orderQuery(_this, postData) {
    Http.post({
      url: config.api.orderQuery,
      data: postData
    })
      .then(res => {
        console.log(666)
        wx.showModal({
          title: '支付信息',
          content: '付款成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '/pages/main/main',
              })
            }
          }
        })
      })
      .catch(err => {
        console.log(err)
        if (err.data.trade_state == 'USERPAYING') {
          if (_this.data.timeCount < 10) {
            setTimeout(function () {
              _this.orderQuery(_this, postData);
              // USERPAYING状态下， 且不超过30秒时继续调用查询
              _this.setData({
                timeCount: _this.data.timeCount + 1
              })
            }, 3000);
          } else {
            _this.orderReverse(_this, postData)
          }
        } else if (err.data.trade_state == 'BANKERROR') {
          setTimeout(function () {
            _this.orderQuery(_this, postData);
          }, 5000)
        } else if (err.data.trade_state == 'SYSTEMERROR') {
          setTimeout(function () {
            _this.orderQuery(_this, postData);
          }, 3000);
        } else {
          _this.orderReverse(_this, postData)
          wx.showModal({
            title: '提示',
            content: err.message,
            showCancel: false
          })
        }
      });
  },
  // 撤销刷卡支付订单
  orderReverse(_this, postData) {
    wx.hideLoading()
    Http.post({
      url: config.api.orderReverse,
      data: postData
    })
      .then(res => {
        console.log(666)
        wx.showModal({
          title: '提示',
          content: err.message,
          showCancel: false,
          success: function (res) {
            console.log(res);
            if (res.cancel) {
              console.log("cancle")
              //点击取消,默认隐藏弹框
            } else {
              console.log("yes")
              this.setData({
                submitText: '扫码收款',
                submitDisabled: false,
                timeCount: 0,
                // loading:true
              })
            }
          },
          fail: function (res) {
            console.log("fail")
          }, //接口调用失败的回调函数
          complete: function (res) { }, //接口调用结束的回调函数（调用成功、失败都会执行）
        })

      })
      .catch(err => { });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options')
    this.setData({
      message: options,
      discountRate: options.discountRate
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    let that = this;
    app.globalData.userInfo().then(res => {
      console.log(res)
      that.setData({
        userInfo: res
      })
      if (res && res.merchant_id) {
        that.findAccountById(res);
        that.findJurisdiction()
      }
    })
  },
  /**
   * 查询是否有修改账户权限
   */
  findJurisdiction() {
    Http.get({
      url: config.api.permitModifiy,
    }).then(res => {
      console.log(res)
      /**
       * data:true
       * 如有：显示
       * 没有；不显示
       */
      if (res && res.data == true) {
        this.setData({
          haveData: true,
        })
      } else {
        this.setData({
          haveData: false,
        })
      }
    }).catch(error => {
      console.log(error)
    })
  },
  /**
   * 查询收款账户状态
   */
  findAccountById(response) {
    let that = this;
    Http.get({
      url: config.api.findAccountById,
      data: {
        id: response.merchant_id
      }
    }).then(res => {
      /**
       * receiverAccount
       * 如有：已设置收款账户
       * 没有；未设置收款账户
       */
      if (res && res.data && res.data.receiver) {
        that.setData({
          receiverAccount: res.data.receiver.receiverAccount
        })
      } else {
        wx.showModal({
          title: '提醒',
          content: '您暂未配置收款账户,请配置',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              if (that.data.haveData == true) {
                wx.navigateTo({
                  url: `/pages/accountManagement/index?merchant_id=${response.merchant_id}&merchant_name=${response.merchant_name}`,
                })
              } else {

                wx.switchTab({
                  url: '/pages/main/main',
                })
              }
            }
          }
        })
      }
    }).catch(error => {
      console.log(error)
    })
  }
})