<template>
  <div class="description-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="(descObj, index) in scope.row.descriptions" :key="index" class="description-item">
            <span class="description-text">{{ descObj.text }}</span>
            <el-tag size="mini" type="info" class="language-tag">{{ getLanguageName(descObj.language) }}</el-tag>
          </div>
          <div v-if="!scope.row.descriptions || scope.row.descriptions.length === 0" class="no-descriptions">
            暂无描述
          </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="descriptions">
          <div class="description-selector-container">
            <div class="selected-descriptions" v-if="form.descriptions && form.descriptions.length > 0">
              <div class="selected-description-header">
                <span>已选择 {{ form.descriptions.length }} 个描述</span>
                <el-button type="text" @click="form.descriptions = []">清空</el-button>
              </div>
              <el-tag
                v-for="(descObj, index) in form.descriptions"
                :key="index"
                closable
                @close="removeDescription(index)"
                class="description-tag">
                {{ descObj.text }}
                <span class="description-language">({{ getLanguageName(descObj.language) }})</span>
              </el-tag>
            </div>
            <el-button type="primary" size="small" @click="showDescriptionSelectorDialog">添加描述</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="descriptionSelectorDialogVisible"
      width="80%"
      append-to-body>
      <text-table-selecter
        @change="handleDescriptionSelectionChange"
        type="2">
      </text-table-selecter>
      <div slot="footer" class="dialog-footer">
        <el-button @click="descriptionSelectorDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDescriptionSelection">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TextTableSelecter from '@/components/TextTableSelecter'
import { getDescriptionGroupList, createDescriptionGroup, updateDescriptionGroup, deleteDescriptionGroup } from '@/api/descriptionGroup'
import { getLanguageName } from '@/const/language'

export default {
  name: 'DescriptionGroupManage',
  components: {
    TextTableSelecter
  },
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      descriptionSelectorDialogVisible: false,
      selectedDescriptions: [], // 用于TextTableSelecter组件的选中项
      form: {
        id: null,
        name: '',
        descriptions: [],
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入描述组名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取语言名称
    getLanguageName,
    
    // 处理描述内容显示格式
    formatDescriptionDisplay(descObj) {
      if (typeof descObj === 'string') {
        // 兼容旧格式：字符串
        return { text: descObj, language: 'en' };
      } else if (descObj && typeof descObj === 'object') {
        // 新格式：对象
        return descObj;
      }
      return null;
    },
    
    // 获取描述组列表
    fetchData() {
      this.loading = true
      getDescriptionGroupList()
        .then(response => {
          this.loading = false
          if (response.status === 200) {
            // 处理从后端返回的数据
            const data = response.result.data || [];
            
            // 转换descriptions字段格式
            data.forEach(item => {
              if (item.descriptions && Array.isArray(item.descriptions)) {
                item.descriptions = item.descriptions.map(this.formatDescriptionDisplay).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()
    },

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

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

    handleDescriptionSelectionChange(data) {
      this.selectedDescriptions = data
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该描述组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDescriptionGroup(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))
          
          // 确保descriptions数组中的每个对象都有text和language属性
          if (formData.descriptions && Array.isArray(formData.descriptions)) {
            formData.descriptions = formData.descriptions.map(description => {
              // 如果是字符串，转换为对象格式
              if (typeof description === 'string') {
                return { text: description, language: 'en' };
              }
              // 如果已经是对象但缺少language属性
              if (typeof description === 'object' && description.text && !description.language) {
                return { ...description, language: 'en' };
              }
              return description;
            });
          }
          
          const apiCall = isEdit 
            ? updateDescriptionGroup(formData.id, formData)
            : createDescriptionGroup(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
        }
      })
    },

    // 显示描述选择器对话框
    showDescriptionSelectorDialog() {
      this.selectedDescriptions = []
      this.descriptionSelectorDialogVisible = true
    },

    // 确认描述选择
    confirmDescriptionSelection() {
      // 从TextTableSelecter获取的是完整的文案对象，已包含text和language属性
      const newDescriptions = this.selectedDescriptions.map(item => ({
        text: item.text,
        language: item.language || 'en' // 如果没有语言字段，默认为英语
      }))
      
      // 合并，避免重复添加相同的描述+语言组合
      const uniqueDescriptions = [...this.form.descriptions]
      
      newDescriptions.forEach(newDesc => {
        const isDuplicate = uniqueDescriptions.some(
          existingDesc => existingDesc.text === newDesc.text && existingDesc.language === newDesc.language
        )
        if (!isDuplicate) {
          uniqueDescriptions.push(newDesc)
        }
      })
      
      this.form.descriptions = uniqueDescriptions
      this.descriptionSelectorDialogVisible = false
    },

    // 移除描述
    removeDescription(index) {
      this.form.descriptions.splice(index, 1)
    }
  }
}
</script>

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

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

.header-right {
  margin-left: auto;
}

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

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

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

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

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

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

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

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

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

.description-language {
  font-size: 0.8em;
  color: #909399;
  margin-left: 3px;
}
</style>
