// packageA/mycomponent/goodsComponent/selfParameterServicetag/selfParameterServicetag.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 详情数据
    goods_info: {
      type: null,
    },
    // 拼团结束时间
    end_time_team: {
      type: null,
    },
    gooddatas: {
      type: null,
    },
    // 商品类型
    goodsType: {
      type: null,
    },
    // 门店id
    store_id: {
      type: null,
    },
    // 活动id
    activityId: {
      type: null,
    },
    fight_groups: {
      type: null,
    },
    // 是不是门店拼团
    is_o2o: {
      type: null,
    },
    // 抢团
    team: {
      type: null,
    },
  },
  lifetimes: {
    attached(e) {
      let start_time = new Date().getTime() / 1000;
      this.setData({
        nowTime: start_time,
      });
    },
  },
  observers: {
    "gooddatas.fight_groups_number_show":function(show){
      if(show == '1'){
        this.totalGetTeamList();
      }
    },
    "goods_info,goodsType": function (datas, type) {
      this.setData({
        goodsInfo: type == "group_goods" ? datas : datas.get_goods,
        goods_plugin: datas.plugin,
      });
      // 自购省
      if (datas.plugin) {
        if (datas.plugin.selfbuy_discount) {
          this.setData({
            selfbuy_discount: datas.plugin.selfbuy_discount,
          });
        }
        if (datas.plugin.pack_fixed_price && datas.plugin.pack_fixed_price.id) {
          this.setData({
            pack_price: datas.plugin.pack_fixed_price.pack_price ? datas.plugin.pack_fixed_price.pack_price : '',
            goods_count: datas.plugin.pack_fixed_price.goods_count ? datas.plugin.pack_fixed_price.goods_count : '',
            fixId: datas.plugin.pack_fixed_price.id ? datas.plugin.pack_fixed_price.id : '',
            hasActivity: true,
          });
        }
        if (datas.plugin.prdocut_market) {
          this.setData({
            is_market: true,
            prdocut_market: datas.plugin.prdocut_market,
            prdocut_market_name: datas.plugin.prdocut_market.plugin,
            prdocut_market_name_apps: datas.plugin.prdocut_market.apps,
          });
        }
      }
      if (datas.get_goods) {
        this.init(datas.get_goods);
      }
      if(this.data.goodsType == 'group_goods'){
        this.getTeamList();
      }
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    // 抢团team
    teamLis: [],
    //自购省数据
    selfbuy_discount: null,
    //商城活动默认第一个
    firstActivityBtn: "",
    //商城活动默认第一个内容
    firstActivityCon: "",
    //商城活动数组
    activityArr: [],
    goods_plugin: [],
    //设置数据
    goodsInfo: [],
    //设置拼团数据
    gooddatas: [],
    // 当前时间
    nowTime: "",
    //活动显示隐藏
    activityShow: false,
    popupModeshow: true,
    show2: false,
    show3: false,
    teamInfo: {
      newword: false,
      totalPage: 0,
      count: 0,
      page: 1,
      listData: []
    },
    uid: wx.getStorageSync("yz_uid"),

    hasActivity: false, //一口价
    marketShow: false, // 应用市场
    // 新增规格#79514
    optionObj:{
      title:'',
      total:''
    },
    // 拼团人数字段  groupTotal
    groupTotal:{
      page:1,
      last_page:1,
      listData:[]
    },
    // 拼团次数弹窗
    showTotal:false,
    success_team_number:0,
    open_team_number:0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init(data) {
      if (data.goods_sale && data.goods_sale.sale_count != 0) {
        for (let i = 0; i < data.goods_sale.sale.length; i++) {
          if (data.goods_sale.sale[i].type == "array" && data.goods_sale.sale[i].value && data.goods_sale.sale[i].value.constructor === Array) {
            data.goods_sale.sale[i].value = data.goods_sale.sale[i].value.join('；');
          }
        }
        this.setData({
          activitySwitch: true,
          activityArr: data.goods_sale.sale,
        });
      } else {
        this.setData({
          activitySwitch: false,
        });
      }
    },
    // 活动事件
    activityShowFun() {
      this.triggerEvent("showCanSelf", false);
      this.setData({
        activityShow: true,
      });
    },
    // 活动显示
    activityShowBtn() {
      this.triggerEvent("showCanSelf", true);
      this.setData({
        activityShow: false,
      });
    },
    gotoList() {
      wx.navigateTo({
        url: "/packageC/o2o/o2oStore/o2oStore?store_id=" + this.data.goodsInfo.store_goods.store_id,
      });
    },
    gotohuiyuan() {
      if (this.data.selfbuy_discount && this.data.selfbuy_discount.link_to_level_page && this.data.selfbuy_discount.link_to_level_page.show == 1) {
        wx.navigateTo({
          url: "/packageB/member/MemberGradeList/MemberGradeList",
        });
      }
    },
    // 一口价
    toFixedPrice() {
      wx.navigateTo({
        url: "/packageE/others/fixedPrice/fixedPrice?id=" + this.data.fixId,
      });
    },
    // 应用市场
    marketShowTap(e) {
      this.setData({
        marketShow: true,
      });
    },
    closeMarketShow() {
      this.setData({
        marketShow: false,
      });
    },
    // 服务标签
    toLink(e) {
      let item = e.currentTarget.dataset.item;
      if (item.min_link) {
        wx.navigateTo({
          url: item.min_link
        });
      }
    },
    showCan() {
      this.setData({
        showCs: true,
        second_content: this.data.goodsInfo.has_many_params,
      });
    },
    closeCs() {
      this.setData({
        showCs: false,
      });
    },
    // 拼团     start
    // 显示去参团列表弹层
    showGroupMore() {
      if (this.data.goodsInfo && this.data.goodsInfo.vip_level_status && this.data.goodsInfo.vip_level_status.status == 1) {
        wx.showToast({
          icon: "none",
          title: this.data.goodsInfo.vip_level_status.tips,
          duration: 1500,
        });
        return false;
      }

      let activityStatus = ['0', '1', '2']; //activityStatus当前活动状态，顺序为未开始，进行中，已结束
      let list = this.data.teamInfo.listData;
      if (this.data.goodsType == "groupwork") {
        list = this.data.gooddatas.alliance;
        activityStatus = ['1', '2', '3'];
      }

      if (this.data.goodsType == "grabGroup") {
        if (this.data.team.length == 0) {
          wx.showToast({
            icon: "none",
            title: "抱歉，暂无更多可参与的团!",
            duration: 2500,
          });
          return;
        }
        this.setData({
          show3: true,
        });
        return;
      }
      
      if (this.data.gooddatas.status == activityStatus[1]) {
        // 活动已开启
        if (this.data.goodsType == "groupwork") {
          if (list.length == 0) {
            wx.showToast({
              title: "暂无更多可参与的团",
              icon: "none",
              duration:2500
            });
            return;
          }
          this.setData({
            show4: true,
          });
          return;
        }

        if (this.data.teamInfo.newword == false) {
          this.data.teamInfo.newword = true;
          if (this.data.teamInfo.listData.length > 0) {
            this.setData({
              show2: true,
            });
          } else {
            wx.showToast({
              title: "暂无更多可参与的团",
              icon: "none",
            });
          }
        } else if (this.data.teamInfo.newword == true && this.data.teamInfo.listData.length == 0) {
          wx.showToast({
            title: "暂无更多可参与的团",
            icon: "none",
            duration:2500
          });
        } else {
          this.setData({
            show2: true,
          });
        }
      } else if (this.data.gooddatas.status == activityStatus[0]) {
        wx.showToast({
          title: "活动未开始",
          icon: "none",
          duration:2500
        });
      } else if (this.data.gooddatas.status == activityStatus[2]) {
        wx.showToast({
          title: "活动已结束",
          icon: "none",
          duration:2500
        });
      }

      
    },
    groupTotalTap(e){
      if(e.currentTarget.dataset.key == 'close'){
        this.setData({
          showTotal:false
        })
        return
      }
      this.setData({
        showTotal:true
      })
    },
    totalGetTeamList(more = false){
      if(more){
        this.setData({
          page:this.data.page + 1
        })
      }
      let urlStr = app.getNetAddresss("plugin.fight-groups.frontend.controllers.fight-groups-goods.all-join-team-number");
      let json = {
        id:this.data.gooddatas.id,
        page:this.data.page
      };
      app._getNetWork({
        url: urlStr,
        data:json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result != 1) {
            return;
          }
          if(!more){
            this.setData({
              success_team_number:res.data.success_team_number,
              open_team_number:res.data.open_team_number,
              "groupTotal.last_page": res.data.team_member.last_page,
              "groupTotal.listData": res.data.team_member.data,
            });
          }else{
            // 加载更多
            this.setData({
              "groupTotal.last_page": res.data.team_member.last_page,
              "groupTotal.listData": this.data.groupTotal.listData.concat(res.data.team_member.data),
            });
          }
        },
      });
    },
    getTeamList() {
      let urlStr = app.getNetAddresss("plugin.fight-groups.frontend.controllers.fight-groups-goods.all-team");
      let store_id = this.data.store_id;
      if (store_id && store_id != 0 && store_id != "undefined") {
        urlStr = app.getNetAddresss("plugin.fight-groups.frontend.store.frontend-fight-groups-goods.all-team");
        urlStr += "&store_id=" + store_id;
      }
      if (this.data.fight_groups != "undefined") {
        urlStr += "&id=" + this.data.activityId;
        urlStr += "&fight_groups_goods_id=" + this.data.fight_groups;
      } else {
        urlStr += "&id=" + this.data.activityId;
      }

      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result != 1) {
            return;
          }
          if (!app._isTextEmpty(res.data.data)) {
            res.data.data.map((val) => {
              val.nowTime = new Date().getTime() / 1000;
              if (!app._isTextEmpty(val.end_time)) {
                val.overTime = val.end_time;
              }
            });
          }
          this.setData({
            "teamInfo.totalPage": res.data.last_page,
            "teamInfo.total": res.data.total,
            "teamInfo.listData": res.data.data,
          });
        },
      });
    },
    tapOverlay() {
      if (this.data.goodsType == 'groupwork') {
        this.setData({
          show4: false,
          posterShow: false,
          showOpenGroup: false,
        });
        return;
      }
      if (this.data.goodsType == "grabGroup") {
        this.setData({
          show3: false,
          posterShow: false,
          showOpenGroup: false,
        });
        return;
      }
      this.setData({
        show2: false,
        posterShow: false,
        showOpenGroup: false,
      });
    },
    // 加入该团按钮
    clickAdd(e) {
      let _id = e.target.dataset.id || e.currentTarget.dataset.id;
      if (this.data.goodsType == "groupwork") {
        wx.navigateTo({
          url: '/packageI/groupWork/groupWorkDetail/groupWorkDetail?allianceid=' + _id + '&id=' + this.data.gooddatas.id
        });
      } else if (this.data.goodsType == "grabGroup") {
        if (e.currentTarget.dataset.oneself == '1') {
          return;
        }

        if (this.data.goodsType == "grabGroup") {
          wx.navigateTo({
            url: "/packageE/grab_group/grab_group_detail/grab_group_detail?" + "&id=" + _id,
          });
        }
        return;
      } else {
        let status = e.target.dataset.item || e.currentTarget.dataset.item;
        let _team_id = e.target.dataset.id || e.currentTarget.dataset.id;

        if (this.data.goodsInfo.vip_level_status && this.data.goodsInfo.vip_level_status.status == 1) {
          wx.showToast({
            icon: "none",
            title: this.data.goodsInfo.vip_level_status.tips,
            duration: 2500,
          });
          return false;
        }

        if (status == "1") {
          // wx.showToast({
          //   title: '请点击右上角分享给好友吧',
          //   icon: 'none'
          // })
          return;
        } else {
          let that = this;
          let goods = [];
          goods.push(that.data.goodsId);
          let urlStr = app.getNetAddresss("from.div-from.isDisplay");
          urlStr += "&goods_ids=" + JSON.stringify(goods);
          app._getNetWork({
            showToastIn: false,
            url: urlStr,
            success: function (resdata) {
              var res = resdata.data;
              if (res.result == 1) {
                // var _data = res.data;
                if (res.data.status && !res.data.member_status) {
                  wx.showModal({
                    title: "提示",
                    content: "购买此商品,请补充您的个人信息",
                    success(res) {
                      if (res.confirm) {
                        //保税真实信息添加
                        wx.navigateTo({
                          url: "/packageB/member/address/myinfo/myinfo?tag=group" + "&activityId=" + that.data.activityId,
                        });
                      } else if (res.cancel) {
                        console.log("用户点击取消");
                      }
                    },
                  });
                } else {
                  wx.navigateTo({
                    url: "/packageB/member/group/GroupDetail/GroupDetail?id=" + _team_id + "&store_id=" + that.properties.store_id,
                  });
                }
              } else {
                wx.showToast({
                  icon: "none",
                  title: res.msg,
                  duration: 2500,
                });
              }
            },
            fail: function (res) {},
          });
        }
      }
    },
    showPop(e) {
      this.triggerEvent('showPop', true);
    },
    gophone(e) {
      let mobile = e.currentTarget.dataset.mobile;
      wx.makePhoneCall({
        phoneNumber: mobile,
      });
    },
    goToAdress() {
      let latitude = this.data.gooddatas.store.store.latitude;
      let longitude = this.data.gooddatas.store.store.longitude;
      let store_name = this.data.gooddatas.store.store.store_name;
      let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
      wx.openLocation({
        latitude: point.lat,
        longitude: point.lng,
        scale: 18,
        name: store_name,
      });
    },
    getMoreTeamList() {
      let urlStr = app.getNetAddresss('plugin.fight-groups.frontend.controllers.fight-groups-goods.all-team');
      if (this.properties.store_id && this.properties.store_id != 0 && this.properties.store_id != 'undefined') {
        urlStr = app.getNetAddresss('plugin.fight-groups.frontend.store.frontend-fight-groups-goods.all-team');
        urlStr += '&store_id=' + this.properties.store_id;
      }
      if (this.data.fight_groups != 'undefined') {
        urlStr += '&id=' + this.data.activityId;
        urlStr += '&fight_groups_goods_id=' + this.data.fight_groups;
      } else {
        urlStr += '&id=' + this.data.activityId;
      }
      this.data.teamInfo.page++;
      urlStr += '&page=' + this.data.teamInfo.page;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result != 1) {
            return;
          }
          var nextPageData = res.data.data;
          if (!app._isTextEmpty(nextPageData)) {
            nextPageData.map(val => {
              val.nowTime = new Date().getTime() / 1000;
              if (!app._isTextEmpty(val.end_time)) {
                val.overTime = val.end_time;
              }
            });
          }
          let listData = this.data.teamInfo.listData.concat(nextPageData);
          this.setData({
            'teamInfo.listData': listData
          });
        }
      });

    },
    // 拼团   end
    //  添加购物车
    getBuyNow(){
      this.triggerEvent('contorBuyNow_good',true);
    }
  },
});
