import HouseApi from '../../../apis/house'
import {
  fotmatDate
} from '../../../utils/date'
import loginFn from '../../../utils/login'
import MsgManager from '../../../pages/chat/msg-manager'
import {
  randomString
} from './../../../utils/tools'
import {
  saveViewHistory
} from '../../../utils/storage'
import {
  loginByUserInfo
} from '../../../utils/login'
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    house_id: String,
    agent_user: Object,
    isAgency: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    loginStatus: app.globalData.token ? true : false,
    userinfo: app.globalData.userinfo,
    isFocused: false,
    recommendList: [],
    user_code: '',
    markers: [],
    house: getApp().globalData.lastHouse,
    new_detailItems: [{
        label: '单价',
        value: '',
        name: 'unit_price'
      },
      {
        label: '挂牌',
        value: '',
        name: 'apply_time',
        format: fotmatDate
      },
      {
        label: '朝向',
        value: '',
        name: 'orientation'
      },
      {
        label: '楼层',
        value: '',
        name: 'floor_num'
      },
      {
        label: '楼型',
        value: '',
        name: 'building_type'
      },
      {
        label: '装修',
        value: '',
        name: 'decoration'
      },
      {
        label: '年代',
        value: '',
        name: 'building_age'
      },
      {
        label: '用途',
        value: '',
        name: 'house_usage'
      },
    ],

    detailItems: [{
        label: '建设年份',
        value: '2009',
        name: 'constructionYear',
        // format: fotmatDate
      },
      {
        label: '浴室个数',
        value: '1',
        name: 'showerroomAmount',
        // format: fotmatDate
      },
      {
        label: '卧室数量',
        value: '3',
        name: 'bedroomAmount'
      },
      {
        label: '单位价格',
        value: '3',
        name: 'unit_price'
      },
      {
        label: '物业编号',
        value: '12321321',
        name: 'propertyNumber'
      },
      {
        label: '建筑面积',
        value: '123',
        name: 'area'
      },
      {
        label: '土地面积',
        value: '123',
        name: 'floorSpace'
      },
    ]
  },
  pageLifetimes: {
    show() {
      this.setData({
        loginStatus: app.globalData.token ? true : false,
        userinfo: app.globalData.userinfo,
        app_type: app.globalData.type
      })
    }
  },
  ready() {


    this.setData({
      loginStatus: app.globalData.token ? true : false,
      userinfo: app.globalData.userinfo,
    })
    this.getHouseDetail(this.properties.house_id)
    this.fetchRecommendHouseList()
    this.msgManager = new MsgManager(this)

    if (!this.data.loginStatus) {
      // wx.login({
      //   success: (res) => {
      //     this.setData({
      //       user_code: res.code
      //     })
      //   }
      // })
    } else {

      this.getHouseFocusStatus()
    }

  },
  /**
   * 组件的方法列表
   */
  methods: {
    toMap() {
      const house = this.data.house
      wx.navigateTo({
        url: `/pages/map/map?longitude=${house.longitude}&latitude=${house.latitude}&housename=${house.district || ''} ${house.estate_name || ''}${this.properties.isAgency ? '' : `&agency_id=${this.properties.agent_user.agency_user_id}&agency_name=${this.properties.agent_user.name}&phone=${this.properties.agent_user.phone}`}`
      })
    },
    sendSchoolMsg() {
      if (!getApp().globalData.token) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return
      }
      Promise.all([this.sendTextMsg('您好，请问这个房子周边有哪些学校？')]).then(res => {
        wx.navigateTo({
          url: `/pages/chat/chat?toId=${this.properties.agent_user.agency_user_id}&toName=${this.properties.agent_user.name}`
        })
      })
    },
    getHouseDetail(house_id) {
      wx.showLoading({
        title: '加载数据中'
      })
      HouseApi.houseDetail(house_id).then(res => {
        let {
          detailItems
        } = this.data
        let house = res.data
        detailItems.forEach(item => {
          if (house[item.name]) {
            // 若有format函数，则执行处理成想要格式化的值
            if (item.format && typeof item.format === 'function') {
              house[item.name] = item.format(house[item.name])
            }
            item.value = house[item.name]
          } else {
            item.value = '暂无数据'
          }
        })
        house.tags = JSON.parse(house.tags || "[]")
        house.ancillaryFacility = JSON.parse(house.ancillaryFacility || "[]")
        // house.remarks = JSON.parse(house.remarks || "[]")[0].text
        house.remarks = JSON.parse(house.remarks || "[]")
        res.data.detail_images = JSON.parse(res.data.detail_images)
        res.data.detail_images = res.data.detail_images.map(item => `${item}?x-oss-process=image/resize,w_750,limit_0/quality,q_75`)
        let markers = [{
          longitude: house.longitude,
          latitude: house.latitude,
          housename: house.title,
          iconPath: "/image/4Dage/location-cycle.png",
          zIndex: -1,
          callout: {
            content: `${house.district || ''} ${house.estate_name || ''}`,
            display: 'ALWAYS',
            padding: 15,
            anchorY: 10
          }
        }]
        this.setData({
          house: res.data,
          detailItems: detailItems,
          markers
        })
        saveViewHistory(res.data)
        app.globalData.last_house = house
        wx.hideLoading()
      }).catch(err => {
        console.log(err, '获取详情出错')
        wx.hideLoading()
      })
    },
    getHouseFocusStatus() {
      const {
        loginStatus
      } = this.data
      if (!loginStatus) {
        return
      }
      return HouseApi.isHouseFocused({
        house_id: this.properties.house_id,
        user_id: this.data.userinfo.user_id
      }).then((res) => {
        this.setData({
          isFocused: res.data === -1 ? false : true
        })
        return res.data
      })
    },
    bindgetphonenumber(e) {
      loginFn(e, this.data.user_code, this.properties.isAgency ? true : false).then(res => {
        this.setData({
          loginStatus: app.globalData.token ? true : false,
          userinfo: app.globalData.userinfo,
        })
        this.getHouseFocusStatus().then(res => {
          if (!res) {
            this.changeFocusStatus()
          }
        })
      })
    },
    changeFocusStatus() {
      const is_valid = this.data.isFocused ? 0 : 1
      HouseApi.focusHouse({
        is_valid,
        house_id: this.properties.house_id
      }).then(res => {
        this.setData({
          isFocused: is_valid
        })
      })
    },
    cancleFocusStatus() {
      return HouseApi.cancleFocusHouse({
        house_id: this.properties.house_id
      }).then(() => {
        this.setData({
          isFocused: 0
        })
      })
    },
    fetchRecommendHouseList() {
      const fetchData = {
        city: app.globalData.city,
        saleState: 1,
        page_size: 8
      }
      HouseApi.houseList(fetchData).then(res => {
        this.setData({
          recommendList: res.data.list
        })
      })
    },
    toMoreIntro() {
      wx.navigateTo({
        url: `/pages/detail-intro/detail-intro?house_id=${this.properties.house_id}`
      })
    },
    addReadHistory() {
      HouseApi.addReadHistory({
        house_id: this.properties.house_id
      })
    },
    // 发送带看
    onlineWatch() {
      if (!this.data.loginStatus) {
        wx.navigateTo({
          url: '/pages/login/login'
        })
        return
      }
      if (this.properties.isAgency) {
        wx.navigateTo({
          url: `/pages/message-list/message-list?house_id=${this.properties.house_id}`
        })
        return
      }
      const room_id = randomString(18)
      this.toVrHouse(room_id, true)
    },
    // 发送房屋卡片
    sendVrMsg(room_id, is_vr_invite) {
      const {
        house
      } = this.data
      let content = {
        house_name: house.title,
        image_url: house.detail_images[0],
        house_type: house.house_type,
        house_area: house.area,
        orientation: house.orientation,
        price: `${house.price}`,
        vr_link: is_vr_invite ? `${house.vrLink}${encodeURIComponent(`&room_id=${room_id}`)}` : '',
        house_id: house.house_id
      }
      return this.sendMsg({
        content,
        msgType: 'vr'
      })
    },
    // 发送文字
    sendTextMsg(content) {
      return this.sendMsg({
        content,
        msgType: 'text'
      })
    },
    sendMsg({
      content,
      msgType
    }) {
      let defaultContent = {
        fromId: app.globalData.userinfo.user_id,
        fromName: app.globalData.userinfo.phone,
        toId: this.properties.agent_user.agency_user_id,
        toName: 'xu',
        type: 'TYPE_ONE',
        msgType,
        content: content
      }
      return getApp().getIMHandler().newFriendSendMsg({
        content: defaultContent
      })
    },
    toVrHouse(room_id, isAuto) {
      // console.log(app.globalData)
      if (typeof room_id !== 'string') room_id = ''

      this.postDataToOpen(room_id).then(res => {
        const vr_link = res.data.vrLink
        wx.navigateTo({
          url: `/pages/web/web?room_id=${res.data.roomId}&vr_link=${encodeURIComponent(vr_link)}&house_id=${this.properties.house_id}${isAuto ? `&is_auto=${isAuto}` : ''}`
        })
      })

    },
    postDataToOpen(room_id) {
      return HouseApi.postDataToOpen({
        house_id: this.properties.house_id,
        room_id,
        type: 'customer'
      })
    },
    toAgentDetail() {
      wx.navigateTo({
        url: `/pages/agent-detail/agent-detail?agency_id=${this.properties.agent_user.agency_user_id}`,
      })
    },
    bindgetuserinfo(e) {
      const {
        action
      } = e.currentTarget.dataset
      loginByUserInfo().then(res => {
        this.setData({
          loginStatus: app.globalData.token ? true : false,
          userinfo: app.globalData.userinfo,
        })
        this.getHouseFocusStatus()
        this[action] && this[action]()
      })
    }
  }
})