<template>
  <div class="title-group-container">
    <!-- 表格头部操作 -->
    <div class="header-actions">
      <el-button type="primary" @click="showAddDialog">新增标题组</el-button>
      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="fetchData">刷新</el-button>
      </div>
    </div>

    <!-- 主表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%;"
      v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="名称" width="250"></el-table-column>
      <el-table-column label="标题" min-width="300">
        <template slot-scope="scope">
          <div v-for="(titleObj, index) in scope.row.titles" :key="index" class="title-item">
            <span class="title-text">{{ titleObj.text }}</span>
            <el-tag size="mini" type="info" class="language-tag">{{ getLanguageName(titleObj.language) }}</el-tag>
          </div>
          <div v-if="!scope.row.titles || scope.row.titles.length === 0" class="no-titles">
            暂无标题
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes">
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="标题组名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="选择标题" prop="titles">
          <div class="title-selector-container">
            <div class="selected-titles" v-if="form.titles && form.titles.length > 0">
              <div class="selected-title-header">
                <span>已选择 {{ form.titles.length }} 个标题</span>
                <el-button type="text" @click="form.titles = []">清空</el-button>
              </div>
              <el-tag
                v-for="(titleObj, index) in form.titles"
                :key="index"
                closable
                @close="removeTitle(index)"
                class="title-tag">
                {{ titleObj.text }}
                <span class="title-language">({{ getLanguageName(titleObj.language) }})</span>
              </el-tag>
            </div>
            <el-button type="primary" size="small" @click="showTitleSelectorDialog">添加标题</el-button>
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 标题选择器对话框 -->
    <el-dialog
      title="选择标题"
      :visible.sync="titleSelectorDialogVisible"
      width="80%"
      append-to-body>
      <text-table-selecter
        @change="handleTitleSelectionChange"
        type="1">
      </text-table-selecter>
      <div slot="footer" class="dialog-footer">
        <el-button @click="titleSelectorDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTitleSelection">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TextTableSelecter from '@/components/TextTableSelecter'
import { getTitleGroupList, createTitleGroup, updateTitleGroup, deleteTitleGroup } from '@/api/titleGroup'
import { getLanguageName } from '@/const/language'

export default {
  name: 'TitleGroupManage',
  components: {
    TextTableSelecter
  },
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      titleSelectorDialogVisible: false,
      selectedTitles: [], // 用于TextTableSelecter组件的选中项
      form: {
        id: null,
        name: '',
        titles: [],
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入标题组名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取语言名称
    getLanguageName,
    
    // 获取标题组列表
    fetchData() {
      this.loading = true
      getTitleGroupList()
        .then(response => {
          this.loading = false
          if (response.status === 200) {
            // 处理从后端返回的数据
            const data = response.result.data || [];
            
            // 转换titles字段格式
            data.forEach(item => {
              if (item.titles && Array.isArray(item.titles)) {
                item.titles = item.titles.map(this.formatTitleDisplay).filter(Boolean);
              }
            });
            
            this.tableData = data;
            this.total = this.tableData.length;
          } else {
            this.$message.error('获取标题组列表失败')
          }
        })
        .catch(error => {
          this.loading = false
          console.error('获取标题组列表失败:', error)
          this.$message.error('获取标题组列表失败: ' + error.message)
        })
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString()
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 处理表格中显示的标题内容
    formatTitleDisplay(titleObj) {
      if (typeof titleObj === 'string') {
        // 兼容旧格式：字符串
        return { text: titleObj, language: 'en' };
      } else if (titleObj && typeof titleObj === 'object') {
        // 新格式：对象
        return titleObj;
      }
      return null;
    },

    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增标题组'
      this.form = {
        id: null,
        name: '',
        titles: [],
        remark: ''
      }
      this.dialogVisible = true
      // 重置表单验证
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },

    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑标题组'
      // 深拷贝避免直接修改表格数据
      const formData = JSON.parse(JSON.stringify(row));
      
      // 处理titles字段，确保为新格式
      if (formData.titles && Array.isArray(formData.titles)) {
        formData.titles = formData.titles.map(this.formatTitleDisplay).filter(Boolean);
      }
      
      this.form = formData;
      this.dialogVisible = true
      // 重置表单验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    handleTitleSelectionChange(data){
      this.selectedTitles = data
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该标题组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTitleGroup(row.id)
          .then(response => {
            if (response.status === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error('删除失败')
            }
          })
          .catch(error => {
            console.error('删除标题组失败:', error)
            this.$message.error('删除标题组失败: ' + error.message)
          })
      }).catch(() => {
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const isEdit = !!this.form.id
          // 深拷贝表单数据，避免直接修改
          const formData = JSON.parse(JSON.stringify(this.form))
          
          // 确保titles数组中的每个对象都有text和language属性
          if (formData.titles && Array.isArray(formData.titles)) {
            formData.titles = formData.titles.map(title => {
              // 如果是字符串，转换为对象格式
              if (typeof title === 'string') {
                return { text: title, language: 'en' };
              }
              // 如果已经是对象但缺少language属性
              if (typeof title === 'object' && title.text && !title.language) {
                return { ...title, language: 'en' };
              }
              return title;
            });
          }
          
          const apiCall = isEdit 
            ? updateTitleGroup(formData.id, formData)
            : createTitleGroup(formData)

          apiCall
            .then(response => {
              if (response.status === 200) {
                this.$message.success(isEdit ? '更新成功' : '创建成功')
                this.dialogVisible = false
                this.fetchData()
              } else {
                this.$message.error(isEdit ? '更新失败' : '创建失败')
              }
            })
            .catch(error => {
              console.error(isEdit ? '更新标题组失败:' : '创建标题组失败:', error)
              this.$message.error((isEdit ? '更新' : '创建') + '标题组失败: ' + error.message)
            })
        } else {
          return false
        }
      })
    },

    // 显示标题选择器对话框
    showTitleSelectorDialog() {
      this.selectedTitles = []
      this.titleSelectorDialogVisible = true
    },

    // 确认标题选择
    confirmTitleSelection() {
      // 从TextTableSelecter获取的是完整的文案对象，已包含text和language属性
      const newTitles = this.selectedTitles.map(item => ({
        text: item.text,
        language: item.language || 'en' // 如果没有语言字段，默认为英语
      }))
      
      // 合并，避免重复添加相同的标题+语言组合
      const uniqueTitles = [...this.form.titles]
      
      newTitles.forEach(newTitle => {
        const isDuplicate = uniqueTitles.some(
          existingTitle => existingTitle.text === newTitle.text && existingTitle.language === newTitle.language
        )
        if (!isDuplicate) {
          uniqueTitles.push(newTitle)
        }
      })
      
      this.form.titles = uniqueTitles
      this.titleSelectorDialogVisible = false
    },

    // 移除标题
    removeTitle(index) {
      this.form.titles.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.title-group-container {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.title-item {
  margin-bottom: 5px;
  line-height: 1.5;
  word-break: break-all;
}

.no-titles {
  color: #999;
  font-style: italic;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.title-selector-container {
  margin-bottom: 10px;
}

.selected-titles {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.selected-title-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.title-tag {
  margin-right: 5px;
  margin-bottom: 5px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.title-text {
  margin-right: 5px;
}

.language-tag {
  margin-left: 5px;
}

.title-language {
  font-size: 0.8em;
  color: #909399;
}
</style>
