// pages/sjdingdan/sjdingdan.js
const app = getApp();
import request from '../../utils/request.js';

Page({
  data: {
    // 商品类型（和打手端用同一个接口）
    shangpinleixing: [],
    xuanzhongLeixingId: null,

    // 搜索关键字（模糊搜索）
    searchKeyword: '',

    // 状态列表（含全部）
    statusList: [
      { name: '全部', key: 'all', zhuangtaiList: [1, 2, 3, 4, 5, 6, 7, 8], color: '#333333' },
      { name: '进行中', key: 'jinxingzhong', zhuangtaiList: [2], color: '#2196F3' },
      { name: '退款中', key: 'tuikuanzhong', zhuangtaiList: [4], color: '#FF9800' },
      { name: '已退款', key: 'yituikuan', zhuangtaiList: [5], color: '#9E9E9E' },
      { name: '退款失败', key: 'tuikuanshibai', zhuangtaiList: [6], color: '#F44336' },
      { name: '已完成', key: 'yiwancheng', zhuangtaiList: [3], color: '#4CAF50' },
      { name: '结算中', key: 'jiesuanzhong', zhuangtaiList: [8], color: '#FF5722' }
    ],
    currentStatusKey: 'all',

    // 每个状态独立的数据集
    sjDingdanShuju: {
      all: { list: [], page: 1, hasMore: true, isLoading: false },
      jinxingzhong: { list: [], page: 1, hasMore: true, isLoading: false },
      tuikuanzhong: { list: [], page: 1, hasMore: true, isLoading: false },
      yituikuan: { list: [], page: 1, hasMore: true, isLoading: false },
      tuikuanshibai: { list: [], page: 1, hasMore: true, isLoading: false },
      yiwancheng: { list: [], page: 1, hasMore: true, isLoading: false },
      jiesuanzhong: { list: [], page: 1, hasMore: true, isLoading: false }
    },

    currentList: [],
    hasMore: true,
    isLoading: false,
    isLoadingMore: false,
    scrollViewRefreshing: false,
    defaultImg: '/images/default-order.png',
    ossImageUrl: app.globalData.ossImageUrl || '',

    // 待结算数量
    pendingCount: 0,
  },

  onLoad() {
    wx.setNavigationBarTitle({ title: '我的派单' });
    this.loadShangpinLeixing();
    this.registerNotificationComponent();
  },

  onShow() {
    this.registerNotificationComponent();
    this.loadPendingCount();
    // 如果已加载过商品类型，刷新当前状态的订单
    if (this.data.currentStatusKey && this.data.xuanzhongLeixingId) {
      this.loadCurrentStatusOrders(true);
    }
  },

  // 注册全局通知组件
  registerNotificationComponent() {
    const notificationComp = this.selectComponent('#global-notification');
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      };
    }
  },

  // 🆕 加载商品类型（和打手端用同一个接口 /dingdan/dsqdhqddlx）
  async loadShangpinLeixing() {
    try {
      const res = await request({
        url: '/dingdan/dsqdhqddlx',
        method: 'POST',
        header: { 'content-type': 'application/json' }
      });
      if (res.data && (res.data.code === 200 || res.data.code === 0)) {
        let list = res.data.data.list || res.data.data || [];
        if (!Array.isArray(list)) list = [];
        const oss = this.data.ossImageUrl;
        // 拼接图片完整URL
        const processed = list.map(item => ({
          ...item,
          full_tupian_url: item.tupian_url && !item.tupian_url.startsWith('http')
            ? oss + item.tupian_url
            : (item.tupian_url || '/images/default-type.png')
        }));
        this.setData({
          shangpinleixing: processed,
          xuanzhongLeixingId: processed[0]?.id || null
        });
        // 初始加载全部状态订单
        this.loadCurrentStatusOrders(true);
      }
    } catch (e) {
      console.error('加载商品类型失败', e);
    }
  },

  // 选择商品类型
  selectLeixing(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.xuanzhongLeixingId) return;
    this.setData({ xuanzhongLeixingId: id });
    this.resetCurrentStatusData();
    this.loadCurrentStatusOrders(true);
  },

  // 搜索输入（防抖）
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
    if (this._searchTimer) clearTimeout(this._searchTimer);
    this._searchTimer = setTimeout(() => {
      this.onSearchConfirm();
    }, 500);
  },

  // 搜索确认
  onSearchConfirm() {
    this.resetCurrentStatusData();
    this.loadCurrentStatusOrders(true);
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.resetCurrentStatusData();
    this.loadCurrentStatusOrders(true);
  },

  // 切换状态Tab
  switchStatus(e) {
    const key = e.currentTarget.dataset.key;
    if (key === this.data.currentStatusKey) return;
    this.setData({ currentStatusKey: key });
    const tabData = this.data.sjDingdanShuju[key];
    // 如果该状态没有数据，则加载；否则只刷新视图
    if (tabData.list.length === 0 && tabData.hasMore && !tabData.isLoading) {
      this.loadCurrentStatusOrders(true);
    } else {
      this.refreshCurrentListView();
    }
  },

  // 🆕 加载订单（核心方法，接口固定用商家订单接口 /dingdan/sjdingdanhq）
  async loadCurrentStatusOrders(isRefresh = false) {
    const key = this.data.currentStatusKey;
    const tabData = this.data.sjDingdanShuju[key];
    if (tabData.isLoading) return;
    const page = isRefresh ? 1 : tabData.page;

    this.setData({
      [`sjDingdanShuju.${key}.isLoading`]: true,
      isLoading: true,
      isLoadingMore: !isRefresh
    });

    try {
      const statusItem = this.data.statusList.find(s => s.key === key);
      const zhuangtaiList = statusItem.zhuangtaiList;

      // 构建请求参数
      const params = {
        zhuangtai_list: zhuangtaiList,
        page: page,
        page_size: 5,
        leixing_id: this.data.xuanzhongLeixingId,  // 🆕 商品类型筛选
        keyword: this.data.searchKeyword || undefined  // 🆕 模糊搜索
      };

      const res = await request({
        url: '/dingdan/sjdingdanhq',  // 商家订单接口（和原来一样）
        method: 'POST',
        data: params,
        header: { 'content-type': 'application/json' }
      });

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

        // 处理数据：拼接图片、转换状态中文
        const processed = newList.map(item => ({
          ...item,
          zhuangtaiZh: this.getZhuangtaiZh(item.zhuangtai),
          zhuangtaiColor: statusItem.color,
          // 如果有商品图片则用商品图片，否则用默认图
          tupian: item.tupian
            ? (item.tupian.startsWith('http') ? item.tupian : this.data.ossImageUrl + item.tupian)
            : this.data.defaultImg
        }));

        const currentList = this.data.sjDingdanShuju[key].list;
        const updatedList = isRefresh ? processed : [...currentList, ...processed];

        this.setData({
          [`sjDingdanShuju.${key}.list`]: updatedList,
          [`sjDingdanShuju.${key}.page`]: page,
          [`sjDingdanShuju.${key}.hasMore`]: hasMore,
          [`sjDingdanShuju.${key}.isLoading`]: false,
          isLoading: false,
          isLoadingMore: false,
          scrollViewRefreshing: false
        });
        this.refreshCurrentListView();
      } else {
        throw new Error(res.data.msg || '加载失败');
      }
    } catch (err) {
      console.error('加载订单失败', err);
      wx.showToast({ title: err.message || '加载失败', icon: 'none' });
      this.setData({
        [`sjDingdanShuju.${key}.isLoading`]: false,
        isLoading: false,
        isLoadingMore: false,
        scrollViewRefreshing: false
      });
      this.refreshCurrentListView();
    }
  },

  // 刷新当前视图
  refreshCurrentListView() {
    const key = this.data.currentStatusKey;
    const tabData = this.data.sjDingdanShuju[key];
    this.setData({
      currentList: tabData.list,
      hasMore: tabData.hasMore,
      isLoading: tabData.isLoading
    });
  },

  // 重置当前状态数据
  resetCurrentStatusData() {
    const key = this.data.currentStatusKey;
    this.setData({
      [`sjDingdanShuju.${key}.list`]: [],
      [`sjDingdanShuju.${key}.page`]: 1,
      [`sjDingdanShuju.${key}.hasMore`]: true,
      [`sjDingdanShuju.${key}.isLoading`]: false
    });
    this.refreshCurrentListView();
  },

  // 🆕 加载待结算数量
  async loadPendingCount() {
    try {
      const res = await request({
        url: '/dingdan/sjdingdanhq',
        method: 'POST',
        data: {
          zhuangtai_list: [8],
          page: 1,
          page_size: 1
        }
      });
      if (res && res.data.code === 0) {
        this.setData({ pendingCount: res.data.data.pending_count || 0 });
      }
    } catch (error) {
      console.error('加载待结算数量失败:', error);
    }
  },

  // 下拉刷新（由 scroll-view 触发）
  onPullDownRefresh() {
    if (this.data.isLoading) {
      this.setData({ scrollViewRefreshing: false });
      return;
    }
    this.setData({ scrollViewRefreshing: true });
    this.resetCurrentStatusData();
    this.loadCurrentStatusOrders(true);
  },

  // 上拉加载更多（由 scroll-view 触发）
  onReachBottom() {
    const key = this.data.currentStatusKey;
    const tabData = this.data.sjDingdanShuju[key];
    if (tabData.isLoading || !tabData.hasMore) return;
    this.setData({ [`sjDingdanShuju.${key}.page`]: tabData.page + 1 });
    this.loadCurrentStatusOrders(false);
  },

  // 🆕 手动点击"加载更多"按钮
  onLoadMoreTap() {
    const key = this.data.currentStatusKey;
    const tabData = this.data.sjDingdanShuju[key];
    if (tabData.isLoading || !tabData.hasMore) return;
    this.setData({ [`sjDingdanShuju.${key}.page`]: tabData.page + 1 });
    this.loadCurrentStatusOrders(false);
  },

  // 状态码转中文
  getZhuangtaiZh(zhuangtai) {
    const map = {
      1: '已下单', 2: '进行中', 3: '已完成',
      4: '退款中', 5: '已退款', 6: '退款失败',
      7: '指定中', 8: '结算中'
    };
    return map[zhuangtai] || '未知状态';
  },

  // 跳转订单详情
  goToSjDingdanXiangqing(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) return;
    const dataStr = encodeURIComponent(JSON.stringify(item));
    wx.navigateTo({
      url: `/pages/sjddxq/sjddxq?dingdanData=${dataStr}`
    });
  },

  // 图片加载失败
  onImageError() {}
});