// pages/address/address.js
const getReq = require('../../config.js').getReq
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    firstLoad: true,
    fromPerson: false,
    card_type: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { card_type } = options
    app.setCardType(card_type)
    console.log(card_type)
    this.setData({ card_type })
    this.getDatas()
    let len = getCurrentPages().length
    let prev = getCurrentPages()[len - 2] 
    if(prev['route'].indexOf('/myhome/myhome') != -1) {
      this.setData({
        fromPerson: true
      })
    }
  },
  getDatas() {
    wx.showLoading({
      title: '加载中',
    })

    const params = {
      act: 'member_card',
      op: 'card_list',
      card_type: this.data.card_type  //petrochina -> 中石油; sinopec -> 中石化; phone-> 手机卡; 不填的时候，返回所有
    }

    getReq(app,params, res => {
      wx.hideLoading()
      if (res.code == 200) {
        let list = res.datas.card_list
        if(!list.length) {
          app.clearRecord()
        }
        this.setData({
          list,
          firstLoad: false
        })
      }
      else {
        app.showToast(res.message)
      }
    })
  },
  check_record(e) {
    if(this.data.fromPerson) return;
    const dataset = e.currentTarget.dataset
    const { record } = dataset
    app.checkCurrentRecord(record)
    wx.navigateBack()
  },
  modify_address(e) {
    const dataset = e.currentTarget.dataset
    const { record } = dataset
    const { card_no, card_type, topcard_id } = record
    app.navigateto(`/pages/postageDetail/postageDetail?card_no=${card_no}&card_type=${card_type}&topcard_id=${topcard_id}`)
  },
  del_address(e) {
    const dataset = e.currentTarget.dataset
    const { record } = dataset
    const { topcard_id } = record
    wx.showModal({
      content: "确认删除此卡号吗",
      confirmText: "确定",
      cancelText: "取消",
      success: res => {
        if (res.confirm) {
          getReq(app,{
            act: 'member_card',
            op: 'card_del',
            topcard_id
          },  res => {
            if (res.code == 200) {
              this.getDatas()
            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.firstLoad) {
      this.setData({ card_type: app.globalData.card_type })
      this.getDatas()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})