//index.js
//获取应用实例
const app = getApp()

const page = require('../../utils/page.js');
import fetch from '../../utils/http'
const $api = require('../../config/api.js').$api;

Page({
  onShow() {
    wx.setNavigationBarTitle({
      title: '楼盘详情'
    })
  },
  onLoad: function (options) {
    const id = page.getCurrentPageOptions().id
    const _that = this

    fetch({
      url: $api.collection.getByUser.url.replace(':openid', app.globalData.UserInfo.openid),
      method: $api.collection.getByUser.method,
      data: {
        pageNum: 1,
        pageSize: 100
      }
    }).then((collects) => {
      _that.setData({
        Collects: collects.data.records
      })
      fetch({
        url: $api.building.detail.url.replace(':id', id),
        method: $api.building.detail.method,
      }).then((data) => {
        const dicts = app.globalData.Dict
        const apart = data.data.buildingApartment.map(x => {
          return {
            ...x,
            imgUrl: (x.buildingImgList[0] || {}).url,
            marketStatus: (dicts.filter(d => d.id == x.marketStatus)[0] || {}).name
          }
        })
        let propertyType = ''
        data.data.propertyType.split(',').map(x => {
          const f = dicts.filter(d => d.id == x)
          if (f.length > 0) {
            propertyType += (propertyType === '' ? '' : ',') + f[0].name
          }
        })
        _that.setData({
          EstateDetail: { 
            ...data.data, 
            openingDate: data.data.openingDate.split(' ')[0],
            propertyType: propertyType, 
            buildingApartment: apart, 
            IsCollect: (_that.data.Collects.filter(x => x.buildingId == data.data.buildingId).length>0? true:false)
            }
        })
      })
    })
  },
  data: {
    UserInfo: app.globalData.UserInfo,
    ScreenBottomHeight: app.globalData.ScreenBottomHeight,
    EstateDetail: {},
    Collects: []
  },
  MakeAnAppointment() { // 预约看房
    wx.navigateTo({
      url: '/pages/AppointmentTime/index?id=' + this.data.EstateDetail.buildingId + '&name=' + this.data.EstateDetail.buildingName
    })
  },
  MakeCollect() {
    const _that = this
    fetch({
      url: $api.collection.save.url.replace(':openid', app.globalData.UserInfo.openid) + '?buildingId=' + this.data.EstateDetail.buildingId,
      method: $api.collection.save.method,
    }).then((data) => {
      wx.showToast({
        title: '收藏成功!'
      })
      _that.setData({
        EstateDetail: { ..._that.data.EstateDetail, IsCollect:true}
      })
    })
  },
  OpenPhone() { // 电话咨询
    let _self = this
    wx.makePhoneCall({
      phoneNumber: _self.data.EstateDetail.tel
    })
  }
})