// pages/sjddxq/sjddxq.js - 商家订单详情（完整版，已添加罚款/退款操作及教程按钮）
const app = getApp()
import request from '../../utils/request.js'
import connectionManager from '../../utils/xiaoxilj.js'
import PopupService from '../../services/popupService.js'   // 新增：导入弹窗服务

Page({
  data: {
    jibenShuju: {
      dingdan_id: '', tupian: '', jieshao: '', create_time: '',
      jine: '', nicheng: '', beizhu: '', zhuangtai: 0, fadanpingtai: 0, is_cross: 0
    },
    dashouInfo: { yonghuid: '', nicheng: '', avatar: '' },
    xiangxiShuju: {
      dashou_jiaofu: [], dashou_liuyan: '', tuikuan_liyou: '', shangjia_liuyan: ''
    },
    fadanData: null,
    fenhongLilv: 0,
    xinDingdanId: '',
    zhuangtaiYanseMap: {
      1: '#E8F5E9', 2: '#E3F2FD', 3: '#F3E5F5', 4: '#FFF3E0',
      5: '#FFEBEE', 6: '#EFEBE9', 7: '#E0F7FA', 8: '#FFF8E1'
    },
    zhuangtaiWenziMap: {
      1: '已下单', 2: '进行中', 3: '已完成', 4: '退款中',
      5: '已退款', 6: '退款失败', 7: '指定中', 8: '结算中'
    },
    isLoading: true,
    showChexiaoModal: false, chexiaoLiyou: '', isChexiaoLoading: false,
    showTuikuanModal: false, tuikuanLiyou: '', isTuikuanLoading: false,
    showFakuanModal: false, fakuanLiyou: '', fakuanJine: '', yingxiangQiangdan: true, isFakuanLoading: false,
    showGhDashouModal: false, isGhDashouLoading: false,
    showJiesuanConfirm: false, isJiesuanLoading: false,
    jiesuanPingfen: 0, jiesuanLiuyan: '',
    xingxingData: [
      { id: 1, active: false }, { id: 2, active: false }, { id: 3, active: false },
      { id: 4, active: false }, { id: 5, active: false }
    ],
    currentIMUserId: '',

    // ========== 新增：罚单/订单操作弹窗控制 ==========
    showModifyFakuanModal: false,     // 修改罚款弹窗
    modifyFakuanLiyou: '',            // 修改后的罚款理由
    modifyFakuanJine: '',             // 修改后的罚款金额
    showCancelFakuanModal: false,     // 撤销罚款弹窗
    cancelFakuanLiyou: '',            // 撤销驳回理由
    showResubmitFakuanModal: false,   // 再次申请罚款弹窗
    resubmitFakuanLiyou: '',          // 再次申请的理由
    resubmitFakuanJine: '',           // 再次申请的金额
    showCancelTuikuanModal: false,    // 撤销退款申请弹窗
    cancelTuikuanLiyou: '',           // 撤销退款理由
    showModifyTuikuanModal: false,    // 修改退款理由弹窗
    modifyTuikuanLiyou: '',           // 修改后的退款理由
    // 教程按钮状态
    tutorialBtnHidden: false
  },

  onLoad(options) {
    wx.setNavigationBarTitle({ title: '订单详情' })
    this.ensureIMConnection()
    this.jiexiTiaozhuanCanshu(options)
    // 新增：启动教程按钮定时器
    this.startTutorialBtnTimer()
  },

  onShow() {
    this.registerNotificationComponent()
    this.ensureIMConnection()
  },

  onHide() {
    // 页面隐藏时重置弹窗服务状态，避免影响其他页面
    PopupService.reset()
  },

  onUnload() {
    // 清除缩进定时器，避免内存泄漏
    if (this.tutorialTimer) {
      clearTimeout(this.tutorialTimer)
    }
    // 页面卸载时重置弹窗服务
    PopupService.reset()
  },

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

  ensureIMConnection() {
    const uid = wx.getStorageSync('uid')
    if (!uid) return
    app.globalData.currentRole = 'shangjia'
    wx.setStorageSync('currentRole', 'shangjia')
    const targetUserId = 'Sj' + uid
    const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected'
    const currentUserId = wx.goEasy?.im?.userId
    if ((status === 'connected' || status === 'reconnected') && currentUserId === targetUserId) {
      this.setData({ currentIMUserId: targetUserId })
      return
    }
    if (app.ensureConnection) app.ensureConnection()
    this.setData({ currentIMUserId: targetUserId })
  },

  jiexiTiaozhuanCanshu(options) {
    try {
      const dingdanDataStr = options.dingdanData || ''
      if (!dingdanDataStr) {
        wx.showToast({ title: '订单数据错误', icon: 'none' })
        setTimeout(() => wx.navigateBack(), 1500)
        return
      }
      const dingdanData = JSON.parse(decodeURIComponent(dingdanDataStr))
      let tupianUrl = dingdanData.tupian || ''
      if (!tupianUrl) tupianUrl = this.getTupianUrl()
      let jine = parseFloat(dingdanData.jine || 0)
      if (isNaN(jine)) jine = 0
      this.setData({
        'jibenShuju.dingdan_id': dingdanData.dingdan_id || '',
        'jibenShuju.tupian': tupianUrl,
        'jibenShuju.jieshao': dingdanData.jieshao || '',
        'jibenShuju.create_time': dingdanData.create_time || '',
        'jibenShuju.jine': jine.toFixed(2),
        'jibenShuju.nicheng': dingdanData.nicheng || '',
        'jibenShuju.beizhu': dingdanData.beizhu || '',
        'jibenShuju.zhuangtai': dingdanData.zhuangtai || 0,
        'jibenShuju.fadanpingtai': dingdanData.fadanpingtai || 0,
        'jibenShuju.is_cross': dingdanData.is_cross || 0,
        isLoading: false
      })
      this.jiazaiXiangxiShuju(dingdanData.dingdan_id)
    } catch (error) {
      console.error('解析订单数据失败', error)
      wx.showToast({ title: '数据解析失败', icon: 'none' })
      setTimeout(() => wx.navigateBack(), 1500)
    }
  },

  getTupianUrl() {
    const cacheTouxiang = wx.getStorageSync('touxiang') || ''
    let tupianPath = cacheTouxiang || app.globalData.morentouxiang || ''
    const ossImageUrl = app.globalData.ossImageUrl || ''
    if (tupianPath && ossImageUrl) {
      if (tupianPath.startsWith('/')) tupianPath = tupianPath.substring(1)
      return ossImageUrl + tupianPath
    }
    return ''
  },

  async jiazaiXiangxiShuju(dingdanId) {
    if (!dingdanId) return
    try {
      const res = await request({
        url: '/dingdan/sjddxq',
        method: 'POST',
        data: { dingdan_id: dingdanId },
        header: { 'content-type': 'application/json' }
      })
      if (res && res.data.code === 0 && res.data.data) {
        const d = res.data.data
        let jiaofuList = d.dashou_jiaofu || []
        jiaofuList = jiaofuList.map(url => {
          if (url && !url.startsWith('http')) {
            const oss = app.globalData.ossImageUrl || ''
            return oss + url
          }
          return url
        })
        let dashouAvatar = d.dashou_avatar || ''
        if (dashouAvatar && !dashouAvatar.startsWith('http')) {
          dashouAvatar = (app.globalData.ossImageUrl || '') + dashouAvatar
        }
        this.setData({
          'dashouInfo.yonghuid': d.dashou_yonghuid || '',
          'dashouInfo.nicheng': d.dashou_nicheng || '',
          'dashouInfo.avatar': dashouAvatar,
          'xiangxiShuju.dashou_jiaofu': jiaofuList,
          'xiangxiShuju.dashou_liuyan': d.dashou_liuyan || '',
          'xiangxiShuju.tuikuan_liyou': d.tuikuan_liyou || '',
          'xiangxiShuju.shangjia_liuyan': d.shangjia_liuyan || '',
          fadanData: d.fadan || null,
          fenhongLilv: parseFloat(d.fenhong_lilv) || 0,
          xinDingdanId: d.xin_dingdan_id || '',
          'jibenShuju.zhuangtai': d.zhuangtai || this.data.jibenShuju.zhuangtai,
          'jibenShuju.is_cross': d.is_cross != null ? d.is_cross : this.data.jibenShuju.is_cross,
          'jibenShuju.fadanpingtai': d.fadanpingtai != null ? d.fadanpingtai : this.data.jibenShuju.fadanpingtai,
        })
      } else {
        wx.showToast({ title: res?.data?.msg || '获取详情失败', icon: 'none' })
      }
    } catch (err) {
      console.error('加载详情失败', err)
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

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

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

  goToKefu() {
    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' })
      }
    })
  },

  // ===== 联系打手（后端准备配对群 + 稳定跳转） =====
  goToChatWithDashou() {
    const uid = wx.getStorageSync('uid')
    if (!uid) return

    const orderId = this.data.jibenShuju.dingdan_id
    if (!orderId) {
      wx.showToast({ title: '订单ID缺失', icon: 'none' })
      return
    }

    connectionManager.connectToGroupChat({
      identityType: 'shangjia',
      userId: 'Sj' + uid,
      orderId,
      partnerUid: this.data.dashouInfo.yonghuid,
      fadanPingtai: this.data.jibenShuju.fadanpingtai || 0,
      groupName: (this.data.dashouInfo.nicheng || this.data.jibenShuju.nicheng) + '的订单群',
      isCross: this.data.jibenShuju.is_cross || 0
    }).catch(err => {
      console.error('跳转群聊失败', err)
    })
  },

  // ========== 以下所有业务功能完全保持不变 ==========
  showGhDashouConfirm() { this.setData({ showGhDashouModal: true }) },
  closeGhDashouModal() { this.setData({ showGhDashouModal: false }) },
  async tijiaoGhDashou() {
    if (this.data.isGhDashouLoading) return
    this.setData({ isGhDashouLoading: true })
    wx.showLoading({ title: '更换中...', mask: true })
    try {
      const res = await request({
        url: '/dingdan/zxsjghds',
        method: 'POST',
        data: { dingdan_id: this.data.jibenShuju.dingdan_id },
        header: { 'content-type': 'application/json' }
      })
      wx.hideLoading()
      this.setData({ isGhDashouLoading: false, showGhDashouModal: false })
      if (res && res.data.code === 0) {
        this.setData({ xinDingdanId: res.data.data?.xin_dingdan_id || '' })
        wx.showToast({ title: '更换成功', icon: 'success' })
        this.jiazaiXiangxiShuju(this.data.jibenShuju.dingdan_id)
      } else {
        wx.showToast({ title: res?.data?.msg || '更换失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isGhDashouLoading: false, showGhDashouModal: false })
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  showFakuanModal() { this.setData({ showFakuanModal: true, fakuanLiyou: '', fakuanJine: '', yingxiangQiangdan: true }) },
  closeFakuanModal() { this.setData({ showFakuanModal: false }) },
  inputFakuanLiyou(e) { this.setData({ fakuanLiyou: e.detail.value.slice(0, 50) }) },
  inputFakuanJine(e) { this.setData({ fakuanJine: e.detail.value }) },
  toggleQiangdan() { this.setData({ yingxiangQiangdan: !this.data.yingxiangQiangdan }) },
  jisuanFenhong() {
    const jine = parseFloat(this.data.fakuanJine)
    if (isNaN(jine) || jine <= 0) return '0.00'
    return (jine * this.data.fenhongLilv).toFixed(2)
  },
  async tijiaoFakuan() {
    const { fakuanLiyou, fakuanJine, jibenShuju, dashouInfo } = this.data
    if (!fakuanLiyou.trim()) { wx.showToast({ title: '请输入罚款原因', icon: 'none' }); return }
    const jineNum = parseFloat(fakuanJine)
    if (isNaN(jineNum) || jineNum <= 0) { wx.showToast({ title: '请输入正确的罚款金额', icon: 'none' }); return }
    if (this.data.isFakuanLoading) return
    this.setData({ isFakuanLoading: true })
    wx.showLoading({ title: '提交中...', mask: true })
    try {
      const res = await request({
        url: '/dingdan/sjfksq',
        method: 'POST',
        data: {
          dingdan_id: jibenShuju.dingdan_id,
          chufa_liyou: fakuanLiyou,
          fakuanjine: jineNum.toFixed(2),
          yingxiang_qiangdan: this.data.yingxiangQiangdan ? 1 : 0,
          dashou_id: dashouInfo.yonghuid
        },
        header: { 'content-type': 'application/json' }
      })
      wx.hideLoading()
      this.setData({ isFakuanLoading: false })
      if (res && res.data.code === 0) {
        wx.showToast({ title: '罚款申请已提交', icon: 'success' })
        this.setData({ showFakuanModal: false })
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id)
      } else {
        wx.showToast({ title: res?.data?.msg || '提交失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isFakuanLoading: false })
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  showChexiaoBtn() { this.setData({ showChexiaoModal: true, chexiaoLiyou: '' }) },
  closeChexiaoModal() { this.setData({ showChexiaoModal: false }) },
  shuruChexiaoLiyou(e) { this.setData({ chexiaoLiyou: e.detail.value.slice(0, 50) }) },
  async tijiaoChexiao() {
    if (this.data.isChexiaoLoading) return
    const { chexiaoLiyou, jibenShuju } = this.data
    if (!chexiaoLiyou.trim()) { wx.showToast({ title: '请输入撤销原因', icon: 'none' }); return }
    this.setData({ isChexiaoLoading: true })
    wx.showLoading({ title: '撤销中...', mask: true })
    try {
      const res = await request({
        url: '/dingdan/sjchexiao',
        method: 'POST',
        data: { dingdan_id: jibenShuju.dingdan_id, chexiao_liyou: chexiaoLiyou },
        header: { 'content-type': 'application/json' }
      })
      wx.hideLoading()
      this.setData({ isChexiaoLoading: false })
      if (res && res.data.code === 0) {
        this.setData({ 'jibenShuju.zhuangtai': 5, showChexiaoModal: false })
        wx.showToast({ title: '撤销成功', icon: 'success' })
      } else {
        wx.showToast({ title: res?.data?.msg || '撤销失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isChexiaoLoading: false })
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  showTuikuanBtn() { this.setData({ showTuikuanModal: true, tuikuanLiyou: '' }) },
  closeTuikuanModal() { this.setData({ showTuikuanModal: false }) },
  shuruTuikuanLiyou(e) { this.setData({ tuikuanLiyou: e.detail.value.slice(0, 50) }) },
  async tijiaoTuikuan() {
    if (this.data.isTuikuanLoading) return
    const { tuikuanLiyou, jibenShuju } = this.data
    if (!tuikuanLiyou.trim()) { wx.showToast({ title: '请输入退款原因', icon: 'none' }); return }
    this.setData({ isTuikuanLoading: true })
    wx.showLoading({ title: '提交中...', mask: true })
    try {
      const res = await request({
        url: '/dingdan/sjtkshenqing',
        method: 'POST',
        data: { dingdan_id: jibenShuju.dingdan_id, tuikuan_liyou: tuikuanLiyou },
        header: { 'content-type': 'application/json' }
      })
      wx.hideLoading()
      this.setData({ isTuikuanLoading: false })
      if (res && res.data.code === 0) {
        this.setData({ 'jibenShuju.zhuangtai': 4, showTuikuanModal: false })
        wx.showToast({ title: '退款申请已提交', icon: 'success' })
      } else {
        wx.showToast({ title: res?.data?.msg || '失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isTuikuanLoading: false })
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  dianjiXingxing(e) {
    const pf = e.currentTarget.dataset.index
    const newStars = this.data.xingxingData.map((item, idx) => ({ ...item, active: idx < pf }))
    this.setData({ xingxingData: newStars, jiesuanPingfen: pf })
  },
  shuruLiuyan(e) { this.setData({ jiesuanLiuyan: e.detail.value.slice(0, 50) }) },
  showJiesuanConfirm() { this.setData({ showJiesuanConfirm: true }) },
  closeJiesuanConfirm() { this.setData({ showJiesuanConfirm: false }) },
  async tijiaoJiesuan() {
    if (this.data.isJiesuanLoading) return
    this.setData({ isJiesuanLoading: true })
    wx.showLoading({ title: '结算中...', mask: true })
    try {
      const res = await request({
        url: '/dingdan/sjjiesuan',
        method: 'POST',
        data: {
          dingdan_id: this.data.jibenShuju.dingdan_id,
          pingfen: this.data.jiesuanPingfen,
          liuyan: this.data.jiesuanLiuyan
        },
        header: { 'content-type': 'application/json' }
      })
      wx.hideLoading()
      this.setData({ isJiesuanLoading: false, showJiesuanConfirm: false })
      if (res && res.data.code === 0) {
        this.setData({ 'jibenShuju.zhuangtai': 3 })
        wx.showToast({ title: '结算成功', icon: 'success' })
      } else {
        wx.showToast({ title: res?.data?.msg || '结算失败', icon: 'none' })
      }
    } catch (err) {
      wx.hideLoading()
      this.setData({ isJiesuanLoading: false })
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  // ========== 新增：罚款操作（修改/撤销/再次申请） ==========
  // 显示修改罚款弹窗（仅当状态为待缴纳 或 申诉中 时可用）
  showModifyFakuan() {
    const status = this.data.fadanData?.zhuangtai;
    if (status !== 1 && status !== 3) {
      wx.showToast({ title: '当前状态不可修改罚款', icon: 'none' });
      return;
    }
    this.setData({
      showModifyFakuanModal: true,
      modifyFakuanLiyou: this.data.fadanData?.chufaliyou || '',
      modifyFakuanJine: this.data.fadanData?.fakuanjine || ''
    });
  },
  closeModifyFakuanModal() {
    this.setData({ showModifyFakuanModal: false });
  },
  inputModifyFakuanLiyou(e) {
    this.setData({ modifyFakuanLiyou: e.detail.value.slice(0, 100) });
  },
  inputModifyFakuanJine(e) {
    this.setData({ modifyFakuanJine: e.detail.value });
  },
  async submitModifyFakuan() {
    const { modifyFakuanLiyou, modifyFakuanJine, fadanData, jibenShuju } = this.data;
    if (!modifyFakuanLiyou.trim()) {
      wx.showToast({ title: '请输入罚款理由', icon: 'none' }); return;
    }
    const jine = parseFloat(modifyFakuanJine);
    if (isNaN(jine) || jine <= 0) {
      wx.showToast({ title: '请输入正确的罚款金额', icon: 'none' }); return;
    }
    wx.showLoading({ title: '提交中...', mask: true });
    try {
      const res = await request({
        url: '/dingdan/sjfkxgycx',
        method: 'POST',
        data: {
          operation: 'modify_penalty',
          fadan_id: fadanData.id,
          dingdan_id: jibenShuju.dingdan_id,
          liyou: modifyFakuanLiyou,
          jine: jine.toFixed(2)
        }
      });
      wx.hideLoading();
      if (res && res.data.code === 0) {
        wx.showToast({ title: '修改成功', icon: 'success' });
        this.setData({ showModifyFakuanModal: false });
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id); // 刷新数据
      } else {
        wx.showToast({ title: res?.data?.msg || '修改失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // 显示撤销罚款弹窗（待缴纳/申诉中 可撤销，变为已驳回）
  showCancelFakuan() {
    const status = this.data.fadanData?.zhuangtai;
    if (status !== 1 && status !== 3) {
      wx.showToast({ title: '当前状态不可撤销罚款', icon: 'none' });
      return;
    }
    this.setData({ showCancelFakuanModal: true, cancelFakuanLiyou: '' });
  },
  closeCancelFakuanModal() {
    this.setData({ showCancelFakuanModal: false });
  },
  inputCancelFakuanLiyou(e) {
    this.setData({ cancelFakuanLiyou: e.detail.value.slice(0, 100) });
  },
  async submitCancelFakuan() {
    const { cancelFakuanLiyou, fadanData, jibenShuju } = this.data;
    if (!cancelFakuanLiyou.trim()) {
      wx.showToast({ title: '请输入驳回理由', icon: 'none' }); return;
    }
    wx.showLoading({ title: '提交中...', mask: true });
    try {
      const res = await request({
        url: '/dingdan/sjfkxgycx',
        method: 'POST',
        data: {
          operation: 'cancel_penalty',
          fadan_id: fadanData.id,
          dingdan_id: jibenShuju.dingdan_id,
          liyou: cancelFakuanLiyou
        }
      });
      wx.hideLoading();
      if (res && res.data.code === 0) {
        wx.showToast({ title: '已撤销', icon: 'success' });
        this.setData({ showCancelFakuanModal: false });
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id);
      } else {
        wx.showToast({ title: res?.data?.msg || '撤销失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // 显示再次申请罚款弹窗（仅当状态为已驳回时可用）
  showResubmitFakuan() {
    if (this.data.fadanData?.zhuangtai !== 4) {
      wx.showToast({ title: '当前状态不可再次申请', icon: 'none' });
      return;
    }
    this.setData({
      showResubmitFakuanModal: true,
      resubmitFakuanLiyou: '',
      resubmitFakuanJine: ''
    });
  },
  closeResubmitFakuanModal() {
    this.setData({ showResubmitFakuanModal: false });
  },
  inputResubmitFakuanLiyou(e) {
    this.setData({ resubmitFakuanLiyou: e.detail.value.slice(0, 100) });
  },
  inputResubmitFakuanJine(e) {
    this.setData({ resubmitFakuanJine: e.detail.value });
  },
  async submitResubmitFakuan() {
    const { resubmitFakuanLiyou, resubmitFakuanJine, fadanData, jibenShuju } = this.data;
    if (!resubmitFakuanLiyou.trim()) {
      wx.showToast({ title: '请输入罚款理由', icon: 'none' }); return;
    }
    const jine = parseFloat(resubmitFakuanJine);
    if (isNaN(jine) || jine <= 0) {
      wx.showToast({ title: '请输入正确的罚款金额', icon: 'none' }); return;
    }
    wx.showLoading({ title: '提交中...', mask: true });
    try {
      const res = await request({
        url: '/dingdan/sjfkxgycx',
        method: 'POST',
        data: {
          operation: 'resubmit_penalty',
          fadan_id: fadanData.id,
          dingdan_id: jibenShuju.dingdan_id,
          liyou: resubmitFakuanLiyou,
          jine: jine.toFixed(2)
        }
      });
      wx.hideLoading();
      if (res && res.data.code === 0) {
        wx.showToast({ title: '申请成功', icon: 'success' });
        this.setData({ showResubmitFakuanModal: false });
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id);
      } else {
        wx.showToast({ title: res?.data?.msg || '申请失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // ========== 新增：订单退款操作（撤销/修改理由） ==========
  showCancelTuikuan() {
    if (this.data.jibenShuju.zhuangtai !== 4) {
      wx.showToast({ title: '只有退款中的订单可撤销', icon: 'none' });
      return;
    }
    this.setData({ showCancelTuikuanModal: true, cancelTuikuanLiyou: '' });
  },
  closeCancelTuikuanModal() {
    this.setData({ showCancelTuikuanModal: false });
  },
  inputCancelTuikuanLiyou(e) {
    this.setData({ cancelTuikuanLiyou: e.detail.value.slice(0, 100) });
  },
  async submitCancelTuikuan() {
    const { cancelTuikuanLiyou, jibenShuju } = this.data;
    if (!cancelTuikuanLiyou.trim()) {
      wx.showToast({ title: '请输入撤销理由', icon: 'none' }); return;
    }
    wx.showLoading({ title: '撤销中...', mask: true });
    try {
      const res = await request({
        url: '/dingdan/sjfkxgycx',
        method: 'POST',
        data: {
          operation: 'cancel_refund',
          dingdan_id: jibenShuju.dingdan_id,
          liyou: cancelTuikuanLiyou
        }
      });
      wx.hideLoading();
      if (res && res.data.code === 0) {
        wx.showToast({ title: '已撤销退款申请', icon: 'success' });
        this.setData({ showCancelTuikuanModal: false });
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id);
      } else {
        wx.showToast({ title: res?.data?.msg || '撤销失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  showModifyTuikuan() {
    if (this.data.jibenShuju.zhuangtai !== 4) {
      wx.showToast({ title: '只有退款中的订单可修改理由', icon: 'none' });
      return;
    }
    this.setData({
      showModifyTuikuanModal: true,
      modifyTuikuanLiyou: this.data.xiangxiShuju.tuikuan_liyou || ''
    });
  },
  closeModifyTuikuanModal() {
    this.setData({ showModifyTuikuanModal: false });
  },
  inputModifyTuikuanLiyou(e) {
    this.setData({ modifyTuikuanLiyou: e.detail.value.slice(0, 100) });
  },
  async submitModifyTuikuan() {
    const { modifyTuikuanLiyou, jibenShuju } = this.data;
    if (!modifyTuikuanLiyou.trim()) {
      wx.showToast({ title: '请输入退款理由', icon: 'none' }); return;
    }
    wx.showLoading({ title: '修改中...', mask: true });
    try {
      const res = await request({
        url: '/dingdan/sjfkxgycx',
        method: 'POST',
        data: {
          operation: 'modify_refund_reason',
          dingdan_id: jibenShuju.dingdan_id,
          liyou: modifyTuikuanLiyou
        }
      });
      wx.hideLoading();
      if (res && res.data.code === 0) {
        wx.showToast({ title: '修改成功', icon: 'success' });
        this.setData({ showModifyTuikuanModal: false });
        this.jiazaiXiangxiShuju(jibenShuju.dingdan_id);
      } else {
        wx.showToast({ title: res?.data?.msg || '修改失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // ========== 新增：教程按钮 ==========
  startTutorialBtnTimer() {
    if (this.tutorialTimer) clearTimeout(this.tutorialTimer);
    this.tutorialTimer = setTimeout(() => {
      this.setData({ tutorialBtnHidden: true });
    }, 5000);
  },
  resetTutorialBtn() {
    if (this.data.tutorialBtnHidden) {
      this.setData({ tutorialBtnHidden: false });
    }
    if (this.tutorialTimer) clearTimeout(this.tutorialTimer);
    this.tutorialTimer = setTimeout(() => {
      this.setData({ tutorialBtnHidden: true });
    }, 5000);
  },
  onTutorialBtnTap() {
    this.resetTutorialBtn();
    PopupService.checkAndShow(this, 'sjddxq1');
  }
})