// pages/product/productDetail/productDetail.js
let app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    proId: 0,
    isMember: 0,
    photo: '',
    address: '',
    name: '',
    account: '',
    header: {
      imgCoverIndex: 1,
      imgCover: [],
      title: '',
      b2CPrice: 0,
      b2BPrice: 0,
      dayNum: 0,
      nightNum: 0,
      startCityName: '',
      priceNum: 0,
      priceList: [],
      priceMore: false,
      flightShow: true,
      flightList:[],
      tcid:'',
    },
    menuIndex: 0,
    toView: 'scroll_view_1',
    heightArr: [],
    containerH: 0,
    // 行程特色
    tripSpecial: '',
    // 多日行程
    tripDays: {},
    // 费用说明
    tripCost: {
      feeInclude: '',
      feeNonInclude: ''
    },
    // 预定须知
    tripReserve: {
      importantTip: '',
      warmTip: '',
      b2BRemark: '',
      shopRemark: '',
      visaRemark: ''
    },
    featureType:0,
    shareInfo:{
      companyName:'',
      peopleName:'',
      phone:''
    },
    isOpenShare:false,
    shareSource:{
      c:null,
      pe:null,
      ph:null
    },
    loginInfo: 'false',
    dataList: [],
    tcid:null,
    priceView: false,
    videoStr: null,
    videoShow: false,
  },

  /**
   * 获取详情数据 (日期, 开始时间, 结束时间)
   */
  setVideoShow: function () {
    this.setData({
      'videoShow': !this.data.videoShow
    })
  },
  computedTime: function (date, startTime, endTime) {
    date=date.replace(/-/g, "/")
    //开始时间
    let startDate = date + ' ' + startTime;
    //结束时间
    let endDate = date + ' ' + endTime;
    //时间差的毫秒数
    var date3 = new Date(endDate).getTime() - new Date(startDate).getTime();
    if (date3 < 0) {
      date3 = date3 + 24*3600*1000
    }
    //计算出相差天数
    var days = Math.floor(date3 / (24 * 3600 * 1000))

    //计算天数后剩余的毫秒数
    var leave1 = date3 % (24 * 3600 * 1000)
    //计算出小时数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算小时数后剩余的毫秒数
    var leave2 = leave1 % (3600 * 1000)
    //计算相差分钟数
    var minutes = Math.floor(leave2 / (60 * 1000))
    //计算分钟数后剩余的毫秒数
    var leave3 = leave2 % (60 * 1000)
    //计算相差秒数
    var seconds = Math.round(leave3 / 1000)
    // alert("相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒")
    let text = '约' + hours + "小时" + minutes + "分"
    return text
  },
  priceViewShow: function () {
    this.setData({
      priceView: !this.data.priceView
    })
  },
  /**
   * 获取详情数据
   */
  getDetail: function(id) {
    app.$api('b2b_get_GetB2BTravelInfoNoDes', {
      configId: id,
    }).then(res => {
      var weekday = ["日", "一", "二", "三", "四", "五", "六"];
      this.setData({
        'dataList': res
      })
      let src = res.videoStr ? res.videoStr : null;
      if (src) {
        this.setData({
          'videoStr': src.indexOf('http') > -1 ? src : 'https://reborndev.oss-cn-hangzhou.aliyuncs.com' + src
        })
      }
      let minPriceIndex = 0;
      for (let i = 0; i < res.priceList.length; i++) {
        if (app.state.admin.account && this.data.isMember === 1) {
          if (res.priceList[i].b2BMemberPrice < res.priceList[minPriceIndex].b2BMemberPrice) {
            minPriceIndex = i
          }
        } else if (app.state.admin.account && this.data.isMember !== 1) { 
          if (res.priceList[i].b2BPrice < res.priceList[minPriceIndex].b2BPrice) {
            minPriceIndex = i
          }
        } else if (!app.state.admin.account) {
          if (res.priceList[i].b2CPrice < res.priceList[minPriceIndex].b2CPrice) {
            minPriceIndex = i
          }
        }
        let myDate = new Date(res.priceList[i].startDate)
        res.priceList[i]['myDate'] = (myDate.getMonth() + 1) + '-' + myDate.getDate() + '余' + res.priceList[i].remainNum
        if (i === 0) {
          res.priceList[i]['myDateTitle'] = (myDate.getMonth() + 1) + '-' + myDate.getDate()
        }
        for (let k = 0; k < res.priceList[i].priceFlight.length; k++) {
          let flight = res.priceList[i].priceFlight[k]
          let timeDifference = this.computedTime(flight.startDate, flight.departureTime, flight.arrivalTime)
          res.priceList[i].priceFlight[k]['timeDifference'] = timeDifference
        }
      }
      let tripDays = this.setupData(res.dayList)
      for (let j = 0; j < tripDays.length; j++) {
        if (tripDays[j].title && tripDays[j].title.constructor === String) {
          tripDays[j].title = [{'text': tripDays[j].title}]
        }
        if (tripDays[j].jiu2 && tripDays[j].jiu2.constructor === Array) {
          tripDays[j].jiu2 = tripDays[j].jiu2.join(' / ')
        }
      }
      wx.setNavigationBarTitle({
        title: res.title
      })
      if (res.feature.featureType<4)
        if (res.feature.featureContent) {
          WxParse.wxParse('article', 'html', res.feature.featureContent, this, 0);
        }
      this.setData({
        // 头部数据
        'header.imgCover': JSON.parse(res.imgCover),
        'header.title': res.title,
        'header.b2CPrice': res.priceList.length>0 ? res.priceList[minPriceIndex].b2CPrice : -1,
        'header.b2BPrice': res.priceList.length > 0 ? (this.data.isMember === 1 ? res.priceList[minPriceIndex].b2BMemberPrice : res.priceList[minPriceIndex].b2BPrice) : -1,
        'header.dayNum': res.dayNum,
        'header.nightNum': res.nightNum,
        'header.startCityName': res.startCityName,
        'header.priceList': res.priceList,
        // 行程特色数据
        'tripSpecial': res.feature.featureHtmlImage,
        // 多日行程数据
        'tripDays': tripDays,
        // 费用说明数据
        'tripCost.feeInclude': res.feature.feeInclude,
        'tripCost.feeNonInclude': res.feature.feeNonInclude,
        // 预定须知数据
        'tripReserve.importantTip': res.feature.importantTip,
        'tripReserve.warmTip': res.feature.warmTip,
        'tripReserve.b2BRemark': res.feature.b2BRemark,
        'tripReserve.shopRemark': res.feature.shopRemark,
        'tripReserve.visaRemark': res.feature.visaRemark,
        'featureType': res.feature.featureType,
      }, this.getHeight)
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 获取滚动区域元素高度
   */
  getHeight: function () {
    let query = wx.createSelectorQuery().in(this);
    let heightArr = [];
    let s = 0;
    query.selectAll('.scroll_view_node').boundingClientRect((rect) => {
      rect.forEach((res) => {
        s += res.height;
        heightArr.push(s)
      })
      this.setData({
        heightArr: heightArr
      })
    })
    query.select('#scroll_view').boundingClientRect((res) => {
      this.setData({
        containerH: res.height
      })
    })
    query.exec()
  },

  /**
   * 跳转下单
   */
  goUrlOrder: function () {
    if (this.data.account === '') {
      wx.navigateTo({
        url: '../../login/login'
      })
    } else {
      wx.navigateTo({
        url: '../productOrder/productOrder?configId=' + this.data.proId
      })
    }
  },
  /**
   * 封面图切换
   */
  swiperChange: function(e) {
    this.setData({
      'header.imgCoverIndex': e.detail.current + 1
    })
  },

  /**
   * 团期切换
   */
  priceOn: function(e) {
    this.setData({
      'header.priceNum': e.currentTarget.dataset.num
    })
  },

  /**
   * 航班显示切换
   */
  flightOn: function(e) {
    this.setData({
      'header.flightShow': !this.data.header.flightShow
    })
  },

  /**
   * 更多团期
   */
  priceMore: function() {
    this.setData({
      'header.priceMore': !this.data.header.priceMore
    })
  },

  /**
   * 菜单切换
   */
  menuChange: function(e) {
    this.setData({
      menuIndex: parseInt(e.currentTarget.dataset.num),
      toView: e.currentTarget.dataset.view
    })
  },

  /**
   * 行程滚动区域滚动事件
   */
  scroll: function (e) {
    let scrollTop = e.detail.scrollTop;
    let scrollArr = this.data.heightArr;
    if (scrollTop >= scrollArr[scrollArr.length - 1] - this.data.containerH) {
      return
    } else {
      for (let i = 0; i < scrollArr.length; i++) {
        if (scrollTop >= 0 && scrollTop < scrollArr[0]) {
          this.setData({
            menuIndex: 0
          })
        } else if (scrollTop >= scrollArr[i - 1] && scrollTop < scrollArr[i]) {
          this.setData({
            menuIndex: i
          })
        }
      }
    }
  },

  /**
   * 行程介绍数据格式化
   */
  setupData: function(tripList) {
    let newTrip = [];
    tripList.forEach((x, j) => {
      let useDinnerTypeBy = ''
      let jin = [],
        jiu = [],
        jiu2 = [],
        jiao = [],
        dadian = [],
        tips = [],
        activy = [],
        can = {
          breakfirst: '敬请自理',
          lanuch: '敬请自理',
          dinner: '敬请自理'
        }
      x.dayArray.forEach((y, index) => {
        if (y.type == 7 && y.childItem.description != '' && y.childItem.title != '') {
          let obj = {
            title: y.childItem.title,
            content: y.childItem.description,
            img: y.childItem.imaArray && y.childItem.imaArray.length > 0 ? y.childItem.imaArray[0].url : '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null,
            url: ''
          }
          dadian.push(obj)
        } else if (y.type == 1 && y.childItem.subTraffic.length > 0) {
          let title = []
          y.childItem.subTraffic.forEach((z, i) => {
            title.push({
              'text': z.startCityName
            })
            if (z.arrivalType == 1) { // 飞机

              title.push({
                'img': '../../../images/product/ico_plane.png'
              })
            } else if (z.arrivalType == 2) { // 汽车

              title.push({
                'img': '../../../images/product/bus.png'
              })
            } else if (z.arrivalType == 3) { // 游轮

              title.push({
                'img': '../../../images/product/ship.png'
              })
            } else { // 轮船

              title.push({
                'img': '../../../images/product/train.png'
              })
            }
            if (i + 1 == y.childItem.subTraffic.length) {
              title.push({
                'text': z.arrivalCityName
              })
            }
          })
          let obj = {
            title: title,
            content: y.childItem.description,
            img: '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null,
            url: ''
          }
          jiao.push(obj)
        } else if (y.type == 2 && y.childItem.couponsName != '' && y.childItem.imaArray.length > 0) {
          let obj = {
            title: y.childItem.couponsName,
            content: y.childItem.description,
            img: y.childItem.imaArray[0].url,
            ticketName: y.childItem.couponsTicketName,
            playTimeHour: y.childItem.playTimeHour,
            playTimeMinutes: y.childItem.playTimeMinutes,
            url: y.childItem.url
          }
          jin.push(obj)
        } else if (y.type == 3 && y.childItem.hotelName != '' && y.childItem.imaArray.length > 0) {
          let obj = {
            title: y.childItem.hotelName,
            content: y.childItem.description,
            img: y.childItem.imaArray[0].url,
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null,
            url: y.childItem.url
          }
          jiu.push(obj)
        } else if (y.type == 4) {
          if (y.childItem.useDinnerType == "1") {
            can.breakfirst = y.childItem.dinnerName
          } else if (y.childItem.useDinnerType == "2") {
            can.lanuch = y.childItem.dinnerName
          } else if (y.childItem.useDinnerType == "3") {
            can.dinner = y.childItem.dinnerName
          }
        } else if (y.type == 5) {
          let obj = {
            title: '自由活动',
            content: y.childItem.description,
            img: '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null,
            url: ''
          }
          activy.push(obj)
        } else if (y.type == 6) {
          let obj = {
            title: y.childItem.title,
            content: y.childItem.description,
            img: '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null,
            url: ''
          }
          tips.push(obj)
        }
        if (y.type == 3) {
          jiu2.push(y.childItem.hotelName);
          useDinnerTypeBy = y.childItem.useDinnerType
        }
      })
      if (can.breakfirst == '敬请自理' && useDinnerTypeBy.indexOf('1') != -1) {
        can.breakfirst = '酒店内享用早餐'
      } else if (can.breakfirst == '') {
        can.breakfirst = '方便游玩敬请自理'
      }
      if (can.lanuch == '敬请自理' && useDinnerTypeBy.indexOf('2') != -1) {
        can.lanuch = '酒店自助'
      } else if (can.lanuch == '') {
        can.lanuch = '方便游玩敬请自理'
      }
      if (can.dinner == '敬请自理' && useDinnerTypeBy.indexOf('3') != -1) {
        can.dinner = '酒店自助'
      } else if (can.dinner == '') {
        can.dinner = '方便游玩敬请自理'
      }
      x.can = can
      let details = [];
      x.tips = tips
      x.jiu2 = jiu2
      if (jin.length > 0) {
        details = jin
      } else if (jiu.length > 0) {
        details = jiu
      } else if (dadian.length > 0) {
        details = dadian
      } else if (jiao.length > 0) {
        if (j == tripList.length - 1) {
          let obj = {
            title: '温暖的家',
            content: '感谢您参加本次行程，期待下次与您相遇',
            img: ''
          }
          details.push(obj)
        } else {
          details = jiao
        }
      } else if (activy.length > 0) {
        details = activy
      }
      x.title = dadian.length > 0 ? dadian[0].title : (jiao.length > 0 ? jiao[0].title : '集合出发')
      x.details = details
      if (x.details.length == 0) {
        if (j == 0) {
          let obj = {
            title: '集合出发',
            content: '向着远方的目标出发起飞',
            img: '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null
          }
          details.push(obj)
        } else if (j == this.tripList.length - 1) {
          let obj = {
            title: '温暖的家',
            content: '感谢您参加本次行程，期待下次与您相遇',
            img: '',
            ticketName: '',
            playTimeHour: null,
            playTimeMinutes: null
          }
          details.push(obj)
        }
      } else {
        if (x.title == '集合出发') {
          x.details.forEach(xc => {
            if (xc.title !== undefined)
              x.title = xc.title + '~'
          })
          if (x.title == '集合出发') {
            if (j > 0 && j < tripList.length - 1)
              x.title = '自由活动'
          } else {
            x.title = x.title.substring(0, x.title.length - 1)
          }
        }
      }
      x.islast = (j + 1) == tripList.length
      newTrip.push(x);
    })

    // for (let i = newTrip.length - 1; i >= 0; i--) {
    //   if (i == 0)
    //     newTrip[i].can.breakfirst = '敬请自理'
    //   else {
    //     newTrip[i].can.breakfirst = newTrip[i - 1].can.breakfirst

    //     if (newTrip[i].lineId != 5 && newTrip[i].can.breakfirst == '敬请自理' && i != newTrip.length-1)
    //       newTrip[i].can.breakfirst = '酒店内享用早餐'
    //   }
    // }
    return newTrip;
  },

  /**
   * 绑定公司信息
   */
  bindShareCompany: function (e) {
    this.data.shareInfo.companyName = e.detail.value
    wx.setStorage({
      key: 'shareInfo',
      data: this.data.shareInfo,
    })
  },

  // 打开分享设置弹出框
  OpenShareBox: function () {
    this.setData({
      isOpenShare: true
    })
  },

  //关闭分享设置
  closeShareBox: function () {
    this.setData({
      isOpenShare: false
    })
  },
  /**
   * 绑定联系人信息
   */
  bindSharePeople: function (e) {
    this.data.shareInfo.peopleName = e.detail.value
    wx.setStorage({
      key: 'shareInfo',
      data: this.data.shareInfo,
    })
  },

  /**
   * 绑定联系人信息
   */
  bindSharePhone: function (e) {
    this.data.shareInfo.phone = e.detail.value
    wx.setStorage({
      key: 'shareInfo',
      data: this.data.shareInfo,
    })
  },

  /**
   * 获取分享信息
   */
  setupShare: function(){
    let that = this
    wx.getStorage({
      key: 'shareInfo',
      success: function(res) {
        //todo
        that.setData({
          'shareInfo.companyName': res.data.companyName,
          'shareInfo.peopleName': res.data.peopleName,
          'shareInfo.phone': res.data.phone,
        })
      },
    })
  },

  // 输入公司名称
  bindCPNameInput: function (e) {
    let val = e.detail.value;
    this.setData({
      'shareInfo.companyName': val 
    })
  },

  // 输入公司姓名
  bindAccountInput: function (e) {
    let val = e.detail.value;
    this.setData({
      'shareInfo.peopleName': val
    })
  },

  // 输入公司电话
  bindPhoneInput: function (e) {
    let val = e.detail.value;
    this.setData({
      'shareInfo.phone': val
    })
  },
  /**
   * 设置分享信息
   */
  setShare: function(){
    if (this.data.shareInfo.companyName != '' && this.data.shareInfo.peopleName && this.data.shareInfo.phone) {
      let obj = this.data.shareInfo;
      wx.setStorage({
        key: 'shareInfo',
        data: obj,
      })
      this.setData({        
        isOpenShare: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: ''
    })
    const scene = decodeURIComponent(options.scene)
    if (scene !== 'undefined') {
      let obj = scene.split('&&')
      let jump = obj[0].split('=')
      let id = obj[1].split('=')
      let tcid = obj[2].split('=')
      this.setData({
        proId: id[1],
        tcid: tcid[1]
      })
      this.getDetail(id[1])
    } else {
      this.setData({
        isMember: app.state.admin.isMember,
        photo: app.state.admin.photo === null ? '' : app.state.admin.photo,
        address: app.state.admin.address,
        name: app.state.admin.name,
        account: app.state.admin.account,
        proId: options.id,
        tcid: options.tcid ? parseInt(options.tcid) : null
      })     
      this.getDetail(options.id)
    }
    this.setupShare()
    if(options.c && options.pe && options.ph){
      this.setData({
        'shareSource.c': options.c,
        'shareSource.pe': options.pe,
        'shareSource.ph': options.ph
      })
    }
    let that = this;
    wx.getStorage({
      key: 'admin',
      success: function (res) {
        that.setData({
          loginInfo: 'true'
        })
      },
    })
  },
  // 拨打电话
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.replyPhone,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {    
    let startDate = this.data.dataList.priceList[this.data.header.priceNum].startDate ? this.data.dataList.priceList[this.data.header.priceNum].startDate : ""
    startDate = startDate!=="" ? startDate.substring(5, startDate.length) : ''
    let title = this.data.header.title
    let path = '/pages/product/productDetail/productDetail?jump=1&&id=' + this.data.proId
    let shareObj = this.data.shareInfo;
    this.setData({
      'tcid': this.data.dataList.priceList[this.data.header.priceNum].tcid
    })
    let tcid = this.data.tcid ? '&tcid=' + this.data.tcid : '';
    if (shareObj.companyName) {
      title = shareObj.companyName + '(' + shareObj.phone + ')' + " " + startDate + " " + title
      path += '&c=' + shareObj.companyName + '&pe=' + shareObj.peopleName + '&ph=' + shareObj.phone + tcid
    } else if (app.state.admin.account !== '') {
      title = app.state.admin.customerName + '(' + app.state.admin.account + ')' + " " + startDate + " " + title 
      path += '&c=' + app.state.admin.customerName + '&pe=' + app.state.admin.contact + '&ph=' + app.state.admin.account + tcid
    }
    return {
      title: title,
      path
    }
  }
})