const app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    showLiveCustomer: false,
    hasOnShow: true,
    prodUrl: app.globalData.prodUrl,
    goodsInfo: {},
    item_submit: false,
    onlineFlag: false,
    nowData: "",
    subPricFlag:false,
    tabData: [{
        tabText: "商品详情",
        select: 0,
        templateName: "goods-detail"
      },
      {
        tabText: "卖家承诺",
        select: 1,
        templateName: "commitment"
      },
      {
        tabText: "保证金须知",
        select: 2,
        templateName: "deposit-notice"
      },
    ],
    tabIndex: 0,
    templateName: "goods-detail",
    pageData: '',
    parameter: [],
    positionFixed: false,
    imgsrc: false,
    //下拉刷新开关
    hasMore: true,
    //服务器时间
    serverTime: '',
    setInval: '',
    setMtimeVal: '',
    serverTimeVal: '',
    checkInt: '',
    price_bidder: 0,
    new_price_bidder: 0,
    seller: true,
    user_hader: '',
    clock: true,
    submit_count: 0,
    circusee_num: 0,
    prodUrl: app.globalData.prodUrl,
    mask: false, //中拍提醒
    bindinputTime: null, // 两次手动输入的时间差
    is_first: false,
    is_pay: false,
    is_sign: false,
    options: '',
    is_abortive:'',
    video_file_id:'',
    kid : "",
    bid_content : "",
    online_sum : 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    _this.setData({
      kid : options.kid
    })
    setInterval(function() {
      _this.showTime();
    }, 1000)
    //监测访问
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/add_circusee_num',
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      data: {
        kid: options.kid
      }
    });
    _this.setData({
      kid: options.kid,
      options: options
    })
    //调用页面初始化
    // setPageData(options.kid);
    //第一次进入拉商品数据
    if (options.isshare) {
      // let getlogin = app.getLogs(app);
      app.getLogs(app).then(function() {
        _this.pageInit();
        if (app.globalData.is_first) {
          _this.setData({
            is_first: app.globalData.is_first
          });

          app.globalData.is_first = false;

          wx.request({
            url: app.globalData.prodUrl + 'web-pm/wx/pm/add_redpack',
            data: {
              persion_id: options.persionID
            },
            header: {
              'ydw-token': wx.getStorageSync('key').ydw_token
            },
            method: 'GET',
            dataType: 'json',
            responseType: 'text',
            success: function(data) {},
            fail: function(res) {},
            complete: function(res) {},
          });
        }
      }).catch(function() {});
      this.setData({
        isshare: options.isshare
      });

    } else {
      _this.pageInit();
    }

  },
  // 显示时间（北京时间）
  showTime: function() {
    var _this = this;
    var date = new Date(); 
    var h = date.getHours();  //时
    var m = date.getMinutes()  //分
    var s = date.getSeconds(); //秒
    if (h < 10) {
      h = "0" + h;
    }
    if (m < 10) {
      m = "0" + m;
    }
    if (s < 10) {
      s = "0" + s;
    }
    var nowTime = h + "时" + m + "分" + s + '秒';
    _this.setData({
      nowData: nowTime
    });
  },
  /* 页面初始化 */
  pageInit: function() {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/select_list',
      data: {
        kid: _this.data.kid
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      success: function(data) {
        console.log("页面初始化",data)
        console.log(_this.data.kid)
        console.log(wx.getStorageSync('key').ydw_token)
        var pmItem = data.data.data[0];
        _this.setData({
          bid_content: pmItem.bid_content
        })
        wx.setNavigationBarTitle({
          title: data.data.data[0].item_name
        });
        if (data.data.persion_kid === wx.getStorageSync('persion').persion.kid) {
          _this.setData({
            seller: false
          })
        };
        // 初始化服务器时间
        _this.setServerTime();
        // 存储本地需要用到的属性
        if (data.data.code) {
          _this.setData({
            serial_number: data.data.code
          })
        }
        if (data.data.record.length === 0) {
          _this.setData({
            new_price_bidder: data.data.data[0].price_start
          })
        } else {
          let price_bidder = (data.data.data[0].price_bidder + data.data.data[0].price_add).toFixed(0);
          _this.setData({
            new_price_bidder: price_bidder
          })
        }
        if (data.data.avataUrl) {
          _this.setData({
            user_hader: data.data.avataUrl
          });
        }
        var is_sign = false,
          is_pay = false;
        if (data.data.pm_offline_apply != undefined) {
          is_sign = true;
          if (data.data.pm_offline_apply.is_pay == 0) {
            is_pay = false;
          } else {
            is_pay = true;
          }
        } else {
          is_sign = false;
        }

        //如果有拍卖会,打开拍卖会
        var showLive = false;
        if (pmItem && pmItem.live_room_id) {
          if (pmItem.live_room_id.indexOf("rtmp") > -1) {
            showLive = true;
          }
        }
        _this.setData({
          showLiveCustomer: showLive,
          goodsInfo: data.data.data[0],
          live_room_id: pmItem.live_room_id,
          circusee_num: data.data.data[0].circusee_num,
          nowTime: data.data.nowtime,
          price_bidder: data.data.data[0].price_bidder == '0' ? data.data.data[0].price_start : data.data.data[0].price_bidder,
          offer_count: data.data.data[0].offer_count,
          bidRecord: data.data.record,
          submit_count: data.data.data[0].submit_count,
          parameter: data.data.data[0].bid_parameter,
          onlineFlag: data.data.data[0].auction_type == 0 ? true : false,
          is_pay: is_pay,
          is_sign: is_sign,
          is_abortive: data.data.data[0].is_abortive,
          video_file_id:data.data.video_file_id,
        });
        
        //如果轮播图片只有一张，则不显示轮播按钮
        if (data.data.imgarray.length == 1) {
          _this.setData({
            bannerImg: data.data.imgarray,
            indicatorDots: false
          })
        } else if (data.data.imgarray.length > 1) {
          _this.setData({
            bannerImg: data.data.imgarray,
            indicatorDots: true
          })
        };
        //判断是否显示保证金按钮
        if (data.data.item_submit) {
          _this.setData({
            item_submit: true
          })
        } else {
          _this.setData({
            item_submit: false
          })
        };
        // 判断是否显示设置提醒按钮
        if (data.data.data[0].bid_opening !== "未开拍") {
          _this.setData({
            clock: false
          })
        }
        //根据状态计算时间
        _this.setGoodsTime(data.data.data[0].bid_opening, data.data.data[0].time_opening, data.data.data[0].time_end);
        //设置进入页面时默标签显示商品详情
        _this.setData({
          templateName: 'goods-detail',
          pageData: data.data.imgarray
        });
        //调用1秒刷新
        _this.data.setMtimeVal = setInterval(function() {
          _this.checkState()
        }, 3000);
      }
    });
  },
 
  /** 请求数据方法 */
  onRrequestData: function() {

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.hasOnShow) {
      this.setData({
        hasOnShow: false
      });
      return;
    };
    let _this = this;
    if (_this.data.goodsInfo.kid) {
      _this.setPageData(_this.data.goodsInfo.kid);
    }
    _this.onLoad(_this.data.options);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(this.data.setInval);
    clearInterval(this.data.setMtimeVal);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.data.setInval);
    clearInterval(this.data.setMtimeVal);
    clearInterval(this.data.serverTimeVal);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var _this = this;
    return {
      title: '和我一起来看看这个拍品',
      path: '/pages/details/details?isshare=true&kid=' + _this.data.goodsInfo.kid + "&title=" + _this.data.goodsInfo.item_name + '&persionID=' + wx.getStorageSync('key').persionid,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  backHome: function() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  //每秒刷新页面状态
  checkState: function() {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/check_item_status',
      data: {
        pm_item_id: _this.data.goodsInfo.kid,
        price: _this.data.goodsInfo.price_bidder,
        live_room_id: '',
        chat_time: 0
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        console.log("id",_this.data.goodsInfo.kid)
        console.log("price",_this.data.goodsInfo.price_bidder)
        console.log("ydw-token",wx.getStorageSync('key').ydw_token)
        console.log("页面状态",data)
        _this.setData({
          online_sum: data.data.online_sum
        })
        //archive_status 是否发起关拍
        //bid_opening 开拍状态
        //offer_status 是否有人出价
        if (data.data.submit_count !== _this.data.submit_count) {
          _this.setData({
            submit_count: data.data.submit_count,
          })
        }
        if (data.data.circusee_num !== _this.data.circusee_num) {
          _this.setData({
            circusee_num: data.data.circusee_num,
          })
        }
        if(data.data.archive_status !== _this.data.goodsInfo.archive_status){
          _this.setPageData(_this.data.goodsInfo.kid);
        console.log("status1111",data.data.archive_status+"00")
        console.log("status2222",_this.data.goodsInfo.archive_status+"00")

        }
        if (data.data.offer_status) {
          _this.setPageData(_this.data.goodsInfo.kid);
          if (data.data.offer_price_persion !== wx.getStorageSync('persion').persion.kid) {
            wx.showToast({
              title: '有新的报价！',
              icon: 'none',
              duration: 3000
            });
          };
        };
        if (data.data.bid_opening !== _this.data.goodsInfo.bid_opening) {
          _this.setPageData(_this.data.goodsInfo.kid);
          if (data.data.bid_opening === '已结束' && data.data.bidding_man) {
            if (data.data.bidding_man === wx.getStorageSync('persion').persion.kid ) {
              _this.setData({
                mask: true
              })
            } else {
              wx.showToast({
                title: '竞买已结束，很遗憾您竞价失败！',
                icon: 'none',
                duration: 3000
              });
            }
          } else if (data.data.bid_opening === '已结束' && !data.data.bidding_man){
            wx.showToast({
              title: '竞买已结束，商品流拍！',
              icon: 'none',
              duration: 3000
            });
          }
        };

      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //更新页面数据
  setPageData: function(kid) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/select_list',
      data: {
        kid: kid
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        console.log("更新数据",data)
        var pmItem = data.data.data[0];
        if (data.data.data[0].price_bidder == 0) {
          _this.setData({
            new_price_bidder: data.data.data[0].price_start
          })
        } else {
          let bidder = data.data.data[0].price_bidder + data.data.data[0].price_add;
          _this.setData({
            new_price_bidder: bidder.toFixed(2)
          })

        }

        _this.setData({
          goodsInfo: data.data.data[0],
          live_room_id: pmItem.live_room_id,
          price_bidder: data.data.data[0].price_bidder == '0' ? data.data.data[0].price_start : data.data.data[0].price_bidder,
          bidRecord: data.data.record
        }, () => {
          clearInterval(_this.data.setInval);
          _this.setGoodsTime(data.data.data[0].bid_opening, data.data.data[0].time_opening, data.data.data[0].time_end);
        });
        
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //设置服务器时间
  setServerTime: function() {
    let _this = this;
    _this.data.serverTimeVal = setInterval(function() {
      _this.setData({
        nowTime: _this.data.nowTime + 1000
      });
    }, 1000);
  },
  //根据状态计算时间
  setGoodsTime: function(state, startTime, endTime) {
    let _this = this;
    if (state === "已开拍") {
      _this.data.setInval = setInterval(function() {
        var sTime = _this.data.nowTime;
        var eTime = endTime;
        _this.countDown(sTime, eTime, _this);
      }, 1000)
    } else if (state === "未开拍") {
      _this.data.setInval = setInterval(function() {
        var sTime = _this.data.nowTime;
        var eTime = startTime;
        _this.countDown(sTime, eTime, _this);
      }, 1000)
    } else if (state === "已结束") {
      var t = _this.formatDateTime(new Date(_this.data.goodsInfo.time_end))
      _this.setData({
        countDown: t
      })
    }
  },
  //转时间格式
  formatDateTime: function(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  //切换标签页
  onLoadTemplate: function(e) {
    var _index = e.currentTarget.dataset.index;
    this.cutDetails(e.currentTarget.dataset.templatename, _index)
  },
  //切换商品详情、卖家承诺、保证金须知
  cutDetails: function(template, _index, content) {
    content = content || '';
    this.setData({
      templateName: template,
      tabIndex: _index
    })
  },
  imgClickShow: function(e) {
    var selectIndex = e.currentTarget.dataset.select;
    var imgIndex = e.currentTarget.dataset.index;
    var userImages = this.data.pageData[selectIndex].userImages;
    wx.previewImage({
      current: userImages[imgIndex],
      urls: userImages,
      success: function(a, b, c) {}
    })
  },
  onFollow: function(e) {
    var _this = this;
    if (!_this.data.imgsrc) {
      _this.setData({
        imgsrc: true
      })
    } else {
      _this.setData({
        imgsrc: false
      })
    }
  },
  onPageScroll: function(e) {
    if (e.scrollTop >= 300) {
      this.setData({
        positionFixed: true
      })
    } else if (e.scrollTop < 300) {
      this.setData({
        positionFixed: false
      })
    }
  },
  // 倒计时
  countDown: function(sTime, eTime, _this) {
    var timeRemain = eTime - sTime;
    var count_down = '';
    if (timeRemain < 0) {
      _this.setData({
        countDown: '0小时0分0秒'
      })
    } else {
      var d = parseInt(timeRemain / 86400000);
      var h = parseInt((timeRemain % 86400000) / 3600000);
      var m = parseInt(((timeRemain % 86400000) % 3600000) / 60000);
      var s = parseInt((((timeRemain % 86400000) % 3600000) % 60000) / 1000);
      if (d > 0) {
        count_down = d + '天' + h + '小时' + m + '分';
      } else {
        count_down = h + '小时' + m + '分' + s + '秒';
      }
      _this.setData({
        countDown: count_down
      })
    }
  },
  //展示拍卖客服页面
  showLive: function() {
    this.setData({
      showLiveCustomer: !this.data.showLiveCustomer
    });
  },
  //减价
  reducePrice: function(e) {
    let _this = this;
    //新价格 = 当前价格 - 加价幅度
    var priceBidder = this.data.new_price_bidder - this.data.goodsInfo.price_add;
    if ((priceBidder.toFixed(2) - this.data.price_bidder) < this.data.goodsInfo.price_add) {
      wx.showToast({
        title: '出价不得低于最低加价幅度',
        icon: 'none',
        duration: 3000
      })
    } else {
      _this.setData({
        new_price_bidder: priceBidder.toFixed(2)
      })
    }
  },
  //加价
  reduceIncrease: function(e) {
    let _this = this;
    var priceBidder = Number(this.data.new_price_bidder) + Number(this.data.goodsInfo.price_add);
    _this.setData({
      new_price_bidder: priceBidder.toFixed(2)
    });
  },
  //出价
  bid: function(e) {
    let _this = this;   
    _this.setData({
      subPricFlag: true,
    })
    setTimeout(function(){
      _this.setData({
        subPricFlag: false,
      })
    },500)
    // if (_this.data.new_price_bidder)
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/compete_price',
      data: {
        pm_item_id: _this.data.goodsInfo.kid,
        price_bidder: _this.data.new_price_bidder
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        if (data.data.success) {
          wx.showToast({
            title: '恭喜您，出价成功！',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: data.data.tip.msg,
            icon: 'none'
          });
        };
        _this.setData({
          price_bidder: data.data.pm_item_submit_offer.price_bidder,
          new_price_bidder: data.data.pm_item_submit_offer.price_bidder + _this.data.goodsInfo.price_add,
          bidRecord: data.data.record
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    });
  },
  // 获取焦点：
  bidFocus: function() {
var _this =this;
_this.setData({
  subPricFlag:true,
})
  },
  // 手动输入价格
  getBidder: function(e) {
    let _this = this;
    let bidder_text;
    let bidder_num;
    if (e.detail.value.substr(0, 1) === '￥') {
      bidder_text = e.detail.value.substr(1);
      bidder_num = Number(bidder_text);
    } else {
      bidder_text = e.detail.value;
      bidder_num = Number(bidder_text);
    }
    bidder_num = bidder_num.toFixed(2);
    if ((bidder_num - this.data.price_bidder) < this.data.goodsInfo.price_add) {
      let price_bidder = (_this.data.price_bidder + _this.data.goodsInfo.price_add).toFixed(2);
      _this.setData({
        new_price_bidder: price_bidder,
        subPricFlag: false,
      })
      wx.showToast({
        title: '出价不得低于最低加价幅度',
        icon: 'none',
        duration: 3000
      });
    } else {
      _this.setData({
        new_price_bidder: Number(bidder_num),
        subPricFlag: false,
      })
    }
    // _this.setData({
    //   new_price_bidder: bidder_num
    // });
  },
  // 支付保证金
  navPayPage: function(e) {
    let _this = this;
    let onlineUrl;
    if (_this.data.onlineFlag) {
        onlineUrl = '../payDeposit/payDeposit?kid=' + _this.data.goodsInfo.kid + '&deposit=' + _this.data.goodsInfo.price_guarantee + '&auction_way=' + _this.data.goodsInfo.auction_way + "&time=" + _this.data.goodsInfo.time_opening
    } else {
      onlineUrl = '../OfflinePayment/OfflinePayment?kid=' + _this.data.goodsInfo.kid + '&deposit=' + _this.data.goodsInfo.price_guarantee
    }
    wx.navigateTo({
      url: onlineUrl,
      success: function(res) {
        clearInterval(_this.data.setInval);
        clearInterval(_this.data.setMtimeVal);
        clearInterval(_this.data.serverTimeVal);
      }
    })
  },
  //跳转出价记录
  getRecordlist:function(e){
    let _this = this;
    wx.navigateTo({
      url: '/pages/recordlist/recordlist?kid='+ _this.data.goodsInfo.kid 
    })
  },
  // 设置提醒
  formSubmit: function(e) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/add_collect',
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      data: {
        pm_item_id: _this.data.goodsInfo.kid,
        form_id: e.detail.formId
      },
      success: function(data) {
        wx.showToast({
          title: data.data.tip.msg,
          icon: 'none',
          duration: 3000,
          success: function() {

          }
        });
      },
    });
  },
  gopay: function(e) {
    wx.navigateTo({
      url: '/pages/mine/wxml/beingphotographed/beingphotographed'
    })
  },
  gopayOffline:function(){
      var _this =this;
    _this.setData({
      mask: false
    })
    wx.showToast({
      title:'请立即前往线下付款',
      icon: 'none',
      duration: 3000,
      success: function () {
      }
    });
  },
  // 点击关闭红包
  closeRedPacket: function(e) {
    this.setData({
      is_first: false
    })
  },
  //领取红包
  getRedPacket: function(e) {
    this.setData({
      is_first: false
    }, () => {
      wx.showToast({
        title: '领取成功，已存入我的红包',
        icon: 'none',
        duration: 2000
      })
    })
  },
  //跳转我的红包
  navRedPacket: function(e) {
    wx.navigateTo({
      url: '/pages/mine/wxml/myredpacket/myredpacket'
    })
  }
});