<template>
  <module-page-shell title="报告模板管理">
    <div class="report-template-page">
      <section class="panel query-list-panel">
        <div class="panel__header">
          <div>
            <h3>报告模板管理</h3>
          </div>
          <el-button type="primary" @click="openCreateDialog">新增模板</el-button>
        </div>

        <div class="project-filter-bar">
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-input
              v-model="queryForm.templateName"
              placeholder="模板名称"
              clearable
            />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--medium">
            <el-input
              v-model="queryForm.scene"
              placeholder="适用场景"
              clearable
            />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--narrow">
            <el-select v-model="queryForm.status" clearable placeholder="状态：全部">
              <el-option label="状态：全部" value="" />
              <el-option label="启用" value="enabled" />
              <el-option label="试用" value="trial" />
              <el-option label="停用" value="disabled" />
            </el-select>
          </div>
          <div class="project-filter-bar__actions">
            <el-button type="primary" class="project-filter-bar__button" @click="applyFilters">查询</el-button>
            <el-button class="project-filter-bar__button" @click="resetFilters">重置</el-button>
          </div>
        </div>

        <el-table :data="pagedTemplates" class="template-table">
          <el-table-column label="模板名称" prop="templateName" min-width="260" />
          <el-table-column label="适用场景" prop="scene" min-width="180" />
          <el-table-column label="更新时间" prop="updatedAt" min-width="120" />
          <el-table-column label="状态" min-width="100">
            <template slot-scope="scope">
              <span :class="['status-pill', statusClass(scope.row.status)]">
                {{ statusLabel(scope.row.status) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="报告项数" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.reportItems.length }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="180" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="openViewDialog(scope.row)">详情</el-button>
              <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="filteredTemplates.length > 0"
          :total="filteredTemplates.length"
          :page.sync="queryForm.pageNum"
          :limit.sync="queryForm.pageSize"
          @pagination="handlePagination"
        />
      </section>

      <el-dialog
        :visible.sync="dialogOpen"
        width="1120px"
        top="5vh"
        append-to-body
        :close-on-click-modal="false"
      >
        <span slot="title" class="dialog-title">{{ dialogTitle }}</span>
        <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="适用场景" prop="scene">
            <el-input v-model="form.scene" placeholder="请输入适用场景" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width: 100%" :disabled="isViewMode">
              <el-option label="启用" value="enabled" />
              <el-option label="试用" value="trial" />
              <el-option label="停用" value="disabled" />
            </el-select>
          </el-form-item>
          <div class="readonly-field">更新时间{{ form.updatedAt || '-' }}</div>

          <div class="items-panel">
            <div class="items-panel__title">报告项清单</div>
            <p class="items-panel__hint">支持按“标题 + 内容”维护报告项，可新增、删除、编辑。</p>

            <div
              v-for="(item, index) in form.reportItems"
              :key="item.itemId"
              class="report-item"
            >
              <div class="report-item__header">
                <span>报告项 {{ index + 1 }}</span>
                <el-button size="mini" :disabled="isViewMode" @click="removeReportItem(index)">删除报告项</el-button>
              </div>
              <el-input
                v-model="item.title"
                :disabled="isViewMode"
                class="report-item__title"
              />
              <el-input
                v-model="item.content"
                type="textarea"
                :rows="5"
                :disabled="isViewMode"
                class="report-item__content"
              />
            </div>
          </div>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button v-if="!isViewMode" @click="appendReportItem">新增报告项</el-button>
          <el-button @click="dialogOpen = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </module-page-shell>
</template>

<script>
import ModulePageShell from '@/components/ModulePageShell'
import cache from '@/plugins/cache'
import { todayString } from '@/views/project/shared/workbench'

const STORAGE_KEY = 'report-template-management-records-v1'

const DEFAULT_TEMPLATES = [
  {
    templateCode: 'RPT-TPL-001',
    templateName: '内部模板_v1.0',
    scene: '标准投资风控',
    status: 'enabled',
    updatedAt: '2026-03-20',
    reportItems: [
      {
        title: '1. 行业风险控制',
        content: '– 行业研究：深入研究目标行业的市场容量、增长潜力、竞争格局及政策环境。\n– 行业周期性分析：行业所处的发展阶段（如导入期、成长期、成熟期、衰退期），避免投资于衰退期行业。\n– 政策敏感性：关注政府对行业的监管政策和扶持力度，避免投资受政策打压的行业。'
      },
      {
        title: '2. 企业风险控制',
        content: '– 财务健康状况：审查融资企业的收入增长率、净利润率、毛利率等指标。\n– 偿债能力：分析资产负债率、流动比率、速动比率等指标。\n– 现金流：确保企业有足够的经营活动现金流支持运营和发展。'
      },
      {
        title: '3. 管理团队风险控制',
        content: '– 核查管理团队稳定性、行业经验与历史履职情况。'
      },
      {
        title: '4. 市场风险控制',
        content: '– 审视产品竞争力、替代风险和客户稳定性。'
      },
      {
        title: '5. 政策与法律风险控制',
        content: '– 核查合规许可、诉讼仲裁及合同履约风险。'
      },
      {
        title: '6. 担保品风险控制',
        content: '– 权属清晰、无争议、可处置性明确，并验证价值与处置路径。'
      }
    ]
  },
  {
    templateCode: 'RPT-TPL-002',
    templateName: '内部模板_地产版_v0.9',
    scene: '地产专项',
    status: 'trial',
    updatedAt: '2026-03-16',
    reportItems: [
      {
        title: '1. 项目区位及销售风险',
        content: '– 核查城市能级、板块供需、售价承压及去化速度。'
      },
      {
        title: '2. 土地及规划条件',
        content: '– 核查土地证照、规划条件、容积率及开发强度。'
      },
      {
        title: '3. 资金监管与账户',
        content: '– 审核预售资金监管、专户归集与拨付条件。'
      },
      {
        title: '4. 建设施工与节点',
        content: '– 审核施工许可证、进度计划与总包履约能力。'
      },
      {
        title: '5. 抵押及担保安排',
        content: '– 审核在建工程抵押、股权质押及连带责任安排。'
      },
      {
        title: '6. 退出路径',
        content: '– 评估销售回款、资产处置及再融资退出方案。'
      }
    ]
  }
]

export default {
  name: 'ReportTemplateManagement',
  components: {
    ModulePageShell
  },
  data() {
    return {
      queryForm: {
        templateName: '',
        scene: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      appliedFilters: {
        templateName: '',
        scene: '',
        status: ''
      },
      templates: [],
      dialogOpen: false,
      dialogMode: 'add',
      form: {},
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        scene: [{ required: true, message: '请输入适用场景', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    filteredTemplates() {
      const nameKeyword = (this.appliedFilters.templateName || '').trim().toLowerCase()
      const sceneKeyword = (this.appliedFilters.scene || '').trim().toLowerCase()
      return this.templates.filter(item => {
        const hitName = !nameKeyword || `${item.templateName || ''}`.toLowerCase().includes(nameKeyword)
        const hitScene = !sceneKeyword || `${item.scene || ''}`.toLowerCase().includes(sceneKeyword)
        const hitStatus = !this.appliedFilters.status || item.status === this.appliedFilters.status
        return hitName && hitScene && hitStatus
      })
    },
    pagedTemplates() {
      const pageNum = Number(this.queryForm.pageNum) || 1
      const pageSize = Number(this.queryForm.pageSize) || 10
      const start = (pageNum - 1) * pageSize
      return this.filteredTemplates.slice(start, start + pageSize)
    },
    dialogTitle() {
      if (this.dialogMode === 'add') {
        return '新增报告模板'
      }
      if (this.dialogMode === 'edit') {
        return '编辑报告模板'
      }
      return '查看报告模板'
    },
    isViewMode() {
      return this.dialogMode === 'view'
    }
  },
  created() {
    this.loadTemplates()
  },
  activated() {
    this.loadTemplates()
  },
  methods: {
    loadTemplates() {
      const cached = cache.local.getJSON(STORAGE_KEY)
      const source = Array.isArray(cached) && cached.length > 0 ? cached : DEFAULT_TEMPLATES
      this.templates = source.map(item => this.normalizeTemplate(item))
      if (!cached) {
        this.persistTemplates()
      }
      this.applyFilters()
      this.handlePagination()
    },
    persistTemplates() {
      cache.local.setJSON(STORAGE_KEY, this.templates)
    },
    normalizeTemplate(template) {
      return {
        templateCode: template.templateCode || `RPT-TPL-${Date.now()}`,
        templateName: template.templateName || '',
        scene: template.scene || '',
        status: template.status || 'enabled',
        updatedAt: template.updatedAt || todayString(),
        reportItems: (template.reportItems || []).map((item, index) => ({
          itemId: item.itemId || `${template.templateCode || 'RPT'}-${index}-${Date.now() + index}`,
          title: item.title || `报告项 ${index + 1}`,
          content: item.content || ''
        }))
      }
    },
    cloneTemplate(template) {
      return JSON.parse(JSON.stringify(template))
    },
    buildNextTemplateCode() {
      const numbers = this.templates.map(item => {
        const matched = `${item.templateCode || ''}`.match(/(\d+)$/)
        return matched ? Number(matched[1]) : 0
      })
      const next = Math.max(0, ...numbers) + 1
      return `RPT-TPL-${String(next).padStart(3, '0')}`
    },
    createDefaultTemplate() {
      const templateCode = this.buildNextTemplateCode()
      return this.normalizeTemplate({
        templateCode,
        templateName: '',
        scene: '',
        status: 'enabled',
        updatedAt: todayString(),
        reportItems: [
          {
            title: '1. 报告项标题',
            content: ''
          }
        ]
      })
    },
    statusLabel(status) {
      if (status === 'enabled') {
        return '启用'
      }
      if (status === 'trial') {
        return '试用'
      }
      return '停用'
    },
    statusClass(status) {
      if (status === 'enabled') {
        return 'status-pill--enabled'
      }
      if (status === 'trial') {
        return 'status-pill--trial'
      }
      return 'status-pill--disabled'
    },
    applyFilters() {
      this.queryForm.pageNum = 1
      this.appliedFilters = { ...this.queryForm }
    },
    resetFilters() {
      this.queryForm = {
        templateName: '',
        scene: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      }
      this.applyFilters()
    },
    handlePagination() {
      const pageSize = Number(this.queryForm.pageSize) || 10
      const totalPages = Math.max(1, Math.ceil(this.filteredTemplates.length / pageSize))
      if (this.queryForm.pageNum > totalPages) {
        this.queryForm.pageNum = totalPages
      }
    },
    openCreateDialog() {
      this.dialogMode = 'add'
      this.form = this.createDefaultTemplate()
      this.dialogOpen = true
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },
    openViewDialog(row) {
      this.dialogMode = 'view'
      this.form = this.cloneTemplate(row)
      this.dialogOpen = true
    },
    openEditDialog(row) {
      this.dialogMode = 'edit'
      this.form = this.cloneTemplate(row)
      this.dialogOpen = true
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },
    appendReportItem() {
      const index = this.form.reportItems.length + 1
      this.form.reportItems.push({
        itemId: `${this.form.templateCode}-${Date.now()}-${index}`,
        title: `${index}. 新增报告项`,
        content: ''
      })
    },
    removeReportItem(index) {
      if (this.form.reportItems.length <= 1) {
        this.$message.warning('至少保留一个报告项')
        return
      }
      this.form.reportItems.splice(index, 1)
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) {
          return
        }
        const payload = this.normalizeTemplate({
          ...this.form,
          updatedAt: todayString()
        })

        if (this.dialogMode === 'add') {
          this.templates.unshift(payload)
          this.$message.success('报告模板新增成功')
        } else {
          this.templates = this.templates.map(item => {
            if (item.templateCode !== payload.templateCode) {
              return item
            }
            return payload
          })
          this.$message.success('报告模板保存成功')
        }

        this.persistTemplates()
        this.dialogOpen = false
        this.applyFilters()
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该报告模板吗？', '提示', { type: 'warning' }).then(() => {
        this.templates = this.templates.filter(item => item.templateCode !== row.templateCode)
        this.persistTemplates()
        this.$message.success('报告模板删除成功')
        this.applyFilters()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/project-filter-bar.scss";
@import "~@/styles/query-list-panel.scss";

.report-template-page {
  display: flex;
  flex-direction: column;
}

.template-table {
  margin-bottom: 12px;
}

.status-pill {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  font-size: 12px;
}

.status-pill--enabled {
  color: #24a148;
  background: #edf8ef;
}

.status-pill--trial {
  color: #1677ff;
  background: #eff6ff;
}

.status-pill--disabled {
  color: #6b7280;
  background: #f3f4f6;
}

.dialog-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}

.readonly-field {
  display: flex;
  align-items: center;
  min-height: 40px;
  margin-bottom: 12px;
  padding: 0 14px;
  border: 1px solid #e4e8ef;
  border-radius: 6px;
  color: #303133;
}

.items-panel {
  padding: 12px;
  border: 1px solid #e4e8ef;
  border-radius: 8px;
}

.items-panel__title {
  font-weight: 600;
  color: #374151;
}

.items-panel__hint {
  margin: 6px 0 12px;
  color: #98a2b3;
  font-size: 13px;
}

.report-item {
  padding: 12px;
  border: 1px solid #e4e8ef;
  border-radius: 8px;
}

.report-item + .report-item {
  margin-top: 12px;
}

.report-item__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
  color: #374151;
  font-weight: 600;
}

.report-item__title {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media screen and (max-width: 768px) {
  .dialog-footer,
  .report-item__header {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
