const baseUrl = require("../../../api/index.js").config;
const member = require("../../../api/member.js");
const masses = require("../../../api/masses.js");
const { charString } = require("../../../utils/util");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentflag: 0,
    preUse: [], //未使用优惠劵
    expired: [], //已过期优惠劵
    used: [], //已使用过优惠劵
    platform_preUse: [], //未使用优惠券
    platform_expired: [], //已过期优惠券
    platform_used: [], //已使用优惠券
    couponflag: "platform",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var cardNumber = wx.getStorageSync("cardNumber");
    var memberid = wx.getStorageSync("memberId");
    masses.getCouponall(
      baseUrl.waimaiUrl + `/client/members/${memberid}/coupons-all`,
      {},
      {},
      "加载中",
      function (res) {
        const { results } = res;
        const { preUse, expired, used } = that.handlerResults(results);

        that.setData({
          preUse,
          expired,
          used,
        });
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
    that.takePlatformCoupon();
  },
  takeAwait: function () {
    var that = this;
    that.setData({
      currentflag: 0,
    });
  },
  takeAlready: function () {
    var that = this;
    that.setData({
      currentflag: 1,
    });
  },
  takeoverdue: function () {
    var that = this;
    that.setData({
      currentflag: 2,
    });
  },
  takeVoucher: function () {
    wx.navigateTo({
      url: "../voucher/voucher",
    });
  },
  takerule: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    for (var i = 0; i < that.data.preUse.length; i++) {
      if (that.data.preUse[i].id == id) {
        that.data.preUse[i].ruleflag = !that.data.preUse[i].ruleflag;
      }
    }
    that.setData({
      preUse: that.data.preUse,
    });
  },
  goCoupondetail: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    if (type == 3) {
      wx.setStorageSync("coupondata", that.data.preUse[index]);
      wx.navigateTo({
        url: "../coupondetail/coupondetail",
      });
    }
  },
  jumpSaleroom: function (e) {
    var that = this;
    let storeid = e.currentTarget.dataset.storeid;
    let merchantid = e.currentTarget.dataset.merchatid;
    wx.setStorageSync("storeid", storeid);
    wx.setStorageSync("merchantid", merchantid);
    wx.setStorageSync("noid", "disagree");
    wx.navigateTo({
      url: "/store/pages/lunch/index",
    });
  },
  // 平台优惠券
  takeBusiness: function () {
    this.setData({
      couponflag: "business",
    });
  },
  takePlatform: function () {
    this.setData({
      couponflag: "platform",
    });
  },
  // 获得平台优惠券
  takePlatformCoupon: function () {
    var that = this;
    var memberid = wx.getStorageSync("memberId");
    member.takePlatformCoupon(
      `${baseUrl.waimaiUrl}/client/members/${memberid}/platform-coupons-all`,
      {},
      {},
      "加载中",
      function (res) {
        const { results } = res;
        const {
          preUse: platform_preUse,
          expired: platform_expired,
          used: platform_used,
        } = that.handlerResults(results);
        that.setData({
          platform_preUse,
          platform_expired,
          platform_used,
        });
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
  },
  // 处理返回
  handlerResults(results) {
    let { preUse, expired, used } = results;

    preUse = this.handlerCouponData(preUse);
    expired = this.handlerCouponData(expired);
    used = this.handlerCouponData(used);

    return { preUse, expired, used };
  },
  // 处理数据
  handlerCouponData(arr) {
    let nowTimeStamp = new Date().valueOf();
    return arr.map((i) => {
      let { startTime, endTime, reductionAmount, storeIds, couponDetail } = i;
      const timeStamp = new Date(startTime.replace(/-/g,'/')).valueOf();
      endTime = endTime.substring(0, 10);
      startTime = startTime.substring(0, 10);

      const timeText = `有效期${
        timeStamp > nowTimeStamp ? startTime : ""
      }至${endTime}`;

      const pointflag = (reductionAmount + "").includes(".");
      const applyflag = storeIds && (storeIds + "").includes(",");

      couponDetail = couponDetail || "";
      let returnCount = 0;
      if (couponDetail) {
        couponDetail.replace(/\n/g, function (m, i) {
          returnCount++;
        });
      }
      const rawLn = charString(couponDetail);

      return {
        ...i,
        endTime,
        ruleflag: false,
        pointflag,
        applyflag,
        timeText,
        expand: false,
        showExpand: returnCount > 2 || rawLn > 68,
      };
    });
  },
  // 处理展开与收起
  controlExpand({ currentTarget: { dataset } }) {
    const { key, index } = dataset;
    if (!key || (!index && index !== 0)) {
      return;
    }

    const { expand } = this.data[key][index];

    this.setData({
      [`${key}[${index}].expand`]: !expand,
    });
  },
});
