// pages/qiangdan/qiangdan.js
const app = getApp();
import request from '../../utils/request.js';
import PopupService from '../../services/popupService.js';
import { reconnectForRole } from '../../utils/role-tab-bar.js';
import { ensurePhoneAuth } from '../../utils/phone-auth.js';

Page({
  data: {
    // 1. 商品类型相关
    shangpinleixing: [],
    xuanzhongLeixingId: null,

    // 2. 订单列表与分页相关
    dingdanList: [],
    page: 1,
    pageSize: 5,
    hasMore: true,
    isLoading: false,

    // 3. 全局状态字段
    dashoustatus: null,
    zhuanghaoStatus: null,
    dashouzhuangtai: null,
    uid: null,
    huiyuanList: [],
    yajin: 0,
    jifen: 0,

    // 4. 刷新控制字段
    scrollViewRefreshing: false,
    lastRefreshTime: 0,
    refreshCooldown: 2000,
    isLoadingMore: false,

    // 5. 切换类型冷却
    lastSwitchTime: 0,
    switchCooldown: 1500,
    isSwitching: false,

    // 6. OSS地址
    ossImageUrl: app.globalData.ossImageUrl || '',

    // 🆕 7. 标签筛选相关
    bankuaiBiaoqian: [],           // 当前商品类型所属板块的全部标签
    xuanzhongBiaoqianId: 0,        // 0=全部

    // 商品轮播展示（只读 globalData，无额外接口）
    lunboList: [],
  },

  async onLoad(options) {
    this.syncShopBannerFromGlobal();
    this.loadGlobalStatus();
    await this.loadShangpinLeixing();
    PopupService.checkAndShow(this, 'jiedan');
  },

  onHide: function () {
    const popupComp = this.selectComponent('#popupNotice');
    if (popupComp && popupComp.cleanup) {
      popupComp.cleanup();
    }
  },

  async onShow() {
    const phoneOk = await ensurePhoneAuth({ redirect: true, role: 'dashou' });
    if (!phoneOk) return;

    this.syncShopBannerFromGlobal();
    this.registerNotificationComponent();
    this.loadGlobalStatus();

    if (wx.getStorageSync('uid')) {
      // IM 延后连接，避免切 Tab 时卡顿；订单列表不自动刷新，由用户下拉刷新
      setTimeout(() => {
        reconnectForRole('dashou');
        if (app.startImWhenReady) app.startImWhenReady();
      }, 600);
    }
  },

  /** 同步点单端已加载的商品轮播图，仅展示用 */
  syncShopBannerFromGlobal() {
    const oss = app.globalData.ossImageUrl || '';
    const lunboList = (app.globalData.shangpinlunbo || []).map((url) => {
      if (!url) return '';
      return url.startsWith('http') ? url : oss + url;
    }).filter(Boolean);
    this.setData({ lunboList });
  },

  async refreshDashouProfileSilent() {
    try {
      const res = await request({ url: '/yonghu/dashouxinxi', method: 'POST' });
      if (!res || res.data.code != 200) return;
      const data = res.data.data || {};
      const patch = {
        dashouNicheng: data.dashounicheng || '',
        zhanghaoStatus: data.zhanghaostatus || '',
        dashouzhuangtai: data.dashouzhuangtai || '',
        yajin: data.yajin || 0,
        jifen: data.jifen || 0,
        clumber: data.clumber || [],
      };
      Object.assign(app.globalData, {
        dashouNicheng: patch.dashouNicheng,
        zhanghaoStatus: patch.zhanghaoStatus,
        dashouzhuangtai: patch.dashouzhuangtai,
        yajin: patch.yajin,
        jinfen: patch.jifen,
        clumber: patch.clumber,
      });
      if (data.dashoustatus !== undefined) {
        wx.setStorageSync('dashoustatus', data.dashoustatus);
        app.globalData.dashoustatus = data.dashoustatus;
      }
      this.setData({
        zhuanghaoStatus: patch.zhanghaoStatus,
        dashouzhuangtai: patch.dashouzhuangtai,
        huiyuanList: patch.clumber,
        yajin: patch.yajin,
        jifen: patch.jifen,
      });
    } catch (e) {}
  },

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

  loadGlobalStatus() {
    const globalData = app.globalData;
    this.setData({
      dashoustatus: wx.getStorageSync('dashoustatus'),
      zhuanghaoStatus: globalData.zhanghaoStatus,
      dashouzhuangtai: globalData.dashouzhuangtai,
      uid: wx.getStorageSync('uid'),
      huiyuanList: globalData.clumber || [],
      yajin: globalData.yajin || 0,
      jifen: globalData.jinfen || 0
    });
  },

  // 加载商品类型
  async loadShangpinLeixing() {
    wx.showLoading({ title: '加载商品类型...' });
    try {
      const res = await request({
        url: '/dingdan/dsqdhqddlx',
        method: 'POST',
        header: { 'content-type': 'application/json' }
      });
      if (res.statusCode === 200 && res.data) {
        const data = res.data;
        let list = [];
        if (data.code === 200 || data.code === 0) {
          if (data.data && Array.isArray(data.data.list)) list = data.data.list;
          else if (data.data && Array.isArray(data.data)) list = data.data;
          else if (Array.isArray(data.list)) list = data.list;
          else if (Array.isArray(data)) list = data;
        }
        const processedList = this.processTupianUrl(list);
        this.setData({
          shangpinleixing: processedList,
          xuanzhongLeixingId: processedList[0]?.id || null
        });
        if (this.data.xuanzhongLeixingId) {
          this.loadDingdanList(true);
          // 🆕 加载板块标签
          this.loadBankuaiBiaoqian();
        }
      } else {
        wx.showToast({ title: res.data?.msg || '加载商品类型失败', icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '网络错误，加载失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 处理图片URL
  processTupianUrl(list) {
    const ossUrl = app.globalData.ossImageUrl || '';
    return list.map(item => ({
      ...item,
      full_tupian_url: item.tupian_url && !item.tupian_url.startsWith('http')
        ? ossUrl + item.tupian_url
        : (item.tupian_url || '/images/default-type.png')
    }));
  },

  // 🆕 加载板块标签
  async loadBankuaiBiaoqian() {
    const leixingId = this.data.xuanzhongLeixingId;
    if (!leixingId) return;
    try {
      const res = await request({
        url: '/dengji/bkqhbq',
        method: 'POST',
        data: { leixing_id: leixingId }
      });
      if (res && res.data.code === 0) {
        this.setData({
          bankuaiBiaoqian: res.data.data.biaoqian_list || [],
          xuanzhongBiaoqianId: 0
        });
      }
    } catch (e) {
      // 标签加载失败不影响主流程
    }
  },

  // 选择商品类型
  async selectLeixing(e) {
    const now = Date.now();
    const lastSwitchTime = this.data.lastSwitchTime;
    const switchCooldown = this.data.switchCooldown;

    if (now - lastSwitchTime < switchCooldown) {
      wx.showToast({
        title: `操作太快，请${Math.ceil((switchCooldown - (now - lastSwitchTime)) / 1000)}秒后再试`,
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (this.data.isSwitching) return;

    const leixingId = e.currentTarget.dataset.id;
    if (leixingId === this.data.xuanzhongLeixingId) return;

    this.setData({ isSwitching: true, lastSwitchTime: now });
    wx.showLoading({ title: '切换中...' });

    try {
      this.setData({
        xuanzhongLeixingId: leixingId,
        dingdanList: [],
        page: 1,
        hasMore: true,
        xuanzhongBiaoqianId: 0 // 重置标签筛选
      });
      await this.loadDingdanList(true);
      // 🆕 切换类型后加载新标签
      await this.loadBankuaiBiaoqian();
    } catch (error) {
      console.error('切换类型失败:', error);
    } finally {
      this.setData({ isSwitching: false });
      wx.hideLoading();
    }
  },

  // 🆕 选择标签筛选
  async selectBiaoqian(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.xuanzhongBiaoqianId) return;
    this.setData({
      xuanzhongBiaoqianId: id,
      dingdanList: [],
      page: 1,
      hasMore: true
    });
    await this.loadDingdanList(true);
  },

  // 加载订单列表
  async loadDingdanList(isRefresh = false) {
    if (this.data.isLoading || !this.data.xuanzhongLeixingId) return;

    const loadPage = isRefresh ? 1 : this.data.page;
    if (!isRefresh && !this.data.hasMore) return;

    this.setData({
      isLoading: true,
      isLoadingMore: !isRefresh
    });

    try {
      const res = await request({
        url: '/dingdan/ddhq',
        method: 'POST',
        data: {
          leixing_id: this.data.xuanzhongLeixingId,
          page: loadPage,
          page_size: this.data.pageSize,
          // 🆕 传递标签筛选参数（0时不传）
          biaoqian_id: this.data.xuanzhongBiaoqianId || undefined
        }
      });

      this.setData({
        isLoading: false,
        isLoadingMore: false,
        scrollViewRefreshing: false
      });

      if (res.data.code === 200 || res.data.code === 0) {
        const newList = res.data.data.list || [];
        const hasMore = res.data.data.has_more || false;

        // 🆕 处理每条订单，增加 hasRequiredMember 字段
        const processedList = newList.map(item => this.processDingdanItem(item));
        const updatedList = isRefresh ? processedList : [...this.data.dingdanList, ...processedList];
        updatedList.sort((a, b) => (b.creat_time || '').localeCompare(a.creat_time || ''));

        this.setData({
          dingdanList: updatedList,
          page: loadPage,
          hasMore: hasMore
        });

        if (isRefresh) {
          this.setData({ lastRefreshTime: Date.now() });
        }
      } else {
        wx.showToast({ title: res.data.msg || '加载失败', icon: 'none' });
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      this.setData({
        isLoading: false,
        isLoadingMore: false,
        scrollViewRefreshing: false
      });
      wx.showToast({ title: '网络请求失败', icon: 'none' });
    }
  },

  // 处理单条订单数据（包含标签、会员判断）
  processDingdanItem(item) {
    const ossUrl = app.globalData.ossImageUrl || '';
    let fullTupianUrl = '';

    if (item.tupian) {
      fullTupianUrl = !item.tupian.startsWith('http') ? ossUrl + item.tupian : item.tupian;
    } else {
      const leixing = this.data.shangpinleixing.find(l => l.id === item.leixing_id);
      fullTupianUrl = leixing ? leixing.full_tupian_url : '/images/default-order.png';
    }

    const isZhiding = item.zhuangtai === 7;

    let zhidingAvatar = '';
    if (item.zhiding_avatar) {
      zhidingAvatar = !item.zhiding_avatar.startsWith('http')
        ? ossUrl + item.zhiding_avatar
        : item.zhiding_avatar;
    }
    const zhidingNicheng = item.zhiding_nicheng || '';

    // 🆕 判断用户是否有订单所需的会员（仅当订单要求会员类型且存在huiyuan_id）
    let hasRequiredMember = true;
    if (item.yaoqiuleixing == 1 && item.huiyuan_id) {
      const userHasIt = this.data.huiyuanList.some(h => h.huiyuanid == item.huiyuan_id);
      hasRequiredMember = userHasIt;
    }

    return {
      ...item,
      full_tupian_url: fullTupianUrl,
      isZhiding: isZhiding,
      isPingtai: item.pingtai == 1,
      isShangjia: item.pingtai == 2,
      zhiding_avatar_full: zhidingAvatar,
      zhiding_nicheng: zhidingNicheng,
      // 🆕 三层标签（后端返回，直接保留）
      xuqiu_biaoqian: item.xuqiu_biaoqian || [],
      dashou_biaoqian: item.dashou_biaoqian || [],
      shangjia_biaoqian: item.shangjia_biaoqian || [],
      // 🆕 是否有查看价格的权限
      hasRequiredMember: hasRequiredMember,
    };
  },

  // 跳转到充值页面（原封不动）
  goToChongzhiPage(failureType, huiyuanId = null, requiredYajin = 0) {
    let url = '/pages/fighter-recharge/fighter-recharge';
    let params = {};

    switch (failureType) {
      case 'huiyuan':
        params = { needScroll: '0', scrollTo: 'member' };
        break;
      case 'yajin':
        params = { needScroll: '1', scrollTo: 'bottom', requiredYajin: requiredYajin };
        break;
      case 'jifen':
        params = { needScroll: '1', scrollTo: 'bottom' };
        break;
    }

    if (huiyuanId) params.huiyuanId = huiyuanId;

    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');

    wx.navigateTo({
      url: `${url}?${queryString}`,
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({ title: '跳转失败，请稍后重试', icon: 'none' });
      }
    });
  },

  // 抢单按钮（原封不动）
  async onQiangdanTap(e) {
    const dingdanItem = e.currentTarget.dataset.item;
    if (!dingdanItem) return;

    // 校验1: 打手身份
    if (!this.data.dashoustatus || this.data.dashoustatus != 1) {
      wx.showToast({ title: '请先开启接单员身份', icon: 'none' });
      return;
    }
    // 校验2: 账号状态
    if (this.data.zhuanghaoStatus != 1) {
      wx.showToast({ title: '账号异常，无法接单', icon: 'none' });
      return;
    }
    // 校验3: 接单员接单状态
    if (this.data.dashouzhuangtai != 1) {
      wx.showToast({ title: '您有订单正在接待中', icon: 'none' });
      return;
    }
    // 校验4: 指定订单
    if (dingdanItem.isZhiding) {
      if (!this.data.uid || this.data.uid != dingdanItem.zhiding_uid) {
        wx.showToast({ title: '此订单为指定单', icon: 'none' });
        return;
      }
    }
    // 校验5: 会员要求
    if (dingdanItem.yaoqiuleixing == 1) {
      const hasHuiyuan = this.data.huiyuanList.some(h => h.huiyuanid == dingdanItem.huiyuan_id);
      if (!hasHuiyuan) {
        wx.showToast({
          title: '未开通对应会员，无法抢单',
          icon: 'none',
          duration: 2000
        });
        setTimeout(() => {
          this.goToChongzhiPage('huiyuan', dingdanItem.huiyuan_id);
        }, 500);
        return;
      }
    }
    // 校验6: 押金要求
    if (dingdanItem.yaoqiuleixing == 2) {
      if (this.data.yajin < dingdanItem.yajin) {
        wx.showToast({
          title: `押金不足，需${dingdanItem.yajin}`,
          icon: 'none',
          duration: 2000
        });
        setTimeout(() => {
          this.goToChongzhiPage('yajin', null, dingdanItem.yajin);
        }, 500);
        return;
      }
    }
    // 校验7: 积分要求
    if (this.data.jifen < 5) {
      wx.showToast({
        title: '积分不足，至少需要5积分',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        this.goToChongzhiPage('jifen');
      }, 500);
      return;
    }

    // 确认框
    const that = this;
    wx.showModal({
      title: '确认抢单',
      content: `确定要抢此订单吗？${dingdanItem.isZhiding ? '(指定订单)' : ''}`,
      success: async function (res) {
        if (res.confirm) {
          wx.showLoading({ title: '抢单中...', mask: true });
          try {
            const qiangdanRes = await request({
              url: '/dingdan/qiangdan',
              method: 'POST',
              data: { dingdan_id: dingdanItem.dingdan_id }
            });
            wx.hideLoading();

            if (qiangdanRes.data.code === 200 || qiangdanRes.data.code === 0) {
              that.showQiangdanSuccessEffect();
              if (app.globalData) {
                app.globalData.dashouzhuangtai = 0;
                that.setData({ dashouzhuangtai: 0 });
              }
              const newList = that.data.dingdanList.filter(
                item => item.dingdan_id !== dingdanItem.dingdan_id
              );
              that.setData({ dingdanList: newList });
            } else {
              wx.showToast({
                title: qiangdanRes.data.msg || '抢单失败',
                icon: 'none'
              });
            }
          } catch (error) {
            wx.hideLoading();
            console.error('抢单请求失败:', error);
            wx.showToast({ title: '网络错误，抢单失败', icon: 'none' });
          }
        }
      }
    });
  },

  showQiangdanSuccessEffect() {
    wx.showToast({ title: '抢单成功！', icon: 'success', duration: 2000 });
  },

  onViewDetail(e) {
    const { type, content } = e.currentTarget.dataset;
    wx.showModal({
      title: type === 'jieshao' ? '订单介绍' : '订单备注',
      content: content,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  onReachBottom() {
    const now = Date.now();
    const lastTime = this.data.lastRefreshTime;
    const cooldown = this.data.refreshCooldown;

    if (now - lastTime < cooldown) {
      wx.showToast({
        title: `操作太快，请${Math.ceil((cooldown - (now - lastTime)) / 1000)}秒后再试`,
        icon: 'none',
        duration: 1500
      });
      return;
    }

    if (this.data.isLoading || this.data.isLoadingMore) return;

    if (this.data.hasMore && !this.data.isLoading && this.data.xuanzhongLeixingId) {
      this.setData({ page: this.data.page + 1 });
      this.loadDingdanList(false);
    }
  },

  onPullDownRefresh() {
    const now = Date.now();
    const lastTime = this.data.lastRefreshTime;
    const cooldown = this.data.refreshCooldown;

    if (now - lastTime < cooldown) {
      this.setData({ scrollViewRefreshing: false });
      wx.showToast({
        title: `操作太快，请${Math.ceil((cooldown - (now - lastTime)) / 1000)}秒后再试`,
        icon: 'none',
        duration: 1500
      });
      return;
    }

    if (this.data.isLoading) {
      this.setData({ scrollViewRefreshing: false });
      return;
    }

    this.setData({
      scrollViewRefreshing: true,
      lastRefreshTime: now,
      page: 1,
      hasMore: true
    });

    if (this.data.xuanzhongLeixingId) {
      this.refreshDashouProfileSilent();
      this.loadDingdanList(true);
    } else {
      this.setData({ scrollViewRefreshing: false });
    }
  }
});