const { db } = require('./config');

class BookInfoService {
  /**
   * 创建项目详细信息
   * @param {Object} bookInfoData - 项目详细信息数据
   * @returns {Promise<number>} - 返回新创建的详细信息ID
   */
  async createBookInfo(bookInfoData) {
    try {
      const now = new Date().toISOString();
      
      // 如果subtitle_segments是对象，转换为JSON字符串
      let subtitleSegments = bookInfoData.subtitle_segments;
      if (subtitleSegments && typeof subtitleSegments === 'object') {
        subtitleSegments = JSON.stringify(subtitleSegments);
      }
      
      // 如果merged_from是数组，转换为JSON字符串
      let mergedFrom = bookInfoData.merged_from;
      if (mergedFrom && Array.isArray(mergedFrom)) {
        mergedFrom = JSON.stringify(mergedFrom);
      }
      
      const bookInfo = {
        book_id: bookInfoData.book_id,
        subtitle_content: bookInfoData.subtitle_content || null,
        subtitle_segments: subtitleSegments || null,
        audio_path: bookInfoData.audio_path || null,
        image_path: bookInfoData.image_path || null,
        description: bookInfoData.description || null,
        video_path: bookInfoData.video_path || null,
        is_merged: bookInfoData.is_merged || false,
        merged_from: mergedFrom || null,
        created_at: now,
        updated_at: now
      };
      
      // 插入数据并返回ID
      const [id] = await db('book_info').insert(bookInfo);
      return id;
    } catch (error) {
      console.error('创建项目详细信息失败:', error);
      throw error;
    }
  }

  /**
   * 根据项目ID获取详细信息
   * @param {number} bookId - 项目ID
   * @returns {Promise<Object>} - 返回项目详细信息
   */
  async getBookInfoByBookId(bookId) {
    try {
      const segments = await db('book_info').where({ book_id: bookId }).orderBy('id', 'asc');
      
      // 处理每个分镜的数据
      return segments.map(segment => {
        // 如果subtitle_segments是JSON字符串，解析为对象
        if (segment.subtitle_segments && typeof segment.subtitle_segments === 'string') {
          try {
            segment.subtitle_segments = JSON.parse(segment.subtitle_segments);
          } catch (e) {
            console.error('解析subtitle_segments失败:', e);
          }
        }
        
        // 如果merged_from是JSON字符串，解析为数组
        if (segment.merged_from && typeof segment.merged_from === 'string') {
          try {
            segment.merged_from = JSON.parse(segment.merged_from);
          } catch (e) {
            console.error('解析merged_from失败:', e);
          }
        }
        
        return segment;
      });
    } catch (error) {
      console.error(`获取项目详细信息(BookID: ${bookId})失败:`, error);
      throw error;
    }
  }

  /**
   * 更新项目详细信息
   * @param {number} id - 分镜ID
   * @param {Object} bookInfoData - 更新的项目详细信息数据
   * @returns {Promise<boolean>} - 返回是否更新成功
   */
  async updateBookInfo(id, bookInfoData) {
    try {
      console.log(`更新分镜信息: id=${id}, data=`, bookInfoData);
      
      // 如果subtitle_segments是对象，转换为JSON字符串
      let updateData = { ...bookInfoData };
      
      // 确保包含id字段
      updateData.id = id;
      
      if (updateData.subtitle_segments && typeof updateData.subtitle_segments === 'object') {
        updateData.subtitle_segments = JSON.stringify(updateData.subtitle_segments);
      }
      
      // 如果merged_from是数组，转换为JSON字符串
      if (updateData.merged_from && Array.isArray(updateData.merged_from)) {
        updateData.merged_from = JSON.stringify(updateData.merged_from);
      }
      
      updateData.updated_at = new Date().toISOString();
      
      await db('book_info').where({ id }).update(updateData);
      console.log(`分镜更新成功: id=${id}`);
      return true;
    } catch (error) {
      console.error(`更新项目详细信息(ID: ${id})失败:`, error);
      throw error;
    }
  }

