<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 统计卡片 -->
      <el-row :gutter="16" class="stat-cards">
        <el-col :span="6" v-for="card in statCards" :key="card.key">
          <div
            class="stat-card"
            :class="{ active: activeStatus === card.value }"
            @click="handleCardClick(card.value)"
          >
            <div class="stat-card__icon" :style="{ backgroundColor: card.bgColor }">
              <i :class="card.icon" :style="{ color: card.color }"></i>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__count">{{ card.count }}</div>
              <div class="stat-card__label">{{ card.label }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 筛选区 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input
                v-model="query.keyword"
                placeholder="搜索标题/版本号"
                clearable
                @keyup.enter.native="search"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="更新类型">
              <el-select v-model="query.type" placeholder="全部" clearable>
                <el-option label="功能更新" :value="1" />
                <el-option label="Bug修复" :value="2" />
                <el-option label="性能优化" :value="3" />
                <el-option label="安全更新" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布状态">
              <el-select v-model="query.isPublished" placeholder="全部" clearable>
                <el-option label="已发布" :value="true" />
                <el-option label="草稿" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 表格区 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <div class="NCC-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增日志</el-button>
          </div>
          <div class="NCC-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh NCC-common-head-icon"
                :underline="false"
                @click="reset"
              />
            </el-tooltip>
          </div>
        </div>

        <el-table v-loading="listLoading" :data="list" border style="width: 100%">
          <el-table-column prop="version" label="版本号" width="100" align="center">
            <template slot-scope="scope">
              <el-tag size="small" effect="plain">v{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="更新标题" width="180" show-overflow-tooltip />
          <el-table-column prop="content" label="内容预览" min-width="250" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="content-preview">{{ getContentPreview(scope.row.content) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getTypeTagType(scope.row.type)" size="small">
                {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isPublished" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isPublished ? 'success' : 'info'" size="small">
                {{ scope.row.isPublished ? '已发布' : '草稿' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="publishedTime" label="发布时间" width="160">
            <template slot-scope="scope">
              {{ scope.row.publishedTime ? formatDateTime(scope.row.publishedTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleTogglePublish(scope.row)">
                {{ scope.row.isPublished ? '取消发布' : '发布' }}
              </el-button>
              <el-button type="text" size="small" class="NCC-table-danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="700px"
      class="NCC-dialog"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="formData.version" placeholder="如：3.2.1" style="width: 200px" />
        </el-form-item>
        <el-form-item label="更新标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入更新标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="更新类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择">
            <el-option label="功能更新" :value="1" />
            <el-option label="Bug修复" :value="2" />
            <el-option label="性能优化" :value="3" />
            <el-option label="安全更新" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="更新内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="8"
            placeholder="请输入更新内容，支持换行"
          />
        </el-form-item>
        <el-form-item label="立即发布">
          <el-switch v-model="formData.isPublished" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog
      title="更新日志详情"
      :visible.sync="detailVisible"
      width="600px"
      class="NCC-dialog"
    >
      <div v-if="detailData" class="changelog-detail">
        <div class="detail-header">
          <el-tag size="small" effect="plain">v{{ detailData.version }}</el-tag>
          <el-tag :type="getTypeTagType(detailData.type)" size="small">
            {{ getTypeText(detailData.type) }}
          </el-tag>
          <el-tag :type="detailData.isPublished ? 'success' : 'info'" size="small">
            {{ detailData.isPublished ? '已发布' : '草稿' }}
          </el-tag>
        </div>
        <h3 class="detail-title">{{ detailData.title }}</h3>
        <div class="detail-time">
          <span v-if="detailData.publishedTime">发布时间：{{ formatDateTime(detailData.publishedTime) }}</span>
          <span>创建时间：{{ formatDateTime(detailData.createTime) }}</span>
        </div>
        <div class="detail-content">{{ detailData.content }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChangelogList, addChangelog, updateChangelog, deleteChangelog, togglePublish } from '@/api/extend/changelog'

export default {
  name: 'LqChangelog',
  data() {
    return {
      activeStatus: null,
      stats: { total: 0, published: 0, draft: 0, type1: 0 },
      query: {
        keyword: undefined,
        type: undefined,
        isPublished: undefined
      },
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        currentPage: 1,
        pageSize: 20
      },
      dialogVisible: false,
      dialogTitle: '新增更新日志',
      formData: {
        id: '',
        version: '',
        title: '',
        content: '',
        type: 1,
        isPublished: false
      },
      rules: {
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        title: [{ required: true, message: '请输入更新标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入更新内容', trigger: 'blur' }],
        type: [{ required: true, message: '请选择更新类型', trigger: 'change' }]
      },
      submitLoading: false,
      detailVisible: false,
      detailData: null
    }
  },
  computed: {
    statCards() {
      return [
        {
          key: 'total',
          label: '全部日志',
          value: null,
          count: this.stats.total,
          icon: 'el-icon-document',
          color: '#409EFF',
          bgColor: 'rgba(64,158,255,0.1)'
        },
        {
          key: 'published',
          label: '已发布',
          value: true,
          count: this.stats.published,
          icon: 'el-icon-circle-check',
          color: '#67C23A',
          bgColor: 'rgba(103,194,58,0.1)'
        },
        {
          key: 'draft',
          label: '草稿',
          value: false,
          count: this.stats.draft,
          icon: 'el-icon-edit-outline',
          color: '#909399',
          bgColor: 'rgba(144,147,153,0.1)'
        },
        {
          key: 'feature',
          label: '功能更新',
          value: 'feature',
          count: this.stats.type1,
          icon: 'el-icon-star-off',
          color: '#E6A23C',
          bgColor: 'rgba(230,162,60,0.1)'
        }
      ]
    }
  },
  created() {
    this.initData()
  },
  methods: {
    loadStats() {
      const allParams = { currentPage: 1, pageSize: 1 }
      getChangelogList(allParams).then(res => {
        this.stats.total = res.data.pagination.total
      })
      getChangelogList({ ...allParams, isPublished: true }).then(res => {
        this.stats.published = res.data.pagination.total
      })
      getChangelogList({ ...allParams, isPublished: false }).then(res => {
        this.stats.draft = res.data.pagination.total
      })
      getChangelogList({ ...allParams, type: 1 }).then(res => {
        this.stats.type1 = res.data.pagination.total
      })
    },
    initData() {
      this.listLoading = true
      this.loadStats()
      const params = {
        currentPage: this.listQuery.currentPage,
        pageSize: this.listQuery.pageSize
      }
      if (this.query.keyword) params.keyword = this.query.keyword
      if (this.query.type !== undefined && this.query.type !== null) params.type = this.query.type
      if (this.query.isPublished !== undefined && this.query.isPublished !== null) params.isPublished = this.query.isPublished

      getChangelogList(params).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleCardClick(value) {
      if (value === 'feature') {
        this.activeStatus = null
        this.query.isPublished = undefined
        this.query.type = 1
      } else {
        this.activeStatus = value
        this.query.isPublished = value
        this.query.type = undefined
      }
      this.listQuery.currentPage = 1
      this.initData()
    },
    search() {
      this.listQuery.currentPage = 1
      this.initData()
    },
    reset() {
      this.activeStatus = null
      this.query = { keyword: undefined, type: undefined, isPublished: undefined }
      this.listQuery = { currentPage: 1, pageSize: 20 }
      this.initData()
    },
    handleAdd() {
      this.dialogTitle = '新增更新日志'
      this.formData = {
        id: '',
        version: '',
        title: '',
        content: '',
        type: 1,
        isPublished: false
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑更新日志'
      this.formData = {
        id: row.id,
        version: row.version,
        title: row.title,
        content: row.content,
        type: row.type,
        isPublished: row.isPublished
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleView(row) {
      this.detailData = row
      this.detailVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.submitLoading = true
        const request = this.formData.id ? updateChangelog(this.formData) : addChangelog(this.formData)
        request.then(res => {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.initData()
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    handleTogglePublish(row) {
      const text = row.isPublished ? '取消发布' : '发布'
      this.$confirm(`确定要${text}该日志吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        togglePublish(row.id).then(res => {
          this.$message.success('操作成功')
          this.initData()
        })
      }).catch(() => {})
    },
    handleDelete(row) {
      this.$confirm('确定要删除该日志吗？删除后不可恢复！', '提示', {
        type: 'warning'
      }).then(() => {
        deleteChangelog(row.id).then(res => {
          this.$message.success('删除成功')
          this.initData()
        })
      }).catch(() => {})
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return dateTime
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      const h = String(date.getHours()).padStart(2, '0')
      const min = String(date.getMinutes()).padStart(2, '0')
      const s = String(date.getSeconds()).padStart(2, '0')
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    },
    getTypeText(type) {
      const map = { 1: '功能更新', 2: 'Bug修复', 3: '性能优化', 4: '安全更新' }
      return map[type] || '其他'
    },
    getTypeTagType(type) {
      const map = { 1: 'primary', 2: 'danger', 3: 'success', 4: 'warning' }
      return map[type] || 'info'
    },
    getContentPreview(content) {
      if (!content) return '-'
      return content.replace(/[\r\n]+/g, ' ').substring(0, 60) + (content.length > 60 ? '...' : '')
    }
  }
}
</script>

<style lang="scss" scoped>
.stat-cards {
  margin-bottom: 16px;
}

.stat-card {
  display: flex;
  align-items: center;
  height: 100px;
  padding: 12px;
  background: #fff;
  border-radius: 12px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  &.active {
    border-color: #409eff;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
  }

  &__icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 56px;
    height: 56px;
    border-radius: 12px;
    flex-shrink: 0;

    i {
      font-size: 28px;
    }
  }

  &__info {
    margin-left: 16px;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  &__count {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    line-height: 1.2;
  }

  &__label {
    font-size: 14px;
    color: #909399;
    margin-top: 4px;
  }
}

.content-preview {
  color: #909399;
  font-size: 13px;
}

.changelog-detail {
  .detail-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
  }

  .detail-title {
    margin: 0 0 12px 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }

  .detail-time {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;
    font-size: 13px;
    color: #909399;
  }

  .detail-content {
    color: #606266;
    line-height: 1.8;
    white-space: pre-wrap;
    background: #f5f7fa;
    padding: 16px;
    border-radius: 8px;
    max-height: 400px;
    overflow-y: auto;
  }
}
</style>
