var t = require("../../../../utils/util.js"),
  ut = t,
  e = require("../../../../utils/common.js"),
  a = require("../../../../utils/wxParse/wxParse.js"),
  s = getApp(),
  i = s.request,
  rq = i,
  oo = s.globalData,
  o = s.globalData.setting,
  os = o;
var regeneratorRuntime = require('../../../../utils/runtime.js');
var  e = getApp(),oo = e.globalData.setting;

Page({
  data: {
    wu:false,
    imageurl: os.imghost,//有礼派图片地址,
    iurl:  os.imghost,//有礼派图片地址,
    pt_state:0,
    order : null,//订单数据
    currentTab: 0,
    current:0,
    ordertx:[],//头像
    baseUrl: "/api/weshop/order/page?1=1",
    resourceUrl: e.globalData.setting.resourceUrl,
    currentPage: 1,
    requestData: null,
    original_img:null,
    timer:null,
  },
  onLoad: function () {
    this.data.requestData=new Array();
    this.init(0);
    wx.setNavigationBarTitle({ title: "我的拼团",})
  },
  onShow:function(){
    var th=this;
    //设置全局定时器
    th.data.timer=setInterval(function () {
      th.countDown();
    },1000);
  },

  /**
  * 点击tab切换
  */
  swichNav: function (e) {
    this.data.requestData=[];
    this.data.currentPage=1;
    var that = this;

    if (that.data.order == null){
      that.setData({
        wu:true
      })
    }

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
      that.init(e.target.dataset.current);
    }
  },
  
  async init(current) {
    var where="1=1";
    var user_id = getApp().globalData.user_id;
    switch (current){
       case "1":
        where+="&pt_status=1";
         break;
      case "2":
        where += "&pt_ok=1";
        break;
      case "3":
        where += "&pt_status=3";
        break;
    }

    var goods_id = 0,//商品ID,
      original_img = [],//商品图片
      ee = this,
      ordertx=[],//头像
      order = null,//订单数据
      goods = null,//商品数据
      users = null,//会员数据
      order_goods=null,//订单商品表
      team_g=null;


    //获取订单表的信息根据活动user_id,pt_prom_id>0 AND pay_time>0
    await getApp().request.promiseGet("/api/weshop/order/pageTuanNew?"+where, {
      data: { is_pt:1,store_id: os.stoid, user_id: user_id, pageSize: 6, page: this.data.currentPage,}
    }).then(res => {
       order = res.data.data.pageData;
       this.data.currentPage++;
    })


    wx.showLoading({ title: "加载中"});
    if(order && order.length){
      for (i = 0; i < order.length; i++) {

        //编号空，就进入下个循环
        if(!order[i].pt_listno) continue;
        //获取teamgroup中的值
        await getApp().request.promiseGet("/api/weshop/teamgroup/page", {
          data: { store_id: os.stoid, listno: order[i].pt_listno,pageSize:1,page:1}
        }).then(res => {
          team_g = res.data.data.pageData[0]
        })


        switch (team_g.goods_type){
          case 0:
            //获取订单从表信息
            await getApp().request.promiseGet("/api/weshop/ordergoods/pageGoods", {
              data: { store_id: os.stoid, order_id: order[i].order_id }
            }).then(res => {
              order_goods = res.data.data.pageData;
              order[i].order_goods = order_goods;
              order[i].gimage = ee.data.imageurl + order_goods[0]?.original_img;
            })

            //获取订单表信息根据上面查询的订单号order[i].pt_listno
            await getApp().request.promiseGet("/api/weshop/order/pagePtList", {
              data: { store_id: os.stoid, pt_listno: order[i].pt_listno,pageSize:60,page:1}
            }).then(res => {
              //console.log("ordertx");
              ordertx = res.data.data.pageData;
              //console.log(ordertx);
              order[i].tx=ordertx;
            })
            //获取预存使用金额
            await getApp().request.promiseGet("/api/weshop/orderMore/get/" + os.stoid + "/" + order[i].order_sn, {
            }).then(res => {
              if (res.data.code == 0 && res.data.data) {
                // data[ind].use_commission = res.data.data.use_commission;
                order[i].pre_cut = res.data.data.pre_cut; //是否使用预存，如果是使用预存不能单品退，只能整单退
                order[i].pre_json = res.data.data.pre_json; //是否使用预存，如果是使用预存不能单品退，只能整单退
              }
            })
            break;

          case 1:

            order[i].goods_type=1;
            order[i].pre_cut=0;

            //获取order信息根据订单编号order_sn
            await getApp().request.promiseGet("/api/weshop/rechargeServicelist/page", {
              data: { store_id: os.stoid, order_id: order[i].order_id,}
            }).then(res => {
              order_goods = res.data.data.pageData;
              order_goods[0].goods_num=order_goods[0].qty;
              order_goods[0].goods_price=order_goods[0].price;
              order[i].order_goods = order_goods;
            })


            //pt_tail_money  在从表
            order[i].pt_tail_money=order_goods[0].pt_tail_money;

            //-- 获取商品信息 --
            await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + os.stoid + "/" + order_goods[0].card_id, {
            }).then(res => {
              //-- 商品地址 --
              order[i].gimage = ee.data.imageurl + res.data.data.imgUrl
              order[i].order_goods[0].goods_name= res.data.data.serviceName;
            })

            //-- 多少人参团头像 --
            await getApp().request.promiseGet("/api/weshop/rechargeServicelist/pagePtList", {
              data: {
                store_id: o.stoid,
                pt_listno: team_g.listno,
              }
            }).then(res => {
              ordertx = res.data.data.pageData;
              order[i].tx=ordertx;
            })

            break;
        }


        if (order[i].is_zsorder== 4) {
          var num = 0;
          var jt_data = JSON.parse(order[i].ct_rylist);
          for (var m in jt_data) {
            if (jt_data[m].rynum > num) num = jt_data[m].rynum;
          }
          order[i].max_ct_num = num;
        }

        var head=[];
        if(team_g.is_xuni_ct)  {
          head=team_g.xuni_head_id.split(",");
          order[i].is_xuni_ct=1;
        }

        var sf_num = order[i].ct_num;
        if (order[i].ct_num>=3){ sf_num=3;}
        sf_num=sf_num-ordertx.length;
        if(sf_num>0) {
          var arr = [];
          for(var j=0;j<sf_num;j++){
            if(team_g.is_xuni_ct){
              arr.push(head[j]);
            }else{
              arr.push(j);
            }

          }
          order[i].sf_num=arr;
        }

      }
      //设置值
      for (var ii = 0; ii < order.length;ii++){
        this.data.requestData.push(order[ii]);
      }
    }




    wx.hideLoading();
    ee.setData({ order: this.data.requestData, ordertx: ordertx, isgo:1});
  },
  
  //---滚动到底部加载更多---
  onReachBottom: function () {
    this.init(this.data.currentTab);
  },

  resetData: function () {
    n.resetConfig(), this.data.order = null, this.data.currentPage = 1;
  },

  //----跳转到拼单success展示-----
  go_team_success:function(e) {
     var order_sn=e.currentTarget.dataset.ordsn;
     var goods_type=e.currentTarget.dataset.goods_type;
     var url="/packageG/pages/team/team_success/team_success?ordersn=" + order_sn;
     if(goods_type==1){
       url="/packageA/pages/serviceCard_pd/team_success/team_success?ordersn=" + order_sn;
     }
     getApp().goto(url);

  },

  onHide:function(){
    //--清理定时器--
    clearInterval(this.timer);
  },

  //----倒计时函数-----
  countDown() {
    var th=this;
    // 获取当前时间，同时得到活动结束时间数组
    let newTime =ut.gettimestamp();
    var endTimeList = this.data.order;
    
    if(endTimeList==null) return null
    // 对结束时间进行处理渲染到页面
    for (var i = 0; i < endTimeList.length;i++){
      var o = endTimeList[i];
      if(o.kt_end_time==undefined) continue;
      var endTime = o.kt_end_time;
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0){
        let time = (endTime - newTime);
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day), hou: this.timeFormat(hou), min: this.timeFormat(min), sec: this.timeFormat(sec)
        }
      }else{
        //活动已结束，全部设置为'00'
        obj = { day: '00', hou: '00', min: '00', sec: '00' }
      }
      
      var txt ="order["+i+"].djs";
      th.setData({ [txt]: obj});
    }
  },
  //---小于10的格式化函数----
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },

  images_err:function(e){
      var txt = e.currentTarget.dataset.err;
      var ob={};
      ob[txt] = this.data.imageurl + "/miniapp/images/default_g_img.gif";
      this.setData(ob);
  }


})

