<template>
  <div class="dimension-management report-container">
    <el-card>
      <template #header>
        <div class="report-header">
          <div class="header-content">
            <h2 class="report-title">{{ t('dataReport.dimensionManagement') }}</h2>
            <p class="report-subtitle">{{ t('dataReport.manageDimensionConfig') }}</p>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd" :icon="Plus">
              {{ t('dataReport.addDimension') }}
            </el-button>
            <el-button @click="refreshList" :icon="Refresh" class="sa-button-refresh">
              {{ t('dataReport.refreshData') }}
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item>
            <el-input v-model="searchForm.keyword" :placeholder="t('dataReport.enterDimensionNameOrCode')" clearable
              @keyup.enter="handleSearch" class="search-input">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              {{ t('common.search') }}
            </el-button>
            <el-button @click="handleReset" :icon="RefreshLeft">
              {{ t('common.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table v-loading="loading" :data="tableData" stripe border style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" :label="t('dataReport.dimensionName')" min-width="150">
            <template #default="{ row }">
              <div class="dimension-name">
                <el-tag :type="getDimensionTypeTag(row.type)" size="small" style="margin-right: 8px;">
                  {{ getDimensionTypeLabel(row.type) }}
                </el-tag>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="code" :label="t('dataReport.dimensionCode')" width="120" />
          <el-table-column prop="description" :label="t('form.description')" min-width="200" show-overflow-tooltip />
          <el-table-column prop="dataType" :label="t('dataReport.dataType')" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getDataTypeTag(row.dataType)">
                {{ getDataTypeLabel(row.dataType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" :label="t('dataReport.unit')" width="80" />
          <el-table-column prop="status" :label="t('common.status')" width="80">
            <template #default="{ row }">
              <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :label="t('form.createTime')" width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column :label="t('common.operation')" width="180" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">
                <el-icon>
                  <Edit />
                </el-icon>
                {{ t('common.edit') }}
              </el-button>

              <el-button size="small" type="danger" link @click="handleDelete(row)">
                <el-icon>
                  <Delete />
                </el-icon>
                {{ t('common.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量操作 -->
        <div class="batch-actions" v-if="selectedRows.length > 0">
          <span class="batch-info">
            {{ t('dataReport.selectedItems', { count: selectedRows.length }) }}
          </span>
          <div class="batch-buttons">
            <el-button type="danger" size="small" @click="handleBatchDelete">
              {{ t('dataReport.batchDelete') }}
            </el-button>
            <el-button type="success" size="small" @click="handleBatchEnable">
              {{ t('dataReport.batchEnable') }}
            </el-button>
            <el-button type="warning" size="small" @click="handleBatchDisable">
              {{ t('dataReport.batchDisable') }}
            </el-button>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-card>

    <!-- 对话框现在通过 useModal 处理 -->
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Refresh, Search, RefreshLeft, Edit, Delete,
  Check, Close
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { api } from '../../data.service.js'
import { useModal } from '@/sheep/components/sa-modal/sa-modal.vue'

// 使用国际化
const { t } = useI18n();

// 响应式数据
const loading = ref(false)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 不再需要 formData、viewData 和相关验证规则，这些已移至独立组件中

// 工具方法已移至独立组件中

// 数据加载
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }

    const response = await api.report.dimensions.list(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '数据加载失败')
    }
  } catch (error) {
    console.error('加载维度数据失败:', error)
    ElMessage.error('数据加载失败')
    // 模拟数据
    tableData.value = generateMockData()
    pagination.total = 50
  } finally {
    loading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const types = ['time', 'region', 'product', 'user', 'channel']
  const dataTypes = ['string', 'number', 'date', 'boolean']
  const data = []

  for (let i = 1; i <= 20; i++) {
    data.push({
      id: i,
      name: `维度${i}`,
      code: `dimension_${i}`,
      type: types[Math.floor(Math.random() * types.length)],
      dataType: dataTypes[Math.floor(Math.random() * dataTypes.length)],
      unit: i % 3 === 0 ? '个' : i % 3 === 1 ? '元' : '',
      description: `这是维度${i}的描述信息`,
      config: i % 4 === 0 ? JSON.stringify({ format: 'YYYY-MM-DD', precision: 2 }) : '',
      status: Math.random() > 0.3 ? 1 : 0,
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
    })
  }

  return data
}

// 事件处理
const handleAdd = () => {
  useModal(() => import('./dimension-edit-modal.vue'), {
    title: '新增维度',
    width: '600px',
    height: '500px',
    componentProps: {
      title: t('dataReport.addDimension'),
      type: 'add',
      dimensionData: {}
    },
    confirm: async (modalRef) => {
      const result = await modalRef.handleConfirm()
      if (result) {
        await api.report.dimensions.add(modalRef.form)
        ElMessage.success(t('message.createSuccess'))
        loadData()
        return true
      }
      return false
    }
  })
}

const handleEdit = (row) => {
  useModal(() => import('./dimension-edit-modal.vue'), {
    title: '编辑维度',
    width: '600px',
    height: '500px',
    componentProps: {
      title: t('dataReport.editDimension'),
      type: 'edit',
      dimensionData: row
    },
    confirm: async (modalRef) => {
      const result = await modalRef.handleConfirm()
      if (result) {
        await api.report.dimensions.update(modalRef.form)
        ElMessage.success(t('message.updateSuccess'))
        loadData()
        return true
      }
      return false
    }
  })
}



const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      t('dataReport.confirmDeleteDimension', { name: row.name }),
      t('dataReport.deleteConfirmation'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )

    const response = await api.report.dimensions.delete(row.id)
    if (response.code === 200) {
      ElMessage.success(t('message.deleteSuccess'))
      loadData()
    } else {
      ElMessage.error(response.message || t('message.deleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除维度失败:', error)
      ElMessage.error(t('message.deleteFailed'))
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    const response = await api.report.dimensions.update(row.id, {
      status: row.status
    })
    if (response.code === 200) {
      ElMessage.success(t('dataReport.statusUpdateSuccess'))
    } else {
      ElMessage.error(response.message || t('dataReport.statusUpdateFailed'))
      // 回滚状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error(t('dataReport.statusUpdateFailed'))
    // 回滚状态
    row.status = row.status === 1 ? 0 : 1
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: ''
  })
  pagination.page = 1
  loadData()
}

const refreshList = () => {
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning($t('dataReport.selectItemsToDelete'))
    return
  }

  try {
    await ElMessageBox.confirm(
      $t('dataReport.confirmBatchDelete', { count: selectedRows.value.length }),
      $t('dataReport.batchDeleteConfirmation'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(row => row.id)
    // 这里应该调用批量删除API
    ElMessage.success($t('dataReport.batchDeleteSuccess'))
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error($t('dataReport.batchDeleteFailed'))
    }
  }
}

const handleBatchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning($t('dataReport.selectItemsToEnable'))
    return
  }

  try {
    const ids = selectedRows.value.map(row => row.id)
    // 这里应该调用批量更新API
    ElMessage.success($t('dataReport.batchEnableSuccess'))
    loadData()
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error($t('dataReport.batchEnableFailed'))
  }
}

const handleBatchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning($t('dataReport.selectItemsToDisable'))
    return
  }

  try {
    const ids = selectedRows.value.map(row => row.id)
    // 这里应该调用批量更新API
    ElMessage.success($t('dataReport.batchDisableSuccess'))
    loadData()
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error($t('dataReport.batchDisableFailed'))
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证配置项JSON格式
    if (formData.config) {
      try {
        JSON.parse(formData.config)
      } catch {
        ElMessage.error('配置项格式错误，请输入有效的JSON格式')
        return
      }
    }

    submitting.value = true

    const submitData = { ...formData }
    delete submitData.id

    let response
    if (isEdit.value) {
      response = await api.report.dimensions.update(formData.id, submitData)
    } else {
      response = await api.report.dimensions.add(submitData)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    type: '',
    dataType: '',
    unit: '',
    description: '',
    config: '',
    status: 1
  })

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
@import '../styles/report-common.scss';

.dimension-management {
  .dimension-name {
    display: flex;
    align-items: center;
    gap: 8px;

    .dimension-icon {
      width: 20px;
      height: 20px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: white;

      &.time {
        background: #409eff;
      }

      &.region {
        background: #67c23a;
      }

      &.product {
        background: #e6a23c;
      }

      &.user {
        background: #f56c6c;
      }

      &.channel {
        background: #909399;
      }
    }
  }

  .config-display {
    background: var(--sa-background-assist);
    border: 1px solid var(--sa-space);
    border-radius: 4px;
    padding: 12px;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    white-space: pre-wrap;
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>