// pages/sjcf/sjcf.js
import request from '../../utils/request.js'
const app = getApp()
const MEIYE_TIAOSHU = 10

Page({
  data: {
    zongshu: 0,
    daichuli: 0,
    yichuli: 0,
    shenfen: 0,
    chufaList: [],
    dangqianye: 1,
    haiyougengduo: true,
    jiazhaozhong: false,
    jiazhaigengduo: false,
    scrollHeight: 0,
    showXiangqing: false,
    xuanzhongChufa: {},
    ossImageUrl: '',
    fangdouTimer: null
  },

  onLoad(options) {
    this.registerNotificationComponent()
    this.initOSSUrl()
    this.jisuanGaodu()
    this.chushihuaShuju()
  },

  onShow() {
    this.registerNotificationComponent()
  },

  onUnload() {
    if (this.data.fangdouTimer) clearTimeout(this.data.fangdouTimer)
  },

  onReachBottom() {
    this.shanglaShuaxin()
  },

  registerNotificationComponent() {
    const notificationComp = this.selectComponent('#global-notification')
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      }
    }
  },

  initOSSUrl() {
    const ossImageUrl = app.globalData.ossImageUrl || ''
    this.setData({ ossImageUrl })
  },

  jisuanGaodu() {
    const systemInfo = wx.getSystemInfoSync()
    const windowHeight = systemInfo.windowHeight
    const height = windowHeight - 200 - 100 - 40
    this.setData({
      scrollHeight: height > 0 ? height : 400
    })
  },

  chushihuaShuju() {
    this.setData({
      dangqianye: 1,
      chufaList: [],
      haiyougengduo: true
    })
    this.jiazhuoquTongji()
    this.jiazhuoquChufaList()
  },

  async jiazhuoquTongji() {
    try {
      // 🔴【修改】商家端接口地址
      const res = await request({
        url: '/yonghu/sjcfjlhq',
        method: 'POST',
        data: { qingqiu_tongji: true }
      })
      if (res.statusCode === 200 && res.data.code === 0) {
        const data = res.data.data
        this.setData({
          zongshu: data.zongshu || 0,
          daichuli: data.daichuli || 0,
          yichuli: data.yichuli || 0
        })
      }
    } catch (error) {}
  },

  async jiazhuoquChufaList(isLoadMore = false) {
    if (this.data.jiazhaozhong || this.data.jiazhaigengduo) return
    if (isLoadMore) {
      if (!this.data.haiyougengduo) return
      this.setData({ jiazhaigengduo: true })
    } else {
      this.setData({ jiazhaozhong: true })
    }
    
    try {
      const params = {
        page: this.data.dangqianye,
        page_size: MEIYE_TIAOSHU
      }
      if (this.data.shenfen === 0) {
        params.zhuangtai = 0
      } else {
        params.zhuangtai = 1
      }
      
      // 🔴【修改】商家端接口地址
      const res = await request({
        url: '/yonghu/sjcfjlhq',
        method: 'POST',
        data: params
      })
      
      if (res.statusCode === 200 && res.data.code === 0) {
        const data = res.data.data
        
        if (data.list && Array.isArray(data.list)) {
          const processedList = data.list.map(item => {
            let displayTime = '--'
            if (item.create_time) {
              if (typeof item.create_time === 'number') {
                displayTime = String(item.create_time)
              } else if (typeof item.create_time === 'string') {
                displayTime = item.create_time
              } else {
                displayTime = String(item.create_time)
              }
            }
            
            let displayStatus = '未知状态'
            let statusClass = 'zhuangtai-weizhi'
            const statusNum = Number(item.sqzhuangtai)
            
            if (!isNaN(statusNum)) {
              if (statusNum === 0) {
                displayStatus = '待处罚'
                statusClass = 'zhuangtai-daichuli'
              } else if (statusNum === 1) {
                displayStatus = '已处罚'
                statusClass = 'zhuangtai-yichufa'
              } else if (statusNum === 2) {
                displayStatus = '已驳回'
                statusClass = 'zhuangtai-yibohui'
              } else if (statusNum === 3) {
                displayStatus = '申诉中'
                statusClass = 'zhuangtai-shensuzhong'
              }
            }
            
            const fullZhengjuTupian = (item.zhengju_tupian || []).map(url => this.getFullImageUrl(url))
            const fullShensuTupian = (item.shensu_tupian || []).map(url => this.getFullImageUrl(url))
            
            return {
              ...item,
              display_time: displayTime,
              display_status: displayStatus,
              status_class: statusClass,
              zhengju_tupian: item.zhengju_tupian || [],
              shensu_tupian: item.shensu_tupian || [],
              full_zhengju_tupian: fullZhengjuTupian,
              full_shensu_tupian: fullShensuTupian
            }
          })
          
          let newList
          if (isLoadMore) {
            newList = [...this.data.chufaList, ...processedList]
          } else {
            newList = processedList
          }
          
          const hasMore = data.has_more === true
          this.setData({
            chufaList: newList,
            haiyougengduo: hasMore,
            dangqianye: this.data.dangqianye + 1
          })
        } else {
          this.setData({ haiyougengduo: false })
        }
      } else {
        throw new Error(res.data?.msg || '加载处罚记录失败')
      }
    } catch (error) {
      this.setData({ haiyougengduo: false })
    } finally {
      if (isLoadMore) {
        this.setData({ jiazhaigengduo: false })
      } else {
        this.setData({ jiazhaozhong: false })
      }
    }
  },

  qiehuanShenfen(e) {
    const type = parseInt(e.currentTarget.dataset.type)
    if (this.data.shenfen === type) return
    this.setData({
      shenfen: type,
      dangqianye: 1,
      chufaList: [],
      haiyougengduo: true
    })
    this.jiazhuoquChufaList()
  },

  shanglaShuaxin() {
    if (this.data.fangdouTimer) clearTimeout(this.data.fangdouTimer)
    const timer = setTimeout(() => {
      if (this.data.jiazhaozhong || this.data.jiazhaigengduo) return
      if (!this.data.haiyougengduo) return
      this.jiazhuoquChufaList(true)
    }, 300)
    this.setData({ fangdouTimer: timer })
  },

  chakanXiangqing(e) {
    const item = e.currentTarget.dataset.item
    this.setData({
      xuanzhongChufa: item,
      showXiangqing: true
    })
  },

  guanbiXiangqing() {
    this.setData({
      showXiangqing: false,
      xuanzhongChufa: {}
    })
  },

  lianxiKefu() {
    const kefuLink = app.globalData.kefuConfig?.link || '';
    const corpId = app.globalData.kefuConfig?.enterpriseId || '';

    if (!kefuLink || !corpId) {
        wx.showToast({
            title: '客服配置未加载',
            icon: 'none'
        });
        return;
    }

    wx.openCustomerServiceChat({
        extInfo: { url: kefuLink },
        corpId: corpId,
        success: (res) => {
            console.log('跳转客服成功', res);
        },
        fail: (err) => {
            console.error('跳转客服失败', err);
            wx.showToast({
                title: '暂时无法连接客服',
                icon: 'none'
            });
        }
    });
  },

  getFullImageUrl(relativeUrl) {
    if (!relativeUrl) return ''
    if (relativeUrl.startsWith('http')) {
      return relativeUrl
    }
    
    const ossUrl = this.data.ossImageUrl
    if (!ossUrl) {
      return relativeUrl
    }
    
    let fullUrl
    if (ossUrl.endsWith('/') && relativeUrl.startsWith('/')) {
      fullUrl = ossUrl + relativeUrl.substring(1)
    } else if (!ossUrl.endsWith('/') && !relativeUrl.startsWith('/')) {
      fullUrl = ossUrl + '/' + relativeUrl
    } else {
      fullUrl = ossUrl + relativeUrl
    }
    
    return fullUrl
  },

  yulanTupian(e) {
    const currentUrl = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls || []
    if (!currentUrl) return
    
    const fullCurrentUrl = currentUrl.startsWith('http') ? currentUrl : this.getFullImageUrl(currentUrl)
    const fullUrls = urls.map(url => url.startsWith('http') ? url : this.getFullImageUrl(url))
    
    wx.previewImage({
      current: fullCurrentUrl,
      urls: fullUrls.length > 0 ? fullUrls : [fullCurrentUrl]
    })
  },

  fuzhiWenben(e) {
    const text = e.currentTarget.dataset.text
    if (!text) return
    
    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({ title: '复制成功', icon: 'success' })
      },
      fail: () => {
        wx.showToast({ title: '复制失败', icon: 'none' })
      }
    })
  },

  imageLoadError(e) {
    // 图片加载失败处理（可以添加默认图片）
    const index = e.currentTarget.dataset.index
    const type = e.currentTarget.dataset.type
    
    if (type === 'zhengju') {
      const key = `xuanzhongChufa.full_zhengju_tupian[${index}]`
      this.setData({
        [key]: '/images/image-error.png'
      })
    } else if (type === 'shensu') {
      const key = `xuanzhongChufa.full_shensu_tupian[${index}]`
      this.setData({
        [key]: '/images/image-error.png'
      })
    }
  }
})