<template>
  <div class="report-template-container">
    <!-- 顶部操作栏 -->
    <div class="header-toolbar">
      <div class="search-section">
        <a-input-search
          v-model="searchKeyword"
          placeholder="搜索模板名称"
          style="width: 300px"
          allow-clear
          @search="handleSearch"
        />
      </div>
      
      <a-button 
        type="primary" 
        @click="handleNewTemplate"
        :loading="creating"
      >
        <template #icon><icon-plus /></template>
        新建模板
      </a-button>
    </div>

    <!-- 模板列表表格 -->
    <div class="template-table">
      <a-table
        :data="filteredTemplates"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        size="medium"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 模板类型 -->
        <template #templateType="{ record }">
          <a-tag :color="getTemplateTypeColor(record.templateType)">
            {{ record.templateType }}
          </a-tag>
        </template>
        
        <!-- 操作列 -->
        <template #action="{ record }">
          <a-space>
            <a-button size="small" @click="viewTemplate(record)">
              查看
            </a-button>
            <a-button size="small" @click="editTemplate(record)">
              编辑
            </a-button>
            <a-button size="small" status="danger" @click="deleteTemplate(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 新建/编辑模板模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑模板' : '新建模板'"
      width="700px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form ref="formRef" :model="templateForm" layout="vertical">
        <a-form-item label="模板名称" field="templateName" required>
          <a-input v-model="templateForm.templateName" placeholder="请输入模板名称" />
        </a-form-item>
        
        <a-form-item label="模板类型" field="templateType" required>
          <a-select v-model="templateForm.templateType" placeholder="请选择模板类型">
            <a-option value="检查报告">检查报告</a-option>
            <a-option value="维修报告">维修报告</a-option>
            <a-option value="月度报告">月度报告</a-option>
            <a-option value="年度报告">年度报告</a-option>
            <a-option value="专项报告">专项报告</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="创建人" field="creator">
          <a-input v-model="templateForm.creator" placeholder="请输入创建人" />
        </a-form-item>
        
        <a-form-item label="模板描述" field="description">
          <a-textarea v-model="templateForm.description" placeholder="请输入模板描述" :rows="4" />
        </a-form-item>
        
        <a-form-item label="模板内容" field="content">
          <a-textarea v-model="templateForm.content" placeholder="请输入模板内容" :rows="8" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 模板详情模态框 -->
    <a-modal
      v-model:visible="detailModalVisible"
      :title="selectedTemplate?.templateName"
      width="800px"
      :footer="false"
    >
      <div v-if="selectedTemplate" class="template-detail">
        <a-descriptions :data="templateDetailData" title="模板信息" :column="2" />
        
        <div class="template-content">
          <h3>模板内容</h3>
          <div class="content-preview">
            {{ selectedTemplate.content }}
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'

defineOptions({ name: 'ReportTemplate' })

// 接口定义
interface TemplateData {
  id: string
  templateName: string
  templateType: string
  creator: string
  createTime: string
  description: string
  content: string
}

// 响应式数据
const searchKeyword = ref('')
const loading = ref(false)
const creating = ref(false)
const modalVisible = ref(false)
const detailModalVisible = ref(false)
const isEdit = ref(false)
const selectedTemplate = ref<TemplateData | null>(null)
const formRef = ref()

// 表单数据
const templateForm = reactive({
  templateName: '',
  templateType: '',
  creator: '',
  description: '',
  content: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
})

// 模板数据
const templates = ref<TemplateData[]>([
  {
    id: '1',
    templateName: '标准检查报告模板',
    templateType: '检查报告',
    creator: '系统管理员',
    createTime: '2023-01-10',
    description: '标准的风电叶片检查报告模板',
    content: `# 风电叶片检查报告

## 1. 检查概况
- 检查时间：{检查时间}
- 检查人员：{检查人员}
- 检查机组：{机组编号}

## 2. 检查结果
- 检查项目：{检查项目}
- 检查结果：{检查结果}
- 缺陷情况：{缺陷情况}

## 3. 处理建议
{处理建议}

## 4. 总结
{总结内容}`
  },
  {
    id: '2',
    templateName: '维修报告模板',
    templateType: '维修报告',
    creator: '王维修',
    createTime: '2023-03-15',
    description: '风电叶片维修记录报告模板',
    content: `# 维修报告

## 基本信息
- 维修时间：{维修时间}
- 维修人员：{维修人员}
- 维修项目：{维修项目}

## 维修过程
{维修过程描述}

## 维修结果
{维修结果}

## 质量检验
{质量检验结果}`
  },
  {
    id: '3',
    templateName: '月度报告模板',
    templateType: '月度报告',
    creator: '李经理',
    createTime: '2023-05-20',
    description: '风电场月度运行报告模板',
    content: `# 月度运行报告

## 本月概况
- 报告期间：{报告期间}
- 发电量：{发电量}
- 设备运行情况：{设备运行情况}

## 主要工作
{主要工作内容}

## 存在问题
{存在问题}

## 下月计划
{下月计划}`
  }
])

