const app = getApp();
import { createPage, request } from '../../utils/base-page.js';
import { reconnectForRole } from '../../utils/role-tab-bar.js';
import { getOrderStatusText } from '../../utils/api-helper.js';

Page(createPage({
  data: {
    // 商品类型
    shangpinleixing: [],
    xuanzhongLeixingId: null,

    // 订单类型: normal 普通, peihu 陪护
    orderType: 'normal',

    // 搜索关键字
    searchKeyword: '',

    // 状态列表（增加全部）
    statusList: [
      { name: '全部', key: 'all', zhuangtaiList: [], color: '#333333' },
      { name: '进行中', key: 'jinxingzhong', zhuangtaiList: [2], color: '#2196F3' },
      { name: '退款中', key: 'tuikuanzhong', zhuangtaiList: [4], color: '#9333ea' },
      { 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',

    // 每个状态独立的数据集
    dsDingdanShuju: {
      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 || '',
  },

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

  onShow() {
    this.registerNotificationComponent();
    if (wx.getStorageSync('uid')) {
      reconnectForRole('dashou');
      if (app.startImWhenReady) app.startImWhenReady();
    }
    if (this.data.currentStatusKey && this.data.xuanzhongLeixingId) {
      this.loadCurrentStatusOrders(true);
    }
  },

  // 加载商品类型（图片拼接）
  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;
        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);
  },

  switchOrderType(e) {
    const type = e.currentTarget.dataset.type;
    if (type === this.data.orderType) return;
    this.setData({ orderType: type });
    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);
  },

  switchStatus(e) {
    const key = e.currentTarget.dataset.key;
    if (key === this.data.currentStatusKey) return;
    this.setData({ currentStatusKey: key });
    const tabData = this.data.dsDingdanShuju[key];
    if (tabData.list.length === 0 && tabData.hasMore && !tabData.isLoading) {
      this.loadCurrentStatusOrders(true);
    } else {
      this.refreshCurrentListView();
    }
  },

  // 加载订单（核心）
  async loadCurrentStatusOrders(isRefresh = false) {
    const key = this.data.currentStatusKey;
    const tabData = this.data.dsDingdanShuju[key];
    if (tabData.isLoading) return;
    const page = isRefresh ? 1 : tabData.page;

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

    try {
      const apiUrl = this.data.orderType === 'peihu'
        ? '/dingdan/phddlbhq'
        : '/dingdan/dshqdingdan';

      const statusItem = this.data.statusList.find(s => s.key === key);
      const zhuangtaiList = statusItem.zhuangtaiList.length > 0 ? statusItem.zhuangtaiList : undefined;
      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: apiUrl,
        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;

        // ✅ 图片URL拼接（核心）
        const processed = newList.map(item => ({
          ...item,
          zhuangtaiZh: getOrderStatusText(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.dsDingdanShuju[key].list;
        const updatedList = isRefresh ? processed : [...currentList, ...processed];

        this.setData({
          [`dsDingdanShuju.${key}.list`]: updatedList,
          [`dsDingdanShuju.${key}.page`]: page,
          [`dsDingdanShuju.${key}.hasMore`]: hasMore,
          [`dsDingdanShuju.${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({
        [`dsDingdanShuju.${key}.isLoading`]: false,
        isLoading: false,
        isLoadingMore: false,
        scrollViewRefreshing: false
      });
      this.refreshCurrentListView();
    }
  },

  refreshCurrentListView() {
    const key = this.data.currentStatusKey;
    const tabData = this.data.dsDingdanShuju[key];
    this.setData({
      currentList: tabData.list,
      hasMore: tabData.hasMore,
      isLoading: tabData.isLoading
    });
  },

  resetCurrentStatusData() {
    const key = this.data.currentStatusKey;
    this.setData({
      [`dsDingdanShuju.${key}.list`]: [],
      [`dsDingdanShuju.${key}.page`]: 1,
      [`dsDingdanShuju.${key}.hasMore`]: true,
      [`dsDingdanShuju.${key}.isLoading`]: false
    });
    this.refreshCurrentListView();
  },

  // 下拉刷新（由 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.dsDingdanShuju[key];
    if (tabData.isLoading || !tabData.hasMore) return;
    this.setData({ [`dsDingdanShuju.${key}.page`]: tabData.page + 1 });
    this.loadCurrentStatusOrders(false);
  },

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

  goToDsDingdanXiangqing(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) return;
    const dataStr = encodeURIComponent(JSON.stringify(item));

    if (this.data.orderType === 'peihu') {
      wx.navigateTo({
        url: `/pages/escort-orders/escort-orders?dingdanData=${dataStr}`
      });
    } else {
      wx.navigateTo({
        url: `/pages/fighter-order-detail/fighter-order-detail?dingdanData=${dataStr}`
      });
    }
  },

  onImageError() {}
}))
