const config = require('../../config/config.js')
const Http = require('../../utils/HttpBasics.js')
const util = require('../../utils/util.js')
const app = getApp();

Page({
  data: {
    recentlyList: [],
    Switch: true,
    todayTimer: '',
    todayMoney: '',
    money: '',
    loading: false,
    flag: true,
    val: '',
    submitText: '确认收款',
    submitDisabled: false,
    timeCount: 0,
    showDetailIf: false,
    copenid: '',
    subappid: '',
    receiverAccount: "",
    haveData: '',
    haveIf: false,
    shijiNum: '',
    shiji1: ''
  },
  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)
    }
    // wx.navigateTo({
    //   url: '/pages/payment/mjCoupon/mjCoupon?val=' + this.data.val + '&END=' + this.data.END + '&ID=' + this.data.ID + '&TYPE=' + this.data.TYPE + '&coupon_id=' + this.data.coupon_id,
    // })
    this.setData({
      val: a.join('.'),
      coupon_id: '',
      ID: '',
      price: 0,
      title: '',
      shiji1: a.join('.'),
      phone: ''
    })
    if (this.data.price) {
      this.setData({
        haveIf: false
      })
    }
  },
  //查看收银记录
  searchDetail() {
    wx.redirectTo({
      url: '../record/list/index',
    })
  },
  //补充会员信息
  addMember() {
    wx.redirectTo({
      url: '../membersinfo/index?copenid=' + this.data.copenid + '&subappid=' + this.data.subappid,
    })
  },
  //扫码支付
  submit(e) {
    console.log(this.data.composeOrderId, "composeOrderId")
    console.log(e, Number(this.data.val))
    let _this = this;
    console.log(_this.data.val, _this.data.price / 100, _this.data.orderId)

    if (!_this.data.price) {
      // 只允许从相机扫码
      if (_this.data.val.split('.')[0] && Number(_this.data.val) > 0 && Number(_this.data.val) <= 10000000) {
        wx.scanCode({
          onlyFromCamera: true,
          success(res) {
            let postData = {
              authCode: res.result,
              totalFee: _this.data.val,
            }
            _this.setData({
              submitText: '收款中',
              submitDisabled: true
            })
            wx.showLoading({
              title: '收款中！',
            })
            if (res.result) {
              _this.orderCreate(_this, postData)
            } else {
              console.log(333)
            }
          }
        })
      } else {
        wx.showToast({
          title: '请输入有效金额！',
          icon: 'none',
          duration: 2000,
          mask: false
        });
      }
    } else {
      // 只允许从相机扫码
      if (_this.data.val.split('.')[0] && Number(_this.data.val) > 0 && Number(_this.data.val) <= 10000000 && this.data.shiji1 > 0) {
        wx.scanCode({
          onlyFromCamera: true,
          success(res) {
            let postData = {
              authCode: res.result,
              payPrice: _this.data.val,
              couponOrderId: _this.data.coupon_id,
              orderId: _this.data.composeOrderId,
            }
            _this.setData({
              submitText: '收款中',
              submitDisabled: true,
            })
            wx.showLoading({
              title: '收款中！',
            })
            if (res.result) {
              _this.orderCreate2(_this, postData)
            } else {
              console.log(333)
            }
          }
        })
      } else if (_this.data.val.split('.')[0] && Number(_this.data.val) > 0 && Number(_this.data.val) <= 10000000 && this.data.shiji1 == 0) {
        let postData = {
          authCode: '',
          payPrice: _this.data.val,
          couponOrderId: _this.data.coupon_id,
          orderId: _this.data.composeOrderId,
        }
        _this.setData({
          submitText: '收款中',
          submitDisabled: true,
        })
        wx.showLoading({
          title: '收款中！',
        })
        _this.orderCreate2(_this, postData)
      } else {
        wx.showToast({
          title: '请输入有效金额！',
          icon: 'none',
          duration: 2000,
          mask: false
        });
      }
    }
    // wx.showLoading({
    //   title: '收款中',
    // })
  },
  // 刷卡支付订单

  orderCreate(_this, postData) {
    Http.post({
      url: config.api.orderCreate,
      data: postData
    })
      .then(res => {
        console.log(res, 666)
        let postData = {
          payOrderId: res.data.payOrderId,
          orderId: res.data.orderId
        }
        _this.orderQuery(_this, postData)
      })
      .catch(err => {
        if (err.code == '1002') {
          wx.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          })
          _this.setData({
            submitText: '收款',
            submitDisabled: false
          })
        }
        let postData = {
          payOrderId: err.data.payOrderId,
          orderId: err.data.orderId
        }
        if (err.data.err_code == 'USERPAYING') {
          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.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      });
  },
  // 使用券刷卡支付订单
  orderCreate2(_this, postData) {
    Http.post({
      url: config.api.orderCreate2,
      data: postData
    })
      .then(res => {
        if (res && res.data.end == 1) {
          _this.setData({
            submitDisabled: false,
            submitText: '确认收款',
            haveIf: false
          })
          wx.hideLoading()
          wx.showLoading({
            title: '收款成功！',
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 2000);
          return
        }
        console.log(res, 666)
        let postData = {
          payOrderId: res.data.payOrderId,
          orderId: res.data.orderId
        }
        _this.orderQuery(_this, postData)
      })
      .catch(err => {
        console.log(err)
        if (err.code == 4008) {
          wx.showModal({
            title: "提示",
            content: err.message,
            showCancel: false,
            success: function (res) {
              console.log(res)
              if (res.confirm) {
                _this.setData({
                  submitDisabled: false,
                  submitText: '确认收款',
                  haveIf: false
                })
              }
            }
          })
          // _this.setData({
          //   submitDisabled: false,
          //   submitText: '确认收款',
          // })
        }
        let postData = {
          payOrderId: err.data.payOrderId,
          orderId: err.data.orderId
        }
        if (err.data.err_code == 'USERPAYING') {
          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.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      });
  },
  //  查询刷卡支付订单
  orderQuery(_this, postData) {
    Http.post({
      url: config.api.orderQuery,
      data: postData
    })
      .then(res => {
        console.log(666)
        if (this.data.price) { }
        _this.setData({
          subappid: res.data.sub_appid,
          copenid: res.data.sub_openid,
          submitText: '继续收款',
          submitDisabled: false,
          showDetailIf: true,
          timeCount: 0,
          val: '',
          // orderId: this.data.orderId
          // loading:true
        })
        wx.hideLoading()
        wx.showLoading({
          title: '收款成功！',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000);
      })
      .catch(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.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
          _this.setData({
            submitText: '继续收款',
            submitDisabled: false,
            // loading:true
          })
        }
      });
  },
  // 撤销刷卡支付订单
  orderReverse(_this, postData) {
    wx.hideLoading()
    Http.post({
      url: config.api.orderReverse,
      data: postData
    })
      .then(res => {
        console.log(666)
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
        _this.setData({
          submitText: '继续收款',
          submitDisabled: false,
          timeCount: 0,
          val: ''
          // loading:true
        })
      })
      .catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      });
  },
  onLoad: function (options) {
    console.log(options)

  },
  onShow: function (options) {

    let that = this;
    console.log(that.data)
    console.log(that.data.price, (that.data.val * 100).toFixed(2))
    if (that.data.price) {
      let shiji = ((that.data.val * 100).toFixed(2) - that.data.price) / 100
      that.setData({
        haveIf: true,
        shiji1: shiji
      })
    }
    app.globalData.userInfo().then(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) {
            console.log(res)
            if (res.confirm) {
              if (that.data.haveData == true) {
                wx.switchTab({
                  url: '/pages/main/main',
                })
              } else {
                wx.switchTab({
                  url: '/pages/main/main',
                })
              }
            }
          }
        })
      }
    }).catch(error => {
      console.log(error)
    })
  },
  /**
   * 跳转获得券
   */
  change() {
    console.log(this.data)
    console.log(this.data.val)
    let _this = this;
    if (_this.data.val.split('.')[0] && Number(_this.data.val) > 0 && Number(_this.data.val) <= 10000000) {
      if (this.data.phone) {
        wx.navigateTo({
          url: '/pages/payment/mjCoupon/mjCoupon?val=' + this.data.val + '&phone=' + this.data.phone + '&coupon_id=' + this.data.coupon_id,
        })
      } else if (this.data.END) {
        wx.navigateTo({
          url: '/pages/payment/mjCoupon/mjCoupon?val=' + this.data.val + '&END=' + this.data.END + '&ID=' + this.data.ID + '&TYPE=' + this.data.TYPE + '&coupon_id=' + this.data.coupon_id,
        })
      } else {
        wx.navigateTo({
          url: '/pages/payment/mjCoupon/mjCoupon?val=' + this.data.val,
        })
      }
    } else {
      wx.showToast({
        title: '抱歉，您还没填收款金额',
        icon: 'none',
        duration: 2000,
        mask: false
      });
    }
  },
})