// pages/sjpaidan/sjpaidan.js
import request from '../../utils/request.js'
import PopupService from '../../services/popupService.js'

Page({
  data: {
    sjyue: '0.00',
    shangpinList: [],
    selectedTypeId: null,
    selectedHuiyuanId: null,
    selectedYaoqiuleixing: null,
    currentTypeChenghaoList: [],

    dingdanJieshao: '',
    dingdanBeizhu: '',
    laobanName: '',
    zhidingUid: '',
    jiage: '',

    selectedLabelId: '',
    selectedLabelName: '',

    commissionEnabled: false,
    commissionValue: '',

    isSpecialType: false,
    currentTypeGoodsList: [],
    selectedGoodsId: null,
    selectedGoodsTitle: '',
    commissionLocked: false,

    isLoading: false,
    isSubmitting: false,
    tutorialBtnHidden: false,
    bgImageUrl: ''
  },

  onLoad() {
    this.loadBgImage()
    this.loadShangjiaYue()
    this.loadShangpinTypes()
    this.startTutorialBtnTimer()
  },

  onShow() {
    this.loadShangjiaYue()
    this.loadBgImage()
    this.registerNotificationComponent()
    this.startTutorialBtnTimer()
  },

  onHide() {
    PopupService.reset()
  },

  onUnload() {
    if (this.tutorialTimer) clearTimeout(this.tutorialTimer)
    PopupService.reset()
  },

  loadBgImage() {
    const app = getApp()
    const ossBase = app.globalData.ossImageUrl || 'https://your-oss-bucket.oss-cn-region.aliyuncs.com'
    const bgUrl = ossBase.replace(/\/$/, '') + '/beijing/shangjiapaidan/bg.jpg'
    this.setData({ bgImageUrl: bgUrl })
  },

  loadShangjiaYue() {
    const app = getApp()
    const shangjiaData = app.globalData.shangjia || {}
    this.setData({ sjyue: shangjiaData.sjyue || '0.00' })
  },

  async loadShangpinTypes() {
    this.setData({ isLoading: true })
    try {
      const res = await request({
        url: '/dingdan/sjspleixing',
        method: 'POST'
      })
      if (res && res.data.code === 200) {
        let list = res.data.data || []
        list.reverse()
        this.setData({ shangpinList: list, isLoading: false })
        if (list.length > 0) {
          this.setSelectedType(list[0])
        }
      } else {
        throw new Error(res.data.msg || '加载失败')
      }
    } catch (error) {
      this.setData({ isLoading: false })
      wx.showToast({ title: '加载类型失败', icon: 'error' })
    }
  },

  // 🔴 切换类型时清空订单介绍、备注、标签、商品模板和押金
  setSelectedType(item) {
    const isSpecial = item.is_special_type || false

    this.setData({
      selectedTypeId: item.id,
      selectedHuiyuanId: item.huiyuan_id,
      selectedYaoqiuleixing: item.yaoqiuleixing,
      currentTypeChenghaoList: item.chenghaoList || [],
      selectedLabelId: '',
      selectedLabelName: '',
      selectedGoodsId: null,
      selectedGoodsTitle: '',
      isSpecialType: isSpecial,
      currentTypeGoodsList: item.goodsList || [],
      // 清空订单介绍和备注
      dingdanJieshao: '',
      dingdanBeizhu: '',
      // 重置押金，等用户选商品再设置
      commissionEnabled: false,
      commissionValue: '',
      commissionLocked: false
    })
  },

  onGoodsItemTap(e) {
    const goodsId = e.currentTarget.dataset.id
    if (!goodsId) return

    const goods = this.data.currentTypeGoodsList.find(item => item.id == goodsId)
    if (!goods) {
      wx.showToast({ title: '商品数据异常', icon: 'none' })
      return
    }

    const hasYongjin = goods.yongjin && parseFloat(goods.yongjin) > 0
    this.setData({
      selectedGoodsId: goods.id,
      selectedGoodsTitle: goods.biaoqian || '',
      dingdanJieshao: goods.jieshao || '',
      dingdanBeizhu: '',
      commissionEnabled: hasYongjin,
      commissionValue: hasYongjin ? goods.yongjin : '',
      commissionLocked: true
    })
  },

  onDingdanJieshaoInput(e) {
    if (this.data.isSpecialType) return
    this.setData({ dingdanJieshao: e.detail.value })
  },
  onDingdanBeizhuInput(e) {
    if (this.data.isSpecialType) return
    this.setData({ dingdanBeizhu: e.detail.value })
  },
  onLaobanNameInput(e) { this.setData({ laobanName: e.detail.value }) },
  onZhidingUidInput(e) { this.setData({ zhidingUid: e.detail.value }) },
  onJiageInput(e) {
    let value = e.detail.value
    if (value === '' || /^\d+(\.\d{0,2})?$/.test(value)) {
      this.setData({ jiage: value })
    }
  },

  onLabelChange(e) {
    const idx = e.detail.value
    const label = this.data.currentTypeChenghaoList[idx]
    if (label) {
      this.setData({ selectedLabelId: label.id, selectedLabelName: label.mingcheng })
    } else {
      this.setData({ selectedLabelId: '', selectedLabelName: '' })
    }
  },

  onCommissionToggle() {
    if (this.data.commissionLocked) return
    this.setData({ commissionEnabled: !this.data.commissionEnabled })
  },
  onCommissionValueInput(e) {
    if (this.data.commissionLocked) return
    let value = e.detail.value
    if (value === '' || /^\d+(\.\d{0,2})?$/.test(value)) {
      this.setData({ commissionValue: value })
    }
  },

  validateForm() {
    const {
      selectedTypeId, dingdanJieshao, laobanName, jiage,
      sjyue, commissionEnabled, commissionValue,
      isSpecialType, selectedGoodsId
    } = this.data

    if (!selectedTypeId) {
      wx.showToast({ title: '请选择订单类型', icon: 'none' })
      return false
    }
    if (isSpecialType && !selectedGoodsId) {
      wx.showToast({ title: '请选择一个商品模板', icon: 'none' })
      return false
    }
    if (!dingdanJieshao.trim()) {
      wx.showToast({ title: '请输入订单介绍', icon: 'none' })
      return false
    }
    if (!laobanName.trim()) {
      wx.showToast({ title: '请输入老板游戏昵称', icon: 'none' })
      return false
    }
    if (!jiage) {
      wx.showToast({ title: '请输入订单价格', icon: 'none' })
      return false
    }

    const price = parseFloat(jiage)
    if (isNaN(price) || price < 0.1 || price > 10000) {
      wx.showToast({ title: '价格需在0.1-10000元之间', icon: 'none' })
      return false
    }
    if (jiage.includes('.') && jiage.split('.')[1].length > 2) {
      wx.showToast({ title: '最多支持两位小数', icon: 'none' })
      return false
    }

    if (commissionEnabled) {
      const com = parseFloat(commissionValue)
      if (isNaN(com) || com <= 0) {
        wx.showToast({ title: '请输入有效的佣金金额', icon: 'none' })
        return false
      }
      if (com > 50000) {
        wx.showToast({ title: '佣金建议不超过50000元', icon: 'none' })
        return false
      }
    }

    const balance = parseFloat(sjyue)
    if (price > balance) {
      wx.showModal({
        title: '余额不足',
        content: `当前余额${sjyue}元，需要${jiage}元。请先充值。`,
        confirmText: '去充值',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/sjchongzhi/sjchongzhi' })
          }
        }
      })
      return false
    }

    return true
  },

  resetForm() {
    this.setData({
      dingdanJieshao: '',
      dingdanBeizhu: '',
      laobanName: '',
      zhidingUid: '',
      jiage: '',
      selectedLabelId: '',
      selectedLabelName: '',
      selectedGoodsId: null,
      selectedGoodsTitle: '',
      commissionEnabled: false,
      commissionValue: ''
    })
    const currentType = this.data.shangpinList.find(t => t.id === this.data.selectedTypeId)
    if (currentType) this.setSelectedType(currentType)
  },

  async onSubmit() {
    if (this.data.isSubmitting) return
    if (!this.validateForm()) return
    this.setData({ isSubmitting: true })

    const postData = {
      shangpinTypeId: this.data.selectedTypeId,
      huiyuanId: this.data.selectedHuiyuanId,
      yaoqiuleixing: this.data.selectedYaoqiuleixing,
      dingdanJieshao: this.data.dingdanJieshao.trim(),
      dingdanBeizhu: this.data.dingdanBeizhu.trim() || '',
      laobanName: this.data.laobanName.trim(),
      zhidingUid: this.data.zhidingUid.trim() || '',
      jiage: this.data.jiage,
      labelId: this.data.selectedLabelId || '',
      labelName: this.data.selectedLabelName || '',
      commissionEnabled: this.data.commissionEnabled,
      commissionValue: this.data.commissionEnabled ? this.data.commissionValue : '',
      goodsId: this.data.selectedGoodsId || ''
    }

    try {
      const res = await request({
        url: '/dingdan/sjpaifa',
        method: 'POST',
        data: postData
      })
      if (res && res.data.code === 200) {
        wx.showToast({ title: '派单成功', icon: 'success' })
        const orderAmount = parseFloat(this.data.jiage)
        const app = getApp()
        if (app.globalData.shangjia) {
          const newBalance = parseFloat(app.globalData.shangjia.sjyue || '0') - orderAmount
          app.globalData.shangjia.sjyue = newBalance.toFixed(2)
          app.globalData.shangjia.fadanzong = (parseInt(app.globalData.shangjia.fadanzong || '0') + 1).toString()
          app.globalData.shangjia.riliushui = (parseFloat(app.globalData.shangjia.riliushui || '0') + orderAmount).toFixed(2)
          app.globalData.shangjia.yueliushui = (parseFloat(app.globalData.shangjia.yueliushui || '0') + orderAmount).toFixed(2)
          this.setData({ sjyue: app.globalData.shangjia.sjyue })
        }
        setTimeout(() => {
          this.resetForm()
          this.setData({ isSubmitting: false })
        }, 1500)
      } else {
        wx.showModal({ title: '派单失败', content: res.data.msg || '请稍后重试', showCancel: false })
        this.setData({ isSubmitting: false })
      }
    } catch (error) {
      wx.showModal({ title: '请求失败', content: error.message || '网络错误', showCancel: false })
      this.setData({ isSubmitting: false })
    }
  },

  onSelectType(e) {
    const { item } = e.currentTarget.dataset
    this.setSelectedType(item)
  },

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

  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)
  },

  async onTutorialBtnTap() {
    this.resetTutorialBtn()
    PopupService.checkAndShow(this, 'sjpd1')
  }
})