import env from '../config/env.js'

/**
 * 设备端专用请求工具
 * 特点:
 * 1. 不添加用户端的 deviceInfo 参数
 * 2. 不处理登录过期逻辑
 * 3. 保留 JSESSIONID 管理
 * 4. 简化 loading 逻辑(无延迟)
 */

// Loading 管理器 - 简化版
const loadingManager = {
  loadingCount: 0,
  isShowing: false,

  show(options = {}) {
    const config = {
      title: '加载中...',
      mask: true,
      ...options
    }

    // 如果已经有 loading 在显示，只增加计数
    if (this.loadingCount > 0) {
      this.loadingCount++
      return
    }

    // 设备端无需延迟,直接显示
    if (!this.isShowing) {
      try {
        uni.showLoading({
          title: config.title,
          mask: config.mask
        })
        this.isShowing = true
      } catch (error) {
        console.warn('showLoading failed:', error)
      }
    }

    this.loadingCount++
  },

  hide() {
    this.loadingCount = Math.max(0, this.loadingCount - 1)

    if (this.loadingCount === 0 && this.isShowing) {
      try {
        uni.hideLoading()
      } catch (error) {
        console.warn('hideLoading failed:', error)
      } finally {
        this.isShowing = false
      }
    }
  },

  forceHide() {
    this.loadingCount = 0
    if (this.isShowing) {
      try {
        uni.hideLoading()
      } catch (error) {
        console.warn('forceHide failed:', error)
      } finally {
        this.isShowing = false
      }
    }
  },

  safeShowToast(options) {
    if (this.isShowing) {
      this.forceHide()
      setTimeout(() => {
        uni.showToast(options)
      }, 100)
    } else {
      uni.showToast(options)
    }
  }
}

const deviceRequest = {
  async get(url, params = {}, options = {}) {
    return this.request(url, 'GET', params, options)
  },

  async post(url, data = {}, options = {}) {
    return this.request(url, 'POST', data, options)
  },

  async request(url, method, data, options = {}) {
    // 解析 loading 配置
    let loadingConfig
    if (options.loading === false) {
      loadingConfig = false
    } else {
      loadingConfig = {
        show: true,
        title: '加载中...',
        mask: true,
        ...(typeof options.loading === 'object' ? options.loading : {})
      }
    }

    // 解析请求配置
    const requestConfig = {
      timeout: 15000,
      ...options.request
    }

    const shouldShowLoading = loadingConfig !== false && loadingConfig.show !== false

    // 显示 loading
    if (shouldShowLoading) {
      loadingManager.show(loadingConfig)
    }

    // 🎯 参考 request.js (161-168行)，自动添加 devId 和 sbmc
    // 设备端从 userInfo 获取，而不是从 deviceInfo
    let finalUrl = url

    // 检查 URL 是否已包含 devId 参数（login 接口已手动添加）
    if (!url.includes('devId=')) {
      const userInfo = uni.getStorageSync('userInfo') || {}
      const devId = userInfo.devId || ''
      const sbmc = userInfo.sbmc || ''

      // 只有在有 devId 时才添加参数
      if (devId) {
        const separator = url.includes('?') ? '&' : '?'
        finalUrl = `${url}${separator}devId=${devId}&sbmc=${sbmc}`
      }
    }

    // 数据格式转换
    let requestData = data
    if (options.formData && data && typeof data === 'object') {
      requestData = Object.keys(data).map(key => {
        const value = data[key]
        if (Array.isArray(value)) {
          return value.map(item => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join('&')
        } else {
          return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        }
      }).join('&')
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: `${env.baseUrl}${finalUrl}`,
        method,
        data: requestData,
        timeout: requestConfig.timeout,
        header: (() => {
          const headers = {}

          if (options.formData) {
            headers['content-type'] = 'application/x-www-form-urlencoded'
          } else {
            headers['content-type'] = 'application/json'
          }

          // 携带 JSESSIONID
          const jsessionId = uni.getStorageSync('JSESSIONID')
          if (jsessionId) {
            headers['Cookie'] = `JSESSIONID=${jsessionId}`
          }

          return headers
        })(),
        success: (res) => {
          // 获取响应头
          const headers = res.header

          // 处理 Set-Cookie，保存 JSESSIONID
          const setCookie = headers['set-cookie'] || headers['Set-Cookie']
          if (setCookie) {
            const match = setCookie.match(/JSESSIONID=([^;]+)/)
            if (match && match[1]) {
              console.log('🔑 设备端获取到 JSESSIONID:', match[1])
              uni.setStorageSync('JSESSIONID', match[1])
            }
          }

          if (res.statusCode === 200) {
            // 检查服务器错误
            if (res && typeof res.data === 'string' && res.data.includes('页面执行时错误')) {
              reject({
                message: '服务器处理错误' + res.data,
              })
              loadingManager.safeShowToast({
                title: '服务器处理错误',
                icon: 'none'
              })
              return
            }

            // 设备端不处理登录过期,直接返回数据
            const responseData = {
              data: res.data,
            }
            resolve(responseData)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          loadingManager.safeShowToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(err)
        },
        complete: () => {
          if (shouldShowLoading) {
            loadingManager.hide()
          }
        }
      })
    })
  }
}

// 添加便捷方法
deviceRequest.loadingManager = loadingManager

// 静默请求
deviceRequest.silent = {
  get: (url, params = {}) => deviceRequest.get(url, params, { loading: false }),
  post: (url, data = {}) => deviceRequest.post(url, data, { loading: false }),
}

// 带自定义 loading 文字的请求
deviceRequest.withLoading = (title) => ({
  get: (url, params = {}) => deviceRequest.get(url, params, { loading: { title } }),
  post: (url, data = {}) => deviceRequest.post(url, data, { loading: { title } }),
})

export default deviceRequest
