|  | // c:\Users\Holy-Knight-IX\Desktop\Working Space\4.TikTok-MiniPro\ttc\package2\pages\appointment\appointment.js
let config = require("../../../config/config.js");
let util = require("../../../utils/util");
let Http = require("../../../utils/HttpBasics");
let app = getApp();
const imgurl = require("../../../utils/imgurl");
Page({
  data: {
    appointmentText: "确认预约",
    id: "",
    orderId: "",
    merOrderId: "",
    startTime: '',
    endTime: "",
    mallTenantId: "",
    pickedAddress: "请选择地址",
    pickedAddressDetail: "",
    pickedDate: "请选择日期",
    pickedStartTime: "请选择",
    pickedEndTime: "请选择",
    reservationMerchantName: "",
    describeStr: "",
    mallList: [],
    merchantId: "",
    currentIndex: "",
    status: "",
    isShowBtns: false,
    latitude: "",
    longitude: ""
  },
  onLoad(options) {
    console.log(options, 'options')
    const mallTenantId = tt.getStorageSync('mallTenantId');
    if (mallTenantId) {
      this.setData({
        mallTenantId
      })
    }
    const date = (new Date()).getTime()
    const nowDate = util.timestampToTime(date, 'YYYY-MM-DD')
    const startTime = util.timestampToTime(options.startTime * 1, 'YYYY-MM-DD')
    console.log(nowDate, startTime, 'time');
    const finalStartTime = options.startTime * 1 > date * 1 ? startTime : nowDate
    console.log(finalStartTime, 'finalStartTime');
    // const mallList = [{
    //   merchantName: "1家帮汇家政保洁(河池市庆远镇)",
    //   latitude: 50.277748,
    //   longitude: 119.996078,
    //   id: 1
    // }, {
    //   merchantName: "2家帮汇家政保洁(河池市庆远镇)",
    //   latitude: 35.277748,
    //   longitude: 119.996078,
    //   id: 2
    // }, {
    //   merchantName: "3家帮汇家政保洁(河池市庆远镇)",
    //   id: 3
    // }, {
    //   merchantName: "4家帮汇家政保洁(河池市庆远镇)",
    //   latitude: 45.277748,
    //   longitude: 119.996078,
    //   id: 4
    // }]
    this.setData({
      id: options.id || '',
      orderId: options.orderId || '',
      merOrderId: options.merOrderId || '',
      startTime: finalStartTime,
      endTime: options.endTime || '',
    })
    this.getCouponMerchant(options.orderId)
    if (this.data.id) {
      this.getDetail(this.data.id)
    } else {
      this.setData({
        isShowBtns: true
      })
    }
  },
  setMerchant(e) {
    console.log(e.detail.value, 'e');
    const index = e.detail.value
    this.setData({
      currentIndex: index,
      merchantId: this.data.mallList[index].id
    })
    console.log(this.data.currentIndex, this.data.merchantId);
  },
  /**
   * 获得经纬度
   */
  getLocation() {
    console.log('getLocation');
    let that = this;
    tt.getLocation({
      type: "wgs84",
      // isHighAccuracy: true,
      success: function (res) {
        console.log(res, 'getLocation')
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
        const latitudeNow = res.latitude
        const longitudeNow = res.longitude
        const mallLocationArr = []
        const mallList = that.data.mallList
        mallList.forEach((item, index) => {
          const obj = {
            latitude: item.latitude || false,
            longitude: item.longitude || false,
            id: item.id,
            index: index
          }
          mallLocationArr.push(obj)
        })
        console.log(mallLocationArr, 'mallLocationArr');
        const tempArr = mallList
        const bloobArr = []
        mallLocationArr.forEach((item, index) => {
          const distanceData = that.getDistances(latitudeNow, longitudeNow, item.latitude, item.longitude)
          tempArr[index].distance_str = distanceData.distance_str
          tempArr[index].distanceName = tempArr[index].merchantName + ' ' + distanceData.distance_str
          tempArr[index].distance = distanceData.distance
          bloobArr.push(tempArr[index])
        })
        const finalSortMallList = that.bloob(bloobArr)
        console.log(finalSortMallList, 'finalSortMallList');
        that.setData({
          mallList: finalSortMallList
        })
      },
      // 拒绝提供定位权限
      fail: error => {
        console.log(error, 'error');
        const mallList = that.data.mallList
        mallList.forEach(item => {
          item.distanceName = item.merchantName
        })
        that.setData({
          mallList
        })
      },
      complete: finish => {
      }
    })
  },
  getCouponMerchant() { //获取适用门店
    const that = this
    Http.get({
      url: config.api.orderDetail,
      data: {
        orderId: that.data.merOrderId,
        mallTenantId: that.data.mallTenantId || ''
      }
    }).then(res => {
      const couponChannelId = res.data.orders[0].couponChannelId
      Http.get({
        url: config.api.couponMerchant,
        data: {
          couponChannelId,
          mallTenantId: that.data.mallTenantId || ''
        }
      }).then(res => {
        const keys = Object.keys(res.data)
        const mallList = []
        let i = 0
        keys.forEach(item => {
          const arr = item.split('|')
          const obj = {
            tenantId: arr[0],
            mallName: arr[1],
            merchantVoList: res.data[item],
            expand: false
          }
          if (i == 0) {
            obj.expand = true
          }
          mallList.push(obj)
          i++
        })
        that.setData({
          mallList: mallList[0].merchantVoList
        })
        console.log(that.data.mallList, 'mallList');
        that.getLocation()
      })
    }).catch(err => {
    })
  },
  chooseAddress() {
    if (!this.data.isShowBtns) return
    let that = this;
    tt.chooseLocation({
      success: function (res) {
        that.setData({
          pickedAddress: res.address,
        })
      },
      fail: function (error) {
        console.log(error)
      },
      complete: function (data) {}
    })
  },
  chooseAddressDetail() {
    this.setData({
      pickedAddressDetailFlag: false
    })
  },
  chooseDate(e) {
    console.log(e.detail.value, 'e');
    this.setData({
      pickedDate: e.detail.value
    })
  },
  chooseStartTime(e) {
    console.log(e.detail.value, 'e');
    this.setData({
      pickedStartTime: e.detail.value
    })
  },
  chooseEndTime(e) {
    console.log(e.detail.value, 'e');
    this.setData({
      pickedEndTime: e.detail.value
    })
  },
  inputAddressDetail(e) {
    this.setData({
      pickedAddressDetail: e.detail.value
    })
  },
  describing(e) {
    this.setData({
      describeStr: e.detail.value
    })
  },
  confirm() {
    const tempData = this.data
    if (tempData.pickedAddress == '请选择地址') {
      tt.showToast({
        title: '请选择地址!',
        icon: 'fail'
      });
      return
    }
    if (tempData.pickedDate == '请选择日期') {
      tt.showToast({
        title: '请请选择日期!',
        icon: 'fail'
      });
      return
    }
    if (tempData.pickedStartTime == '请选择') {
      tt.showToast({
        title: '请起始时间!',
        icon: 'fail'
      });
      return
    }
    if (tempData.pickedEndTime == '请选择') {
      tt.showToast({
        title: '请结束时间!',
        icon: 'fail'
      });
      return
    }
    const data = {
      couponOrderId: tempData.orderId,
      userAddress: tempData.pickedAddress,
      detailedAddress: tempData.pickedAddressDetail,
      startDate: tempData.pickedDate + " " + tempData.pickedStartTime + ":00",
      endDate: tempData.pickedDate + " " + tempData.pickedEndTime + ":00",
      describeStr: tempData.describeStr,
      mallTenantId: tempData.mallTenantId || '',
      reservationMerchantId: tempData.merchantId
    }
    if (this.data.id) {
      data.id = this.data.id
    }
    if (this.data.status == 1) {
      data.status = 0
    }
    console.log(data, 'data');
    this.saveOrderReservation(data)
  },
  cancel() {
    tt.showModal({
      title: "取消预约",
      content: "确定要取消预约吗?",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          this.cancelReservation(this.data.id)
        }
        if (res.cancel) {
          return
        }
      },
      fail: (res) => {
      },
    });
  },
  cancelReservation(id) {
    const that = this
    Http.post({
      url: config.api.cancelReservation,
      data: {
        id,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      console.log(res, 'cancelReservation');
      tt.showToast({
        title: '取消成功!',
        icon: 'success',
        duration: 2000,
        success: (res) => {
          setTimeout(() => {
            tt.navigateBack();
          }, 1500);
        },
        fail: (res) => {
        },
      });
    }).catch(err => {
      console.log(err, 'cancelReservation');
      tt.showToast({
        title: err.message,
        icon: 'none'
      });
    })
  },
  saveOrderReservation(data) {
    Http.post({
      url: config.api.saveOrderReservation,
      data
    }).then(res => {
      console.log(res, 'saveOrderReservation');
      tt.showToast({
        title: '预约成功!',
        icon: 'success',
        duration: 2000,
        success: (res) => {
          setTimeout(() => {
            tt.navigateBack();
          }, 1500);
        },
        fail: (res) => {
        },
      });
    }).catch(err => {
      console.log(err, 'saveOrderReservation');
      tt.showToast({
        title: err.message,
        icon: 'none'
      });
    })
  },
  getDetail(id) {
    const that = this
    Http.get({
      url: config.api.getOrderReservationDetail,
      data: {
        id,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      console.log(res, 'getOrderReservationDetail');
      const status = res.data.status
      that.setData({
        pickedAddress: res.data.userAddress || '请选择地址',
        pickedAddressDetail: res.data.detailedAddress,
        pickedDate: util.timestampToTime(res.data.startDate, 'YYYY-MM-DD'),
        pickedStartTime: util.timestampToTime(res.data.startDate, 'hh:mm'),
        pickedEndTime: util.timestampToTime(res.data.endDate, 'hh:mm'),
        describeStr: res.data.describeStr,
        status,
        appointmentText: res.data.status == 1 ? "重新预约" : "修改预约",
        merchantId: res.data.reservationMerchantId,
        reservationMerchantName: res.data.reservationMerchantName
      })
      if (status == 0 || status == 1 || status == 2 || status == 3) {
        that.setData({
          isShowBtns: true
        })
      }
    }).catch(err => {
      console.log(err, 'getOrderReservationDetail');
    })
  },
  /**
   * @description:根据经纬度计算距离
   * @param {*} locationInfo (lat1, lng1, lat2, lng2)
   * @return: distanceObj: { distance , distance_str }
   */
  getDistances(lat1, lng1, lat2, lng2) {
    if (lat2 || lng2) {
      function rad(num) {
        return num * Math.PI / 180.0;
      }
      var radLat1 = rad(lat1);
      var radLat2 = rad(lat2);
      var a = radLat1 - radLat2;
      var b = rad(lng1) - rad(lng2);
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10000;
      var distance = s;
      var distance_str = "";
      if (parseInt(distance) >= 1) {
        distance_str = distance.toFixed(2) + "km";
      } else if (!arseInt(distance)) {
        return false
      } else {
        distance_str = (distance * 1000).toFixed(2) + "m";
      }
      let objData = {
        distance: distance,
        distance_str: distance_str
      }
      return objData
    } else {
      let objData = {
        distance: Infinity,
        distance_str: ''
      }
      return objData
    }
  },
  bloob(arr) {
    const tempArr = arr
    for (let i = 0; i < tempArr.length - 1; i++) {
      for (let j = 0; j < tempArr.length - 1 - i; j++) {
        if (tempArr[j].distance > tempArr[j + 1].distance) {
          let temp = tempArr[j];
          tempArr[j] = tempArr[j + 1];
          tempArr[j + 1] = temp;
        }
      }
    }
    return tempArr
  },
  onShow() {
  }
})
 |