import request from '../../utils/request';

const app = getApp();

function mapIdentityForApi() {
  const role = app.globalData.currentRole || wx.getStorageSync('currentRole') || 'normal';
  if (role === 'dashou') return 'dashou';
  if (role === 'shangjia') return 'shangjia';
  return 'normal';
}

Component({
  properties: {
    visible: { type: Boolean, value: false },
    groupId: { type: String, value: '' },
    orderId: { type: String, value: '' },
  },

  data: {
    keyword: '',
    loading: false,
    orders: [],
    filteredOrders: [],
  },

  observers: {
    visible(v) {
      if (v) {
        this.setData({ keyword: '' });
        this.loadOrders('');
      }
    },
  },

  methods: {
    close() {
      this.triggerEvent('close');
    },

    onSearchInput(e) {
      const keyword = (e.detail.value || '').trim();
      this.setData({ keyword });
      if (this._searchTimer) clearTimeout(this._searchTimer);
      this._searchTimer = setTimeout(() => {
        this.loadOrders(keyword);
      }, 350);
    },

    async loadOrders(keyword) {
      const { groupId, orderId } = this.properties;
      if (!groupId && !orderId) return;

      this.setData({ loading: true });
      try {
        const res = await request({
          url: '/dingdan/ltpddd',
          method: 'POST',
          data: {
            groupId,
            dingdan_id: orderId,
            keyword: keyword || '',
            identityType: mapIdentityForApi(),
          },
        });
        const body = res?.data || {};
        const list = body.data?.list || [];
        this.setData({
          orders: list,
          filteredOrders: list,
          loading: false,
        });
      } catch (e) {
        console.warn('加载历史订单失败', e);
        this.setData({ loading: false, orders: [], filteredOrders: [] });
        wx.showToast({ title: '加载订单失败', icon: 'none' });
      }
    },

    onSelectOrder(e) {
      const index = e.currentTarget.dataset.index;
      const order = this.data.filteredOrders[index];
      if (!order) return;
      this.triggerEvent('send', { order });
      this.close();
    },
  },
});
