// pages/jiedanchi/jiedanchi.js
const app = getApp();
import request from '../../utils/request.js';
import PopupService from '../../services/popupService.js';

Page({
  data: {
    // 1. 商品类型相关
    shangpinleixing: [], // 商品类型列表 {id, jieshao, tupian_url}
    xuanzhongLeixingId: null, // 当前选中的类型ID

    // 2. 订单列表与分页相关
    dingdanList: [], // 当前展示的订单列表
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,

    // 3. 全局状态字段
    dashoustatus: null,
    zhuanghaoStatus: null,     // 注意变量名：zhuanghaoStatus
    dashouzhuangtai: null,
    uid: null,
    huiyuanList: [], // clumber 列表
    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. 授权状态控制
    showUnauthorized: false,
    unauthorizedMsg: '您尚未开启此功能',
  },

  async onLoad(options) {
    this.loadGlobalStatus();
    this.checkAuthorization();
    
  },
  // 🆕 页面隐藏时清理弹窗视图
  onHide: function () {
    const popupComp = this.selectComponent('#popupNotice');
    if (popupComp && popupComp.cleanup) {
        popupComp.cleanup();
    }
},
  
  onShow() {
    this.registerNotificationComponent();
    this.loadGlobalStatus();
    this.checkAuthorization();
  },

  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;
    // 从缓存读取，确保与抢单时使用的数据源一致
    const dashoustatusCache = wx.getStorageSync('dashoustatus');
    const dashoustatus = dashoustatusCache !== '' ? dashoustatusCache : null;
    
    // 从 globalData 或缓存获取 zhuanghaoStatus（注意字段名可能有差异）
    let zhuanghaoStatus = globalData.zhanghaoStatus;
    if (zhuanghaoStatus === undefined || zhuanghaoStatus === null) {
      zhuanghaoStatus = wx.getStorageSync('zhanghaoStatus');
    }
    
    this.setData({
      dashoustatus: dashoustatus,
      zhuanghaoStatus: zhuanghaoStatus,
      dashouzhuangtai: globalData.dashouzhuangtai,
      uid: wx.getStorageSync('uid'),
      huiyuanList: globalData.clumber || [],
      yajin: globalData.yajin || 0,
      jifen: globalData.jinfen || 0
    });

    // 打印当前值，方便调试
    //console.log('loadGlobalStatus -> dashoustatus:', dashoustatus, 'zhuanghaoStatus:', zhuanghaoStatus);
  },

  checkAuthorization() {
    const { dashoustatus, zhuanghaoStatus } = this.data;
    //console.log('checkAuthorization -> dashoustatus:', dashoustatus, 'zhuanghaoStatus:', zhuanghaoStatus);
    
    // 完全复制抢单时的判断逻辑
    const isDashouValid = (dashoustatus && dashoustatus == 1) || false;  // 存在且等于1
    const isZhuanghaoValid = (zhuanghaoStatus == 1);  // 宽松比较，null/undefined/0 均视为 false
    
    const isAuthorized = isDashouValid && isZhuanghaoValid;

    if (!isAuthorized) {
      this.setData({ showUnauthorized: true });
      let msg = '';
      if (!isDashouValid) msg = '您尚未开启身份';
      //else if (!isZhuanghaoValid) msg = '您的账号状态异常';
      this.setData({ unauthorizedMsg: msg || '无法使用抢单功能' });
    } else {
      this.setData({ showUnauthorized: false });
      if (!this.data.shangpinleixing.length) {
        this.loadShangpinLeixing();
      } else if (this.data.xuanzhongLeixingId) {
        this.loadDingdanList(true);
      }
      PopupService.checkAndShow(this, 'jiedanchi');
    }
  },

  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);
        }
      } else {
        wx.showToast({ title: res.data?.msg || '加载商品类型失败', icon: 'none', duration: 2000 });
      }
    } catch (error) {
      console.error('加载商品类型失败:', error);
      wx.showToast({ title: '网络错误，加载失败', icon: 'none', duration: 2000 });
    } finally {
      wx.hideLoading();
    }
  },

  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 selectLeixing(e) {
    const now = Date.now();
    if (now - this.data.lastSwitchTime < this.data.switchCooldown) {
      wx.showToast({
        title: `操作太快，请${Math.ceil((this.data.switchCooldown - (now - this.data.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
      });
      await this.loadDingdanList(true);
    } catch (error) {
      console.error('切换类型失败:', error);
    } finally {
      this.setData({ isSwitching: false });
      wx.hideLoading();
    }
  },

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

      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;

        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 || '';

    return {
      ...item,
      full_tupian_url: fullTupianUrl,
      isZhiding: isZhiding,
      isPingtai: item.pingtai == 1,
      isShangjia: item.pingtai == 2,
      zhiding_avatar_full: zhidingAvatar,
      zhiding_nicheng: zhidingNicheng
    };
  },

  goToChongzhiPage(failureType, huiyuanId = null, requiredYajin = 0) {
    let url = '/pages/dashouchongzhi/dashouchongzhi';
    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('&');
    const fullUrl = `${url}?${queryString}`;
    wx.navigateTo({
      url: fullUrl,
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({ title: '跳转失败，请稍后重试', icon: 'none' });
      }
    });
  },

  async onQiangdanTap(e) {
    const dingdanItem = e.currentTarget.dataset.item;
    if (!dingdanItem) return;

    if (!this.data.dashoustatus || this.data.dashoustatus != 1) {
      wx.showToast({ title: '请先开启打手身份', icon: 'none' });
      return;
    }
    if (this.data.zhuanghaoStatus != 1) {
      wx.showToast({ title: '账号异常，无法接单', icon: 'none' });
      return;
    }
    if (this.data.dashouzhuangtai != 1) {
      wx.showToast({ title: '您有订单正在接待中', icon: 'none' });
      return;
    }
    if (dingdanItem.isZhiding) {
      if (!this.data.uid || this.data.uid != dingdanItem.zhiding_uid) {
        wx.showToast({ title: '此订单为指定单', icon: 'none' });
        return;
      }
    }
    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;
      }
    }
    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;
      }
    }
    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();
    if (now - this.data.lastRefreshTime < this.data.refreshCooldown) {
      wx.showToast({
        title: `操作太快，请${Math.ceil((this.data.refreshCooldown - (now - this.data.lastRefreshTime)) / 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();
    if (now - this.data.lastRefreshTime < this.data.refreshCooldown) {
      this.setData({ scrollViewRefreshing: false });
      wx.showToast({
        title: `操作太快，请${Math.ceil((this.data.refreshCooldown - (now - this.data.lastRefreshTime)) / 1000)}秒后再试`,
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (this.data.isLoading) {
      this.setData({ scrollViewRefreshing: false });
      return;
    }
    this.setData({ 
      scrollViewRefreshing: true,
      lastRefreshTime: now
    });
    if (this.data.xuanzhongLeixingId) {
      this.setData({ page: 1, hasMore: true });
      this.loadDingdanList(true);
    } else {
      this.setData({ scrollViewRefreshing: false });
    }
  },

  goToDashouRegister() {
    wx.navigateTo({
      url: '/pages/dashouduan/dashouduan'
    });
  }
});