  /**
   * 删除项目详细信息
   * @param {number} id - 分镜ID
   * @returns {Promise<boolean>} - 返回是否删除成功
   */
  async deleteBookInfo(id) {
    try {
      await db('book_info').where({ id }).delete();
      return true;
    } catch (error) {
      console.error(`删除项目详细信息(ID: ${id})失败:`, error);
      throw error;
    }
  }
  
  /**
   * 合并分镜
   * @param {number} bookId - 项目ID
   * @param {number[]} segmentIds - 要合并的分镜ID数组
   * @returns {Promise<number>} - 返回新创建的合并分镜ID
   */
  async mergeSegments(bookId, segmentIds) {
    try {
      // 查询要合并的分镜
      const segments = await db('book_info')
        .whereIn('id', segmentIds)
        .where('book_id', bookId)
        .orderBy('id', 'asc');
      
      if (segments.length < 2) {
        throw new Error('至少需要两个分镜才能合并');
      }
      
      // 提取分镜的文本内容和时间信息
      const firstSegment = segments[0];
      const lastSegment = segments[segments.length - 1];
      
      // 合并文本内容
      const mergedText = segments.map(segment => {
        // 尝试解析subtitle_segments
        let subtitleData = segment.subtitle_segments;
        if (typeof subtitleData === 'string') {
          try {
            subtitleData = JSON.parse(subtitleData);
          } catch (e) {
            console.error('解析subtitle_segments失败:', e);
            subtitleData = null;
          }
        }
        
        return segment.text || (subtitleData && subtitleData.text ? subtitleData.text : '');
      }).join('\n\n');
      
      // 创建合并后的分镜
      const mergedSegment = {
        book_id: bookId,
        text: mergedText,
        start_time: firstSegment.start_time,
        end_time: lastSegment.end_time,
        duration: this._calculateDuration(firstSegment.start_time, lastSegment.end_time),
        is_merged: true,
        merged_from: JSON.stringify(segmentIds),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      // 插入合并后的分镜
      const [id] = await db('book_info').insert(mergedSegment);
      
      return id;
    } catch (error) {
      console.error(`合并分镜失败:`, error);
      throw error;
    }
  }
  
  /**
   * 拆分分镜
   * @param {number} segmentId - 要拆分的分镜ID
   * @param {Object[]} newSegments - 新分镜数据数组
   * @returns {Promise<number[]>} - 返回新创建的分镜ID数组
   */
  async splitSegment(segmentId, newSegments) {
    try {
      // 查询要拆分的分镜
      const segment = await db('book_info').where({ id: segmentId }).first();
      
      if (!segment) {
        throw new Error(`分镜(ID: ${segmentId})不存在`);
      }
      
      // 创建新分镜
      const newSegmentIds = [];
      for (const newSegment of newSegments) {
        const segmentData = {
          book_id: segment.book_id,
          text: newSegment.text,
          start_time: newSegment.start_time,
          end_time: newSegment.end_time,
          duration: this._calculateDuration(newSegment.start_time, newSegment.end_time),
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        };
        
        const [id] = await db('book_info').insert(segmentData);
        newSegmentIds.push(id);
      }
      
      // 删除原分镜
      await this.deleteBookInfo(segmentId);
      
      return newSegmentIds;
    } catch (error) {
      console.error(`拆分分镜失败:`, error);
      throw error;
    }
  }
  
  /**
   * 计算两个时间点之间的持续时间（秒）
   * @param {string} startTime - 开始时间 (HH:MM:SS,mmm)
   * @param {string} endTime - 结束时间 (HH:MM:SS,mmm)
   * @returns {number} - 持续时间（秒）
   * @private
   */
  _calculateDuration(startTime, endTime) {
    const parseTime = (time) => {
      if (!time) return 0;
      const [hours, minutes, seconds] = time.replace(',', '.').split(':').map(parseFloat);
      return hours * 3600 + minutes * 60 + seconds;
    };
    
    const startSeconds = parseTime(startTime);
    const endSeconds = parseTime(endTime);
    
    return (endSeconds - startSeconds).toFixed(2);
  }
}

module.exports = new BookInfoService(); 