// packageI/groupWork/groupWorkDetail/groupWorkDetail.js
const app = getApp();
var yz_pay = require("../../../mycomponent/yz_pay/yz_pay");
Page({
  behaviors: [yz_pay],
  /**
   * 页面的初始数据
   */
  data: {
    alliance_id: 0, //团状ID
    goods: {},
    status: null, //参团中奖状态：1:未中奖，2:已中奖
    activity_status: 1, //团状态1:拼团中，2:拼团成功，-1:拼团失败
    spec_status: null, //该层级活动状态
    end_time: "",
    active_status: "", //活动状态文字
    timestamp: Date.parse(new Date()) / 1000, //获取当前时间戳
    countDownTime: 0,
    btnTest: "加载中...",
    Participants: [], //参团人员
    joinMember: [],
    showSpecs: false,
    groupLevel: [],

    Payshow: false,
    btnData: [], //支付方式集合,
    payKeyboardShow: false, //键盘显示

    timeData: {}, //倒计时组件
    isJoin: false, //是否已参团

    shareConfig: {}, //自定义分享信息
    isPlaying: false //防止重复支付
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.allianceid) {
      this.data.alliance_id = options.allianceid;
    }
    this.initData();
    this.getData();
  },
  onTimeChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  initData() {
    this.setData({
      showSpecs: false,
      Payshow: false,
      payKeyboardShow: false,
      isPlaying: false
    });
  },
  getData() {
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.alliance.controllers.detail.index"),
      data: {
        alliance_id: this.data.alliance_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let recordData = res.data.record;
          let Participants = [];
          let goods = {};
          goods["title"] = recordData.title;
          goods["thumb"] = recordData.thumb;
          goods["presentPrice"] = recordData.price;
          goods["group_price"] = recordData.activity_price;
          goods["person"] = recordData.person;
          goods["pay"] = recordData.person - recordData.disparity;
          this.data.joinMember = recordData.activity_detail;

          for (let i = 0; i < recordData.activity_detail.length; i += 5) {
            Participants.push(recordData.activity_detail.slice(i, i + 5));
          }

          // let stauts = recordData.activity_status; //1拼团中,2:拼团成功，-1:拼团失败
          this.setData({
            goods: goods,
            Participants: Participants,
            groupModel: recordData.spec_id,
            status: recordData.status, //团状态1:拼团中，2:拼团成功，-1:拼团失败
            spec_status: recordData.spec_status, //该层级活动状态
            active_status: this.isWarnText(recordData.status, recordData.disparity),
            countDownTime: recordData.status == 1 ? app.getTimeDifference(recordData.end_time) : 0,
            isJoin: this.isJoined(),
            btnTest: recordData.status == 1 ? (this.isJoined() ? "邀请好友" : "我要参团") : "我要开团"
          });
          if (Number(recordData.spec_status) == 3) {
            this.setData({
              btnTest: '已结束'
            });
          }
          this.data.shareConfig['title'] = recordData.desc_title;
          this.data.shareConfig['imgUrl'] = recordData.thumb;
          this.data.shareConfig['description'] = recordData.desc_content;
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: "none",
          });
        }
      },
    });
  },
  isJoined() {
    //本人是否已参团
    let uid = wx.getStorageSync("yz_uid");
    let join = this.data.joinMember.findIndex(v => {
      return v.uid == uid;
    });
    return join > -1 ? true : false;
  },
  isWarnText(status, _disparity) {
    //处理不同状态下显示文字
    let isPeopleOk = Number(_disparity) == 0 ? true : false; //是否已达到人数
    if (status == 1) {
      return "拼团中，离成团还差" + _disparity + "人";
    }
    if (status == 2) {
      return "该团已拼团成功";
    }
    if (status == -1) {
      let text = isPeopleOk ? "未中奖" : "未达到拼团人数，拼团失败";
      return text;
    }
  },
  clickBtn() {
    if (Number(this.data.spec_status) == 3) {
      wx.showToast({
        title: '已结束',
        duration: 1000,
        icon: "none",
      });
      wx.navigateTo({
        url: '/packageI/groupWork/groupWorkIndex/groupWorkIndex'
      });
      return;
    }
    if (this.data.status == 1) {
      //活动进行中
      if (!this.data.isJoin) {
        this.getGoods(); //没参团过
      }
    } else {
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?name=99&activity_id=' + this.options.id
      });
    }
  },
  countDownEnd() {
    this.setData({
      active_status: "等待抽奖..."
    });
  },
  gotoUrl(e) {
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?name=99&activity_id=' + this.options.id
    });
  },
  getGoods() {
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.goods.controllers.detail.index"),
      data: {
        record_id: this.options.id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        let goods = this.data.goods;
        goods['id'] = res.data.goods_id;
        goods['thumb'] = res.data.goods_info.thumb;
        goods['stock'] = res.data.stock;
        let groupLevel = res.data.specs.filter((v) => {
          if (v.id == this.data.groupModel) {
            goods['price'] = v.min_price;
            goods['person'] = v.person;
            return v;
          }
        }); //过滤层级，只显示之前开团参团支付的层级
        this.setData({
          goods: goods,
          groupLevel: groupLevel,
          showSpecs: true
        });
      }
    });
  },
  //获取支付类型参数
  getPayData() {
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.alliance.controllers.pay.button"),
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            btnData: res.data.buttons,
            showSpecs: false,
            Payshow: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: "none",
          });
        }
      },
    });
  },
  async payPost(e) {
    console.log(e);
    if (this.data.isPlaying) {
      return;
    }
    let _data = e.currentTarget.dataset.info;
    let json = {
      pay_type: _data.value,
      spec_id: this.data.groupModel,
      alliance_id: this.data.alliance_id,
      client_type: 2
    };

    if (_data.need_password) {
      let pass = await this.getPayKeyboardPassword(); //开启支付密码验证
      json.password = pass;
    }
    this.data.isPlaying = true;
    app._getNetWork({
      url: app.getNetAddresss('plugin.group-work.frontend.modules.alliance.controllers.apply.index'),
      data: json,
      success: (res) => {
        this.data.isPlaying = false;
        if (res.data.result === 1) {
          this.handleOtherPay(_data, _data.value, res.data, "groupWork");
          this.setData({
            Payshow: false,
            popupSpecs: false,
            showSpecs: false
          });
        } else {
          Dialog.alert({
            title: '提示',
            message: res.data.msg
          }).then(() => {
            // on close
          });
          console.error(res);
        }
      },
      fail: (res) => {
        console.error(res);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let value = wx.getStorageSync("yz_uid");
    let mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.shareConfig.title,
      path: '/packageI/groupWork/groupWorkDetail/groupWorkDetail?allianceid=' + this.options.allianceid + '&id=' + this.options.id + '&mid=' + mid,
      imageUrl: this.data.shareConfig.imgUrl
    };
  }
});