// 服务人员详情页
const api = require('../../utils/api')
const app = getApp()

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    provider: null,
    reviews: [],
    showBookingModal: false,
    showAllReviewsModal: false,
    // 预约表单数据
    selectedType: '',
    serviceTypes: [],
    bookingTime: '',
    bookingAddress: '',
    remark: '',
    loading: true
  },

  onLoad(options) {
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight

    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight
    })

    // 加载服务人员数据
    if (options.id) {
      this.loadProviderDetail(options.id)
    } else {
      // 使用模拟数据
      this.loadMockData()
    }
  },

  /**
   * 加载服务人员详情
   */
  async loadProviderDetail(id) {
    this.setData({ loading: true })

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${config.API_BASE_URL}/service/providers/${id}`,
          method: 'GET',
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        })
      })

      if (res.statusCode === 200 && res.data.success) {
        const provider = res.data.data
        const baseUrl = 'https://ai-c.maimanji.com'

        // 处理头像URL
        if (provider.avatar && provider.avatar.startsWith('/')) {
          provider.avatar = baseUrl + provider.avatar
        }

        // 处理服务类型
        let serviceTypes = provider.serviceTypes || []
        if (serviceTypes.length === 0) {
          // 默认服务类型
          serviceTypes = [
            { id: 'basic', name: '基础服务', price: provider.price, unit: provider.unit || '小时' }
          ]
        }

        // 模拟评价数据（暂时保留，因为后端未返回）
        const reviews = [
          {
            id: 1,
            userName: '138****6172',
            avatar: '',
            rating: 5,
            content: '非常专业，服务态度很好。工作认真负责，每次都能把家里打扫得干干净净。非常满意！',
            tags: ['专业', '认真', '细心'],
            date: '2024-01-15'
          }
        ]

        this.setData({
          provider,
          reviews,
          serviceTypes,
          selectedType: serviceTypes[0].id,
          loading: false
        })
      } else {
        wx.showToast({ title: '加载失败', icon: 'none' })
        setTimeout(() => wx.navigateBack(), 2000)
      }
    } catch (err) {
      console.error('加载服务人员详情失败', err)
      wx.showToast({ title: '网络错误', icon: 'none' })
      setTimeout(() => wx.navigateBack(), 2000)
    }
  },

  /**
   * 返回
   */
  onBack() {
    wx.navigateBack()
  },

  /**
   * 分享
   */
  onShare() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 咨询
   */
  onConsult() {
    // 检查登录
    if (app.checkNeedLogin && app.checkNeedLogin()) return

    wx.showToast({ title: '咨询功能开发中', icon: 'none' })
  },

  /**
   * 立即预约
   */
  onBook() {
    // 检查登录
    if (app.checkNeedLogin && app.checkNeedLogin()) return

    this.setData({ showBookingModal: true })
  },

  /**
   * 关闭预约弹窗
   */
  closeBookingModal() {
    this.setData({ showBookingModal: false })
  },

  /**
   * 选择服务类型
   */
  selectServiceType(e) {
    const id = e.currentTarget.dataset.id
    this.setData({ selectedType: id })
  },

  /**
   * 选择预约时间
   */
  onPickTime() {
    const now = new Date()
    const currentDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
    const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`

    wx.showModal({
      title: '选择时间',
      content: '请使用日期时间选择器',
      showCancel: false,
      success: () => {
        // 简化版：直接设置当前时间
        this.setData({
          bookingTime: `${currentDate} ${currentTime}`
        })
      }
    })
  },

  /**
   * 选择服务地址
   */
  onPickAddress() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          bookingAddress: res.address + res.name
        })
      },
      fail: (err) => {
        if (err.errMsg.includes('auth deny')) {
          wx.showModal({
            title: '需要位置权限',
            content: '请在设置中开启位置权限',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        }
      }
    })
  },

  /**
   * 备注输入
   */
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value })
  },

  /**
   * 计算价格
   */
  calculatePrice() {
    const { serviceTypes, selectedType } = this.data
    const type = serviceTypes.find(t => t.id === selectedType)
    return type ? type.price : 0
  },

  /**
   * 确认预约
   */
  async confirmBooking() {
    const { selectedType, bookingTime, bookingAddress, remark, provider } = this.data

    // 验证表单
    if (!bookingTime) {
      wx.showToast({ title: '请选择预约时间', icon: 'none' })
      return
    }

    if (!bookingAddress) {
      wx.showToast({ title: '请选择服务地址', icon: 'none' })
      return
    }

    wx.showLoading({ title: '提交中...' })

    try {
      // TODO: 调用实际API
      // const res = await api.service.createBooking({
      //   providerId: provider.id,
      //   serviceType: selectedType,
      //   bookingTime,
      //   address: bookingAddress,
      //   remark
      // })

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      wx.hideLoading()
      wx.showToast({ title: '预约成功', icon: 'success' })

      this.setData({ showBookingModal: false })

      // 跳转到订单详情
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/order-detail/order-detail?id=mock123'
        })
      }, 1500)
    } catch (err) {
      wx.hideLoading()
      console.error('预约失败', err)
      wx.showToast({ title: '预约失败', icon: 'none' })
    }
  },

  /**
   * 查看全部评价
   */
  onViewAllReviews() {
    this.setData({ showAllReviewsModal: true })
  },

  /**
   * 关闭全部评价弹窗
   */
  closeAllReviewsModal() {
    this.setData({ showAllReviewsModal: false })
  },

  /**
   * 分享给好友
   */
  onShareAppMessage() {
    const { provider } = this.data
    const referralCode = wx.getStorageSync('referralCode') || ''
    const referralCodeParam = referralCode ? `&referralCode=${referralCode}` : ''
    return {
      title: `推荐服务人员：${provider.name}`,
      path: `/pages/service-provider-detail/service-provider-detail?id=${provider.id}${referralCodeParam}`,
      imageUrl: provider.avatar
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    const { provider } = this.data
    const referralCode = wx.getStorageSync('referralCode') || ''
    const query = `id=${provider.id}${referralCode ? `&referralCode=${referralCode}` : ''}`
    return {
      title: `推荐服务人员：${provider.name}`,
      query: query,
      imageUrl: provider.avatar
    }
  }
})
