<template>
  <div class="app-container">
    <el-button
      type="success"
      size="mini"
      @click="handleAdd"
      style="margin-bottom: 10px;"
    >
      新增模板
    </el-button>

    <el-table :data="templateList" v-loading="loading" border>
      <el-table-column label="ID" prop="id" width="70" />
      <el-table-column label="模板名称" prop="templateName" />
      <el-table-column label="模板类型">
        <template slot-scope="scope">
            <el-tag v-if="scope.row.templateType === 'home'">
                首页模板
            </el-tag>

            <el-tag
                type="success"
                v-else-if="scope.row.templateType === 'user'"
            >
                个人中心
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '启用' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" width="340">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope.row)"> 编辑 </el-button>

          <el-button type="text" size="mini" @click="handlePreview(scope.row)"> 查看JSON </el-button>

          <el-tag v-if="currentTemplateMap[scope.row.templateType] === scope.row.id" type="success" size="mini"> 使用中 </el-tag>

          <el-button v-else type="text" size="mini" @click="handleUseTemplate(scope.row)"> 使用当前模板 </el-button>

          <el-button type="text" size="mini" style="color:#F56C6C" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- ✅ JSON预览弹窗（必须放在同一个根div里） -->
    <el-dialog
      title="模板JSON"
      :visible.sync="jsonOpen"
      width="80%"
      top="5vh"
    >
      <pre class="json-preview">{{ currentJson }}</pre>

      <div slot="footer">
        <el-button size="mini" @click="jsonOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDecorationTemplate,
  getDecorationTemplate,
  delDecorationTemplate,
  useDecorationTemplate,
  getCurrentCompanyTemplate
} from '@/api/decoration/decoration'

export default {
  name: 'DecorationTemplateList',
  data() {
    return {
      loading: false,
      templateList: [],
      jsonOpen: false,
      currentJson: '',
      currentTemplateMap: {}
    }
  },
  created() {
    this.getList()
    this.loadCurrentTemplates()
  },
  methods: {
    getList() {
      this.loading = true
      listDecorationTemplate()
        .then(res => {
          this.templateList = res.data || []
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleAdd() {
      this.$router.push({
        path: '/decoration/template/editor'
      })
    },

    handleEdit(row) {
      this.$router.push({
        path: '/decoration/template/editor',
        query: { id: row.id }
      })
    },

    handlePreview(row) {
      getDecorationTemplate(row.id).then(res => {
        const data = res.data || {}

        try {
          this.currentJson = JSON.stringify(
            JSON.parse(data.templateData || '{}'),
            null,
            2
          )
        } catch (e) {
          this.currentJson = data.templateData || ''
        }

        this.jsonOpen = true
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除该模板吗？', '提示', { type: 'warning' })
        .then(() => delDecorationTemplate(row.id))
        .then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
    },

    // 查询当前公司每种类型正在使用的模板
    loadCurrentTemplates() {
      const types = ['home', 'activity', 'user']

      types.forEach(type => {
        getCurrentCompanyTemplate({
          templateType: type
        }).then(res => {
          this.$set(this.currentTemplateMap, type, res.data)
        })
      })
    },

// 使用当前模板
    handleUseTemplate(row) {
      this.$confirm('确认使用该模板吗？同类型模板会被替换。', '提示', {
        type: 'warning'
      }).then(() => {
        return useDecorationTemplate({
          templateId: row.id
        })
      }).then(() => {
        this.$message.success('使用成功')
        this.loadCurrentTemplates()
      })
    }
  }
}
</script>

<style scoped>
.json-preview {
  background: #1e1e1e;
  color: #dcdcdc;
  padding: 16px;
  border-radius: 6px;
  font-size: 13px;
  line-height: 1.6;

  max-height: 70vh;
  overflow: auto;

  white-space: pre-wrap;
  word-break: break-all;
}
</style>
