// pages/Add/index.js
const config = require('../../config/config.js')
const Http = require('../../utils/http.js')
const HttpBasics = require('../../utils/HttpBasics.js')
const util = require('../../utils/util.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    paramData: null,
    isAdmin: null,
    userData: null,
    couList: [],
    couListH: [],
    pages: 1,
    page: 1,
    checkedArr: [],
    showModal: false,
    arr: [],
    dataH: [],
    quanPageNum: 1,
    quanPageSize: 15,
    quanTotalpageNum: 0,
    titleH: [],
    pageNavigationObj: null,
    submitAble: true,
    errM: '',
    codeE: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options');
    options.phone = (options.phone != 'undefined' ? options.phone : '未绑定')
    options.nickName = (options.nickName != 'undefined' ? options.nickName : '未绑定')
    this.setData({
      paramData: options,
      page: 1,
      loading: false
    });
    this.getUserInfo()
    this.getMerchentCoupon(1)
  },
  onShow: function (options) {
    this.setData({
      showModal: false,
      submitAble: true
    });
    this.getUserInfo()
    this.getMerchentCoupon(1)
  },

  getUserInfo() {
    let that = this;
    app.globalData.userInfo().then(res => {
      that.setData({
        userData: res
      })
    }).catch(err => {
      wx.showToast({
        title: '商户信息获取出错',
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },
  /**
  * 获取会员可赠送的券
  */
  getMerchentCoupon(page, dealType) {
    let that = this;
    let postData = {
      token: app.globalData.token,
      pageNum: page,
      pageSize: 6,
      sendType: 7,
      expired: 0,
      status: 0
    }
    HttpBasics.get({
      url: config.api.wxMerchantcouponSend,
      data: postData,
    })
      .then(res => {
        if (res.data && res.data.list && res.data.list.length >= 0) {
          this.setData({
            pageNavigationObj: res.data,
          })
          wx.stopPullDownRefresh();
          res.data.list.map((item, index) => {
            item.validEndDate = util.formatTime(item.validEndDate, 'yyyy-MM-dddd')
            item.validStartDate = util.formatTime(item.validStartDate, 'yyyy-MM-dddd')
            item = Object.assign(item, { checked: false })
          });
          var tmpArr = [];
          if (page == 1) {
            tmpArr = [];
          } else {
            tmpArr = that.data.couListH;
          }
          tmpArr = [...tmpArr, ...res.data.list];
          that.setData({
            page: page + 1,
            couListH: tmpArr,
          })
          if (tmpArr.length >= res.data.total) {
            that.setData({
              loading: "没有更多数据"
            })
            return false;
          } else {
            that.setData({
              loading: "小主,我在玩命加载中..."
            })
          }
        }
      })
      .catch(err => {
        wx.showToast({
          title: '玩命加载中,请检查网络连接',
          icon: 'none',
          duration: 2000,
          mask: false
        });
      });
  },
  /**
    * 刷新
    */
  onPullDownRefresh: function (e) {
    let that = this;
    that.setData({
      pageNum: 1,
      loading: false,
      page: 1,
      showModal: false,
      arr: []
    });
    that.getMerchentCoupon(1, 'fromPullDown');
  },
  onReachBottom() {
    let that = this;
    let page = that.data.page++;
    if (that.data.pageNavigationObj.pages + 1 >= page) {
      that.getMerchentCoupon(page);
    }
  },

  /**
   * 选择使用的优惠券
   */
  choicecoupon: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let item = that.data.couListH[index];
    item.checked = !item.checked;
    this.setData({
      couListH: that.data.couListH,
    });
  },
  /**
    * 确认
    */
  submitForm() {
    let selArr = this.data.couListH;
    for (let i = 0; i < selArr.length; i++) {
      this.data.arr = this.data.couListH.filter((value, index) => {
        return value.checked == true
      })
    }
    if (this.data.arr.length != 0) {
      this.setData({
        showModal: true,
        arr: this.data.arr
      })
    } else {
      wx.showToast({
        title: '抱歉，您还未选择券',
        icon: 'none',
        duration: 2000,
        mask: false
      });
    }

  },
  /**
   * 弹框确认注券
   */
  sure() {
    let that = this;
    that.data.dataH = that.data.arr.map(item => item.id)
    that.data.titleH = that.data.arr.map(item => item.title)
    that.setData({
      submitAble: false
    })
    HttpBasics.post({
      url: config.api.wxMerchantcouponhandSel,
      data: {
        wxCouponSendIds: that.data.dataH,
        cUserId: that.data.paramData.id,
      }
    })
      .then(res => {
        wx.showToast({
          title: '注券成功！',
          icon: 'none',
          duration: 2000,
          mask: false
        });
        wx.navigateTo({
          url: '/pages/editSuccess/index?type=3&titleH=' + that.data.titleH
        })
        that.setData({
          submitAble: true
        })
      })
      .catch(err => {
        // that.setData({
        //   submitAble: true,
        //   errM: err.message,
        //   codeErr: err.code
        // })
        // if (err.message){
        //   that.setData({
        //     submitAble: false 
        //   }) 
        // }
        that.setData({
          submitAble: true,
        })
        wx.showToast({
          title: err.message ? err.message : err.data,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      });
  },

  /**
   * 取消弹框
   */
  closeModal: function () {
    this.getMerchentCoupon(1)
    this.setData({
      showModal: false,
      codeErr: '',
      submitAble: true
    })
  },
})