<template>
  <div class="policies-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="政策标题">
              <el-input v-model="searchForm.title" placeholder="请输入政策标题" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="政策类型">
              <el-select v-model="searchForm.type" placeholder="请选择政策类型" clearable style="width: 150px">
                <el-option label="服务条款" value="terms" />
                <el-option label="定价政策" value="pricing" />
                <el-option label="隐私政策" value="privacy" />
                <el-option label="合规政策" value="compliance" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><search /></el-icon>搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><refresh /></el-icon>重置
              </el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><plus /></el-icon>发布政策
            </el-button>
          </div>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          row-key="id"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="title" label="政策标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="type" label="政策类型" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getPolicyTypeTag(scope.row.type)">
                {{ getPolicyTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="publisher" label="发布人" width="120" align="center" />
          <el-table-column prop="publishTime" label="发布时间" width="180" align="center" />
          <el-table-column prop="effectiveTime" label="生效时间" width="180" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                type="warning" 
                link 
                @click="handleChangeStatus(scope.row)"
                v-if="scope.row.status === 'active'"
              >下线</el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(scope.row)"
                v-if="scope.row.status === 'inactive'"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

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

    <!-- 政策详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div v-if="dialogType === 'view'" class="policy-detail">
        <h2 class="detail-title">{{ currentPolicy.title }}</h2>
        <div class="detail-info">
          <span>类型: {{ getPolicyTypeText(currentPolicy.type) }}</span>
          <span>发布人: {{ currentPolicy.publisher }}</span>
          <span>发布时间: {{ currentPolicy.publishTime }}</span>
          <span>生效时间: {{ currentPolicy.effectiveTime }}</span>
          <span>状态: {{ getStatusText(currentPolicy.status) }}</span>
        </div>
        <div class="detail-content" v-html="currentPolicy.content"></div>
      </div>
      <div v-else>
        <el-form :model="policyForm" label-width="120px" :rules="rules" ref="policyFormRef">
          <el-form-item label="政策标题" prop="title">
            <el-input v-model="policyForm.title" placeholder="请输入政策标题" />
          </el-form-item>
          <el-form-item label="政策类型" prop="type">
            <el-select v-model="policyForm.type" placeholder="请选择政策类型" style="width: 100%">
              <el-option label="服务条款" value="terms" />
              <el-option label="定价政策" value="pricing" />
              <el-option label="隐私政策" value="privacy" />
              <el-option label="合规政策" value="compliance" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="生效时间" prop="effectiveTime">
            <el-date-picker
              v-model="policyForm.effectiveTime"
              type="datetime"
              placeholder="选择生效时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="政策内容" prop="content">
            <el-input
              v-model="policyForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入政策内容"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="policyForm.status">
              <el-radio label="active">立即生效</el-radio>
              <el-radio label="pending">计划中</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="dialogType !== 'view'">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { 
  Plus, Search, Refresh, View, Edit, TurnOff, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  dateRange: []
})

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.type = ''
  searchForm.dateRange = []
  handleSearch()
}

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

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('') // 'add', 'edit', 'view'
const dialogTitle = computed(() => {
  if (dialogType.value === 'add') return '发布政策'
  if (dialogType.value === 'edit') return '编辑政策'
  return '政策详情'
})

// 当前选中的政策
const currentPolicy = ref({})

// 表单对象和规则
const policyFormRef = ref(null)
const policyForm = reactive({
  id: '',
  title: '',
  type: '',
  effectiveTime: '',
  content: '',
  status: 'active'
})

const rules = {
  title: [{ required: true, message: '请输入政策标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择政策类型', trigger: 'change' }],
  effectiveTime: [{ required: true, message: '请选择生效时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入政策内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 政策类型标签
const getPolicyTypeTag = (type) => {
  const map = {
    terms: '',
    pricing: 'success',
    privacy: 'warning',
    compliance: 'danger',
    other: 'info'
  }
  return map[type] || 'info'
}

const getPolicyTypeText = (type) => {
  const map = {
    terms: '服务条款',
    pricing: '定价政策',
    privacy: '隐私政策',
    compliance: '合规政策',
    other: '其他'
  }
  return map[type] || '未知'
}

// 状态标签样式
const getStatusType = (status) => {
  const map = {
    active: 'success',
    pending: 'warning',
    inactive: 'info'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    active: '已生效',
    pending: '计划中',
    inactive: '已下线'
  }
  return map[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 这里应该是真实的API请求
    const mockData = []
    const types = ['terms', 'pricing', 'privacy', 'compliance', 'other']
    const statuses = ['active', 'pending', 'inactive']
    
    for (let i = 0; i < pagination.pageSize; i++) {
      const id = (pagination.currentPage - 1) * pagination.pageSize + i + 1
      if (id > 28) break // 模拟总数
      
      const type = types[Math.floor(Math.random() * types.length)]
      const status = statuses[Math.floor(Math.random() * statuses.length)]
      
      mockData.push({
        id: `policy-${id}`,
        title: `云平台${getPolicyTypeText(type)}(${id})`,
        type,
        publisher: '系统管理员',
        publishTime: '2023-09-30 14:00:00',
        effectiveTime: '2023-10-01 00:00:00',
        status,
        content: `<p><strong>第一条：总则</strong></p>
                 <p>本政策适用于零零七云平台所有用户，请您仔细阅读并理解本政策的所有内容。</p>
                 <p><strong>第二条：服务内容</strong></p>
                 <p>本平台提供云计算、存储和网络等基础设施服务，以及相关的技术支持和咨询服务。</p>
                 <p><strong>第三条：用户权利与义务</strong></p>
                 <p>用户在使用本平台服务时，应当遵守中华人民共和国法律法规和平台规则，不得利用平台服务从事违法活动。</p>`
      })
    }
    
    tableData.value = mockData
    pagination.total = 28
    loading.value = false
  }, 500)
}

// 添加政策
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  policyForm.id = ''
  policyForm.title = ''
  policyForm.type = ''
  policyForm.effectiveTime = ''
  policyForm.content = ''
  policyForm.status = 'active'
}

// 查看政策
const handleView = (row) => {
  dialogType.value = 'view'
  dialogVisible.value = true
  currentPolicy.value = { ...row }
}

// 编辑政策
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  policyForm.id = row.id
  policyForm.title = row.title
  policyForm.type = row.type
  policyForm.effectiveTime = row.effectiveTime
  policyForm.content = row.content
  policyForm.status = row.status
}

// 更改政策状态（下线）
const handleChangeStatus = (row) => {
  ElMessageBox.confirm(`确定要下线"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该是API请求
    ElMessage.success('操作成功')
    fetchData()
  }).catch(() => {})
}

// 删除政策
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除"${row.title}"吗？删除后不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    // 这里应该是API请求
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {})
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (policyFormRef.value) {
    policyFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!policyFormRef.value) return
  
  await policyFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该是API请求
      ElMessage.success(dialogType.value === 'add' ? '发布成功' : '更新成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 初始加载
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.policies-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

/* 政策详情样式 */
.policy-detail {
  padding: 0 20px;
}

.detail-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
  color: #303133;
}

.detail-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  color: #909399;
  margin-bottom: 30px;
  font-size: 14px;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}

.detail-info span {
  margin: 5px 10px;
}

.detail-content {
  line-height: 1.8;
  color: #606266;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>