const app = getApp<IAppOption>()

Page({
  data: {
    availableModels: [] as string[],
    selectedModels: [] as string[],
    responseData: null as any
  },

  onLoad() {
    this.fetchModels();
  },

  // 1. 获取后端有哪些模型
  fetchModels() {
    wx.showNavigationBarLoading();
    wx.request({
      // 假设你在全局路由配置的是 multi_model_detection/
      url: `${app.globalData.baseUrl}/multi_model_detection/api/models/`, 
      method: 'GET',
      success: (res: any) => {
        wx.hideNavigationBarLoading();
        if (res.data.code === 200) {
          this.setData({ 
            availableModels: res.data.data,
            // 默认全选
            selectedModels: res.data.data 
          });
        }
      }
    });
  },

  // 2. 监听复选框变化
  onModelChange(e: any) {
    this.setData({
      selectedModels: e.detail.value
    });
  },

  // 3. 选择照片并发起并发检测
  chooseImage() {
    if (this.data.selectedModels.length === 0) {
      wx.showToast({ title: '请至少勾选一个模型', icon: 'none' });
      return;
    }

    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ responseData: null }); // 清空旧数据
        this.uploadForMultiDetect(tempFilePath);
      }
    });
  },

  uploadForMultiDetect(filePath: string) {
    wx.showLoading({ title: '多路并发推理中...', mask: true });
    const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo');
    
    // 将数组转成逗号分隔的字符串发给后端
    const modelsStr = this.data.selectedModels.join(',');

    wx.uploadFile({
      url: `${app.globalData.baseUrl}/api/detect/`,
      filePath: filePath,
      name: 'image',
      formData: {
        'user_id': userInfo ? userInfo.user_id : '',
        'models': modelsStr
      },
      success: (res) => {
        wx.hideLoading();
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          this.setData({ responseData: data.data });
          wx.showToast({ title: '联合检测完成', icon: 'success' });
        } else {
          wx.showToast({ title: data.msg || '检测失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error(err);
        wx.showToast({ title: '网络异常', icon: 'none' });
      }
    });
  }
})