const app = getApp()
import request from '../../utils/request.js'
import connectionManager from '../../utils/xiaoxilj.js'

Page({
  data: {
    isLoading: true,
    jibenShuju: {
      dingdanId: '',
      tupian: '',
      jieshao: '',
      chuangjianshijian: '',
      jine: '0.00',
      nicheng: '',
      beizhu: '',
      zhuangtai: 0,
      updateTime: ''
    },
    xiangxiShuju: {
      dashou: '',
      dashouNicheng: '',
      dashouTouxiang: '',
      dashoujiaofu: [],
      dashouliuyan: '',
      jiedanTime: '',
      tijiaoTime: '',
      laobanPingjia: '',
      shangxianSudu: null,
      fuwuTaidu: null,
      fancheCishu: null
    },
    zhuangtaiWenziMap: {
      1: '已下单', 2: '进行中', 3: '已完成', 4: '退款中',
      5: '已退款', 6: '退款失败', 7: '指定中', 8: '结算中'
    },
    jiesuan: {
      fancheCishu: '',
      speedValue: 0,
      attitudeValue: 0,
      liuyan: ''
    },
    // 🔥 实时解释文字（必须在 data 中声明，才能用于 wxml 绑定）
    speedExplain: '',
    attitudeExplain: '',
    speedOptions: [
      { value: 5, label: '极速', explain: '接单后秒上线，2分钟以内' },
      { value: 4, label: '快', explain: '接单后5分钟以内上线' },
      { value: 3, label: '一般', explain: '接单后10分钟以内上线' },
      { value: 2, label: '慢', explain: '接单后15分钟以内上线' },
      { value: 1, label: '极慢', explain: '接单后15分钟以后上线' }
    ],
    attitudeOptions: [
      { value: 5, label: '极好', explain: '主动聊天哄开心，情绪价值拉满，处处护着老板' },
      { value: 4, label: '好', explain: '主动互动，保护老板，说话语气温和' },
      { value: 3, label: '一般', explain: '正常保护与聊天，以任务为主，情绪价值一般' },
      { value: 2, label: '较差', explain: '交互少，很少说话，纯应付订单，偶尔埋怨' },
      { value: 1, label: '极差', explain: '全程无交流或骂老板，体验极差，很愤怒' }
    ],
    showSpeedModal: false,
    showAttitudeModal: false,
    showConfirm: false,
    countdown: 3,
    countdownTimer: null,
    showMyEvaluation: false
  },

  onLoad(options) {
    wx.setNavigationBarTitle({ title: '订单详情' })
    this.parseParams(options)
  },

  parseParams(options) {
    try {
      const dingdanDataStr = options.dingdanData || ''
      if (!dingdanDataStr) {
        wx.showToast({ title: '参数错误', icon: 'none' })
        setTimeout(() => wx.navigateBack(), 1500)
        return
      }
      const data = JSON.parse(decodeURIComponent(dingdanDataStr))
      const ossImageUrl = app.globalData.ossImageUrl || ''
      let tupianUrl = data.tupian || ''
      if (tupianUrl && !tupianUrl.startsWith('http')) {
        tupianUrl = ossImageUrl + tupianUrl
      }
      if (!tupianUrl) {
        tupianUrl = ossImageUrl + (app.globalData.morentouxiang || '/images/default-avatar.png')
      }
      const jine = parseFloat(data.jine || 0).toFixed(2)

      this.setData({
        'jibenShuju.dingdanId': data.dingdanId || '',
        'jibenShuju.tupian': tupianUrl,
        'jibenShuju.jieshao': data.jieshao || '',
        'jibenShuju.chuangjianshijian': data.chuangjianshijian || '',
        'jibenShuju.jine': jine,
        'jibenShuju.nicheng': data.nicheng || '',
        'jibenShuju.beizhu': data.beizhu || '',
        'jibenShuju.zhuangtai': data.zhuangtai || 0,
        isLoading: false
      })
      this.loadDetail(data.dingdanId)
    } catch (e) {
      console.error('参数解析失败', e)
      wx.showToast({ title: '数据解析错误', icon: 'none' })
    }
  },

  async loadDetail(dingdanId) {
    try {
      const res = await request({
        url: '/dingdan/dingdanxiangqing2',
        method: 'POST',
        data: { dingdanId }
      })
      if (res && res.data.code === 0 && res.data.data) {
        const d = res.data.data
        const oss = app.globalData.ossImageUrl || ''
        let dashouTouxiang = d.dashou_touxiang || ''
        if (dashouTouxiang && !dashouTouxiang.startsWith('http')) {
          dashouTouxiang = oss + dashouTouxiang
        }
        if (!dashouTouxiang) {
          dashouTouxiang = oss + (app.globalData.morentouxiang || '/images/default-avatar.png')
        }
        const jiaofuList = (d.dashoujiaofu || []).map(url => {
          if (url && !url.startsWith('http')) return oss + url
          return url
        })
        const shangxian = d.shangxian_sudu
        const taidu = d.fuwu_taidu
        const fanche = d.fanche_cishu
        const showEval = (shangxian !== null && shangxian !== undefined) ||
                         (taidu !== null && taidu !== undefined) ||
                         (fanche !== null && fanche !== undefined)

        this.setData({
          'jibenShuju.zhuangtai': d.zhuangtai || 0,
          'jibenShuju.updateTime': d.update_time || '',
          'xiangxiShuju.dashou': d.dashou || '',
          'xiangxiShuju.dashouNicheng': d.dashou_nicheng || '',
          'xiangxiShuju.dashouTouxiang': dashouTouxiang,
          'xiangxiShuju.dashoujiaofu': jiaofuList,
          'xiangxiShuju.dashouliuyan': d.dashouliuyan || '',
          'xiangxiShuju.jiedanTime': d.jiedan_time || '',
          'xiangxiShuju.tijiaoTime': d.tijiao_time || '',
          'xiangxiShuju.laobanPingjia': d.laoban_pingjia || '',
          'xiangxiShuju.shangxianSudu': shangxian,
          'xiangxiShuju.fuwuTaidu': taidu,
          'xiangxiShuju.fancheCishu': fanche,
          showMyEvaluation: showEval && [3,4,5,6].includes(d.zhuangtai)
        })
        this.computeEvaluationText()
      } else {
        wx.showToast({ title: '获取详情失败', icon: 'none' })
      }
    } catch (e) {
      console.error('加载详情失败', e)
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  // 计算历史评价的文字
  computeEvaluationText() {
    const { speedOptions, attitudeOptions, xiangxiShuju } = this.data
    let speedText = '未评价'
    let attitudeText = '未评价'
    if (xiangxiShuju.shangxianSudu != null) {
      const sItem = speedOptions.find(v => v.value == xiangxiShuju.shangxianSudu)
      speedText = sItem ? sItem.label + ' (' + sItem.explain + ')' : ''
    }
    if (xiangxiShuju.fuwuTaidu != null) {
      const aItem = attitudeOptions.find(v => v.value == xiangxiShuju.fuwuTaidu)
      attitudeText = aItem ? aItem.label + ' (' + aItem.explain + ')' : ''
    }
    this.setData({ speedText, attitudeText })
  },

  onGoodsImgError() {
    const fallback = app.globalData.ossImageUrl + (app.globalData.morentouxiang || '/images/default-avatar.png')
    this.setData({ 'jibenShuju.tupian': fallback })
  },

  copyText(e) {
    const text = e.currentTarget.dataset.text
    if (text) {
      wx.setClipboardData({ data: text, success: () => wx.showToast({ title: '已复制', icon: 'none' }) })
    }
  },

  previewImages(e) {
    const current = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls || [current]
    wx.previewImage({ current, urls })
  },

  // 联系打手（防止角色被篡改）
  contactDashou() {
    const uid = wx.getStorageSync('uid')
    if (!uid) {
      wx.showToast({ title: '用户信息缺失', icon: 'none' })
      return
    }
    const dingdanId = this.data.jibenShuju.dingdanId

    // 备份全局角色
    const savedRole = app.globalData.currentRole
    const savedXshenfen = app.globalData.xshenfen

    connectionManager.connectToGroupChat({
      identityType: 'normal',
      userId: 'Boss' + uid,
      orderId: dingdanId,
      groupName: this.data.jibenShuju.nicheng + '的订单群',
      isCross: 0
    }).catch(err => {
      console.error('跳转群聊失败', err)
      wx.showToast({ title: '跳转聊天失败，请检查网络', icon: 'none' })
    })

    // 立即恢复角色
    app.globalData.currentRole = savedRole
    app.globalData.xshenfen = savedXshenfen
    wx.setStorageSync('currentRole', savedRole)
  },

  // 结算相关
  onFancheshuInput(e) { this.setData({ 'jiesuan.fancheCishu': e.detail.value }) },

  selectSpeed(e) {
    const value = parseInt(e.currentTarget.dataset.value)
    const explain = this.data.speedOptions.find(v => v.value === value)?.explain || ''
    this.setData({
      'jiesuan.speedValue': value,
      speedExplain: explain      // 更新解释文字
    })
  },
  selectAttitude(e) {
    const value = parseInt(e.currentTarget.dataset.value)
    const explain = this.data.attitudeOptions.find(v => v.value === value)?.explain || ''
    this.setData({
      'jiesuan.attitudeValue': value,
      attitudeExplain: explain
    })
  },
  onLiuyanInput(e) { this.setData({ 'jiesuan.liuyan': e.detail.value.slice(0, 50) }) },

  showSpeedStandard() { this.setData({ showSpeedModal: true }) },
  hideSpeedModal() { this.setData({ showSpeedModal: false }) },
  showAttitudeStandard() { this.setData({ showAttitudeModal: true }) },
  hideAttitudeModal() { this.setData({ showAttitudeModal: false }) },
  noop() {},

  showSettleConfirm() {
    const { fancheCishu } = this.data.jiesuan
    if (!fancheCishu || isNaN(parseInt(fancheCishu))) {
      wx.showToast({ title: '请填写翻车次数', icon: 'none' })
      return
    }
    if (!this.data.jiesuan.speedValue || !this.data.jiesuan.attitudeValue) {
      wx.showToast({ title: '请选择上线速度和服务态度', icon: 'none' })
      return
    }
    this.setData({ showConfirm: true, countdown: 3 })
    this.countdownTimer = setInterval(() => {
      const next = this.data.countdown - 1
      if (next <= 0) {
        clearInterval(this.countdownTimer)
        this.setData({ countdown: 0 })
      } else {
        this.setData({ countdown: next })
      }
    }, 1000)
  },
  cancelConfirm() {
    clearInterval(this.countdownTimer)
    this.setData({ showConfirm: false, countdown: 3 })
  },
  async confirmSettle() {
    if (this.data.countdown !== 0) return
    clearInterval(this.countdownTimer)
    this.setData({ showConfirm: false, countdown: 3 })

    wx.showLoading({ title: '结算中' })
    const { jiesuan, jibenShuju } = this.data
    try {
      const res = await request({
        url: '/dingdan/jiedan2',
        method: 'POST',
        data: {
          dingdanId: jibenShuju.dingdanId,
          fanche_cishu: parseInt(jiesuan.fancheCishu),
          shangxian_sudu: jiesuan.speedValue,
          fuwu_taidu: jiesuan.attitudeValue,
          liuyan: jiesuan.liuyan
        }
      })
      wx.hideLoading()
      if (res && res.data.code === 0) {
        wx.showToast({ title: '结算成功' })
        setTimeout(() => wx.navigateBack(), 1000)
      } else {
        wx.showToast({ title: res?.data?.msg || '结算失败', icon: 'none' })
      }
    } catch (e) {
      wx.hideLoading()
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  }
})