import { useState, useCallback } from 'react';
import { bitable } from '@lark-base-open/js-sdk';
import { RecordDetail, SelectedLabels } from '../types';
import { TABLE_CONFIG } from '../constants/config';
import { buildFieldNameToIdMap, extractLabelsFromRecord } from '../utils/dataUtils';
import { executePricingQuery, executeSecondaryProcessQuery, executePricingDetailsQuery } from '../services/apiService';

export const useRecordSelection = () => {
  const [selectedRecords, setSelectedRecords] = useState<string[]>([]);
  const [recordDetails, setRecordDetails] = useState<RecordDetail[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedLabels, setSelectedLabels] = useState<SelectedLabels>({});
  
  const handleSelectRecords = useCallback(async () => {
    setLoading(true);
    // 清空标签选择
    setSelectedLabels({});
    
    try {
      const recordIdList = await bitable.ui.selectRecordIdList(
        TABLE_CONFIG.TABLE_ID,
        TABLE_CONFIG.VIEW_ID
      );
      
      setSelectedRecords(recordIdList);
      
      if (recordIdList.length > 0) {
        const table = await bitable.base.getTable(TABLE_CONFIG.TABLE_ID);
        const [recordPromises, fieldMetaList] = await Promise.all([
          Promise.all(recordIdList.map(recordId => table.getRecordById(recordId))),
          table.getFieldMetaList()
        ]);
        
        const recordValList: RecordDetail[] = recordPromises.map((record, index) => ({
          id: recordIdList[index],
          fields: record.fields
        }));
        
        setRecordDetails(recordValList);
        
        // 提取标签值
        if (recordValList.length > 0) {
          const fieldMap = buildFieldNameToIdMap(fieldMetaList);
          const extractedLabels = extractLabelsFromRecord(recordValList[0], fieldMap);
          
          setSelectedLabels(prev => ({
            ...prev,
            ...extractedLabels
          }));
          
          // 自动执行查询
          await executeAllQueries(recordValList[0]);
        }
      } else {
        setRecordDetails([]);
      }
    } catch (error) {
      console.error('选择记录时出错:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  }, []);
  
  const handleClearRecords = useCallback(() => {
    setSelectedRecords([]);
    setRecordDetails([]);
    setSelectedLabels({});
  }, []);
  
  const executeAllQueries = async (record: RecordDetail) => {
    // 实现查询逻辑
  };
  
  return {
    selectedRecords,
    recordDetails,
    loading,
    selectedLabels,
    setSelectedLabels,
    handleSelectRecords,
    handleClearRecords,
  };
};