/**
 * 项目-模板绑定服务
 * 遵循前端开发规范的服务层设计原则
 */

import { invoke } from '@tauri-apps/api/core';
import {
  ProjectTemplateBinding,
  CreateProjectTemplateBindingRequest,
  UpdateProjectTemplateBindingRequest,
  ProjectTemplateBindingQueryParams,
  ProjectTemplateBindingDetail,
  BatchCreateProjectTemplateBindingRequest,
  BatchDeleteProjectTemplateBindingRequest,
} from '../types/projectTemplateBinding';

export class ProjectTemplateBindingService {
  /**
   * 创建项目-模板绑定
   */
  static async createBinding(request: CreateProjectTemplateBindingRequest): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('create_project_template_binding', { request });
    } catch (error) {
      console.error('创建项目-模板绑定失败:', error);
      throw new Error(`创建绑定失败: ${error}`);
    }
  }

  /**
   * 更新项目-模板绑定
   */
  static async updateBinding(id: string, request: UpdateProjectTemplateBindingRequest): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('update_project_template_binding', { id, request });
    } catch (error) {
      console.error('更新项目-模板绑定失败:', error);
      throw new Error(`更新绑定失败: ${error}`);
    }
  }

  /**
   * 删除项目-模板绑定
   */
  static async deleteBinding(id: string): Promise<void> {
    try {
      await invoke('delete_project_template_binding', { id });
    } catch (error) {
      console.error('删除项目-模板绑定失败:', error);
      throw new Error(`删除绑定失败: ${error}`);
    }
  }

  /**
   * 根据项目ID和模板ID删除绑定
   */
  static async deleteBindingByIds(projectId: string, templateId: string): Promise<void> {
    try {
      await invoke('delete_project_template_binding_by_ids', { 
        project_id: projectId, 
        template_id: templateId 
      });
    } catch (error) {
      console.error('删除项目-模板绑定失败:', error);
      throw new Error(`删除绑定失败: ${error}`);
    }
  }

  /**
   * 获取项目-模板绑定详情
   */
  static async getBinding(id: string): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('get_project_template_binding', { id });
    } catch (error) {
      console.error('获取项目-模板绑定失败:', error);
      throw new Error(`获取绑定失败: ${error}`);
    }
  }

  /**
   * 查询项目-模板绑定列表
   */
  static async listBindings(params: ProjectTemplateBindingQueryParams = {}): Promise<ProjectTemplateBinding[]> {
    try {
      return await invoke('list_project_template_bindings', { params });
    } catch (error) {
      console.error('查询项目-模板绑定列表失败:', error);
      throw new Error(`查询绑定列表失败: ${error}`);
    }
  }

  /**
   * 获取项目的模板列表
   */
  static async getTemplatesByProject(projectId: string): Promise<ProjectTemplateBindingDetail[]> {
    try {
      return await invoke('get_templates_by_project', { projectId });
    } catch (error) {
      console.error('获取项目模板列表失败:', error);
      throw new Error(`获取项目模板列表失败: ${error}`);
    }
  }

  /**
   * 获取模板的项目列表
   */
  static async getProjectsByTemplate(templateId: string): Promise<ProjectTemplateBindingDetail[]> {
    try {
      return await invoke('get_projects_by_template', { templateId });
    } catch (error) {
      console.error('获取模板项目列表失败:', error);
      throw new Error(`获取模板项目列表失败: ${error}`);
    }
  }

  /**
   * 批量创建项目-模板绑定
   */
  static async batchCreateBindings(request: BatchCreateProjectTemplateBindingRequest): Promise<ProjectTemplateBinding[]> {
    try {
      return await invoke('batch_create_project_template_bindings', { request });
    } catch (error) {
      console.error('批量创建项目-模板绑定失败:', error);
      throw new Error(`批量创建绑定失败: ${error}`);
    }
  }

  /**
   * 批量删除项目-模板绑定
   */
  static async batchDeleteBindings(request: BatchDeleteProjectTemplateBindingRequest): Promise<number> {
    try {
      console.log('Service: 发送批量删除请求:', request);
      const result = await invoke<number>('batch_delete_project_template_bindings', { request });
      console.log('Service: 批量删除响应:', result);
      return result;
    } catch (error) {
      console.error('批量删除项目-模板绑定失败:', error);
      throw new Error(`批量删除绑定失败: ${error}`);
    }
  }

  /**
   * 激活项目-模板绑定
   */
  static async activateBinding(id: string): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('activate_project_template_binding', { id });
    } catch (error) {
      console.error('激活项目-模板绑定失败:', error);
      throw new Error(`激活绑定失败: ${error}`);
    }
  }

  /**
   * 停用项目-模板绑定
   */
  static async deactivateBinding(id: string): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('deactivate_project_template_binding', { id });
    } catch (error) {
      console.error('停用项目-模板绑定失败:', error);
      throw new Error(`停用绑定失败: ${error}`);
    }
  }

  /**
   * 获取项目的主要模板绑定
   */
  static async getPrimaryBindingForProject(projectId: string): Promise<ProjectTemplateBinding | null> {
    try {
      return await invoke('get_primary_template_binding_for_project', { project_id: projectId });
    } catch (error) {
      console.error('获取项目主要模板绑定失败:', error);
      throw new Error(`获取主要模板绑定失败: ${error}`);
    }
  }

  /**
   * 设置项目的主要模板
   */
  static async setPrimaryTemplate(projectId: string, templateId: string): Promise<ProjectTemplateBinding> {
    try {
      return await invoke('set_primary_template_for_project', { 
        project_id: projectId, 
        template_id: templateId 
      });
    } catch (error) {
      console.error('设置项目主要模板失败:', error);
      throw new Error(`设置主要模板失败: ${error}`);
    }
  }

  /**
   * 检查项目-模板绑定是否存在
   */
  static async checkBindingExists(projectId: string, templateId: string): Promise<boolean> {
    try {
      return await invoke('check_project_template_binding_exists', { 
        project_id: projectId, 
        template_id: templateId 
      });
    } catch (error) {
      console.error('检查项目-模板绑定是否存在失败:', error);
      throw new Error(`检查绑定是否存在失败: ${error}`);
    }
  }

  /**
   * 获取项目的活跃模板绑定
   */
  static async getActiveBindingsForProject(projectId: string): Promise<ProjectTemplateBindingDetail[]> {
    try {
      const bindings = await this.getTemplatesByProject(projectId);
      return bindings.filter(detail => 
        detail.binding.is_active && 
        detail.binding.binding_status === 'Active'
      );
    } catch (error) {
      console.error('获取项目活跃模板绑定失败:', error);
      throw new Error(`获取活跃模板绑定失败: ${error}`);
    }
  }

  /**
   * 获取项目的主要模板详情
   */
  static async getPrimaryTemplateForProject(projectId: string): Promise<ProjectTemplateBindingDetail | null> {
    try {
      const bindings = await this.getTemplatesByProject(projectId);
      const primaryBinding = bindings.find(detail => 
        detail.binding.binding_type === 'Primary' && 
        detail.binding.is_active
      );
      return primaryBinding || null;
    } catch (error) {
      console.error('获取项目主要模板详情失败:', error);
      throw new Error(`获取主要模板详情失败: ${error}`);
    }
  }

  /**
   * 切换绑定状态（激活/停用）
   */
  static async toggleBindingStatus(id: string, currentStatus: boolean): Promise<ProjectTemplateBinding> {
    try {
      if (currentStatus) {
        return await this.deactivateBinding(id);
      } else {
        return await this.activateBinding(id);
      }
    } catch (error) {
      console.error('切换绑定状态失败:', error);
      throw new Error(`切换绑定状态失败: ${error}`);
    }
  }

  /**
   * 重新排序绑定优先级
   */
  static async reorderBindings(_projectId: string, bindingIds: string[]): Promise<void> {
    try {
      const updatePromises = bindingIds.map((id, index) => 
        this.updateBinding(id, { priority: index })
      );
      await Promise.all(updatePromises);
    } catch (error) {
      console.error('重新排序绑定失败:', error);
      throw new Error(`重新排序绑定失败: ${error}`);
    }
  }

  /**
   * 复制绑定到其他项目
   */
  static async copyBindingToProject(bindingId: string, targetProjectId: string): Promise<ProjectTemplateBinding> {
    try {
      const sourceBinding = await this.getBinding(bindingId);
      const createRequest: CreateProjectTemplateBindingRequest = {
        project_id: targetProjectId,
        template_id: sourceBinding.template_id,
        binding_name: sourceBinding.binding_name,
        description: sourceBinding.description,
        priority: sourceBinding.priority,
        binding_type: sourceBinding.binding_type === 'Primary' ? 'Secondary' as any : sourceBinding.binding_type,
      };
      return await this.createBinding(createRequest);
    } catch (error) {
      console.error('复制绑定到其他项目失败:', error);
      throw new Error(`复制绑定失败: ${error}`);
    }
  }
}