// 表格列配置
const columns: TableColumnData[] = [
  { title: '模板名称', dataIndex: 'templateName', width: 200 },
  { title: '模板类型', dataIndex: 'templateType', slotName: 'templateType', width: 120 },
  { title: '创建人', dataIndex: 'creator', width: 100 },
  { title: '创建时间', dataIndex: 'createTime', width: 120 },
  { title: '描述', dataIndex: 'description', ellipsis: true, tooltip: true },
  { title: '操作', slotName: 'action', width: 200, fixed: 'right' }
]

// 计算属性
const filteredTemplates = computed(() => {
  if (!searchKeyword.value) return templates.value
  return templates.value.filter(template => 
    template.templateName.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    template.templateType.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const templateDetailData = computed(() => {
  if (!selectedTemplate.value) return []
  
  return [
    { label: '模板名称', value: selectedTemplate.value.templateName },
    { label: '模板类型', value: selectedTemplate.value.templateType },
    { label: '创建人', value: selectedTemplate.value.creator },
    { label: '创建时间', value: selectedTemplate.value.createTime },
    { label: '模板描述', value: selectedTemplate.value.description }
  ]
})

// 方法
const getTemplateTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '检查报告': 'blue',
    '维修报告': 'green',
    '月度报告': 'orange',
    '年度报告': 'purple',
    '专项报告': 'red'
  }
  return colorMap[type] || 'gray'
}

const handleSearch = () => {
  // 搜索逻辑已在 computed 中处理
}

const handleNewTemplate = () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

const editTemplate = (template: TemplateData) => {
  isEdit.value = true
  Object.assign(templateForm, {
    templateName: template.templateName,
    templateType: template.templateType,
    creator: template.creator,
    description: template.description,
    content: template.content
  })
  modalVisible.value = true
}

const viewTemplate = (template: TemplateData) => {
  selectedTemplate.value = template
  detailModalVisible.value = true
}

const deleteTemplate = (template: TemplateData) => {
  const index = templates.value.findIndex(t => t.id === template.id)
  if (index > -1) {
    templates.value.splice(index, 1)
    Message.success('模板删除成功')
  }
}

const resetForm = () => {
  Object.assign(templateForm, {
    templateName: '',
    templateType: '',
    creator: '',
    description: '',
    content: ''
  })
}

const handleModalOk = async () => {
  creating.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 编辑逻辑
      const template = templates.value.find(t => t.id === selectedTemplate.value?.id)
      if (template) {
        Object.assign(template, templateForm)
      }
      Message.success('模板更新成功')
    } else {
      // 新建逻辑
      const newTemplate: TemplateData = {
        id: Date.now().toString(),
        ...templateForm,
        createTime: new Date().toLocaleDateString()
      }
      templates.value.push(newTemplate)
      Message.success('模板创建成功')
    }
    
    modalVisible.value = false
    resetForm()
  } catch (error) {
    Message.error('操作失败')
  } finally {
    creating.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const onPageChange = (page: number) => {
  pagination.current = page
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
}

// 组件挂载
onMounted(() => {
  pagination.total = templates.value.length
})
</script>

<style scoped lang="scss">
.report-template-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  
  .header-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .template-table {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .template-detail {
    .template-content {
      margin-top: 24px;
      
      h3 {
        margin-bottom: 16px;
        color: #1f2937;
      }
      
      .content-preview {
        background: #f8f9fa;
        padding: 16px;
        border-radius: 8px;
        white-space: pre-wrap;
        font-family: monospace;
        font-size: 14px;
        line-height: 1.6;
        color: #374151;
        border: 1px solid #e5e7eb;
        max-height: 400px;
        overflow-y: auto;
      }
    }
  }
}

:deep(.arco-table) {
  .arco-table-th {
    background: #f8f9fa;
    font-weight: 600;
  }
  
  .arco-table-td {
    padding: 12px 16px;
  }
}

:deep(.arco-descriptions-item-label) {
  font-weight: 600;
  color: #374151;
}

:deep(.arco-descriptions-item-value) {
  color: #1f2937;
}
</style>
