<template>
  <module-page-shell title="评估任务模板">
    <div class="assessment-task-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--keyword assessment-task-template-page__field--keyword">
            <el-input
              v-model="queryForm.keyword"
              placeholder="模板ID/模板名称/版本/适用范围"
              clearable
            />
          </div>
          <div class="project-filter-bar__field project-filter-bar__field--narrow">
            <el-select v-model="queryForm.status" placeholder="状态：全部" clearable>
              <el-option label="状态：全部" value="" />
              <el-option label="启用" value="enabled" />
              <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="模板ID" prop="templateCode" min-width="140" />
          <el-table-column label="模板名称" prop="templateName" min-width="220" />
          <el-table-column label="版本" prop="version" min-width="90" />
          <el-table-column label="适用范围" prop="scope" min-width="180" />
          <el-table-column label="状态" min-width="100">
            <template slot-scope="scope">
              <span :class="['status-pill', scope.row.status === 'enabled' ? 'status-pill--enabled' : 'status-pill--disabled']">
                {{ statusLabel(scope.row.status) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updatedAt" min-width="120" />
          <el-table-column label="评估项数" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.items.length }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="220" 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="toggleStatus(scope.row)">
                {{ scope.row.status === 'enabled' ? '停用' : '启用' }}
              </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="1140px"
        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="version">
            <el-input v-model="form.version" placeholder="请输入版本" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="适用范围" prop="scope">
            <el-input v-model="form.scope" 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="disabled" />
            </el-select>
          </el-form-item>

          <div class="items-panel">
            <div class="items-panel__title">评估项表格（可编辑，可新增行列）</div>
            <div class="items-table">
              <div class="items-table__head" :style="itemsTableGridStyle">
                <div class="col-seq">序号</div>
                <div class="col-question">问题</div>
                <div class="col-answer">解答</div>
                <div class="col-judge">评估师评定</div>
                <div class="col-score">评分/10分制</div>
                <div
                  v-for="column in form.extraColumns"
                  :key="column.key"
                  class="col-extra"
                >
                  <el-input
                    v-if="!isViewMode"
                    v-model="column.label"
                    placeholder="新增列标题"
                  />
                  <span v-else>{{ column.label }}</span>
                </div>
                <div class="col-action">操作</div>
              </div>
              <div
                v-for="(item, index) in form.items"
                :key="item.rowId"
                class="items-table__row"
                :style="itemsTableGridStyle"
              >
                <el-input v-model="item.seq" class="col-seq" :disabled="isViewMode" />
                <el-input v-model="item.question" class="col-question" :disabled="isViewMode" />
                <el-input v-model="item.answer" class="col-answer" :disabled="isViewMode" />
                <el-input v-model="item.judgement" class="col-judge" :disabled="isViewMode" />
                <el-input v-model="item.score" class="col-score" :disabled="isViewMode" />
                <el-input
                  v-for="column in form.extraColumns"
                  :key="`${item.rowId}-${column.key}`"
                  v-model="item.extraValues[column.key]"
                  class="col-extra"
                  :disabled="isViewMode"
                />
                <div class="col-action">
                  <el-button size="mini" :disabled="isViewMode" @click="removeItem(index)">删除行</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <template v-if="!isViewMode">
            <el-button @click="appendRow">新增行</el-button>
            <el-button @click="appendColumn">新增列</el-button>
          </template>
          <el-button @click="dialogOpen = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="submitForm">
            {{ dialogMode === 'add' ? '新增' : '保存' }}
          </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 = 'assessment-task-template-records-v1'

const DEFAULT_ITEMS_A = [
  { seq: '1.', question: '政策监管力度', answer: '', judgement: '', score: '' },
  { seq: '2.', question: '政策扶持力度', answer: '', judgement: '', score: '' },
  { seq: '3.', question: '项目发展阶段', answer: '', judgement: '', score: '' },
  { seq: '10', question: '评估师总结', answer: '', judgement: '', score: '' }
]

const DEFAULT_ITEMS_B = [
  { seq: '1.', question: '市场容量', answer: '', judgement: '', score: '' },
  { seq: '2.', question: '政策扶持力度', answer: '', judgement: '', score: '' },
  { seq: '3.', question: '项目发展阶段', answer: '', judgement: '', score: '' },
  { seq: '10', question: '评估师总结', answer: '', judgement: '', score: '' }
]

const DEFAULT_TEMPLATES = [
  {
    templateCode: 'TPL-001',
    templateName: '标准风控评估模板',
    version: 'v1.0',
    scope: '通用投资风控',
    status: 'enabled',
    updatedAt: '2026-04-01',
    items: DEFAULT_ITEMS_A
  },
  {
    templateCode: 'TPL-002',
    templateName: '地产专项评估模板',
    version: 'v0.9',
    scope: '地产项目',
    status: 'disabled',
    updatedAt: '2026-03-18',
    items: DEFAULT_ITEMS_B
  }
]

export default {
  name: 'AssessmentTaskTemplate',
  components: {
    ModulePageShell
  },
  data() {
    return {
      queryForm: {
        keyword: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      appliedFilters: {
        keyword: '',
        status: ''
      },
      templates: [],
      dialogOpen: false,
      dialogMode: 'add',
      form: {},
      rules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        version: [{ required: true, message: '请输入版本', trigger: 'blur' }],
        scope: [{ required: true, message: '请输入适用范围', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    filteredTemplates() {
      const keyword = (this.appliedFilters.keyword || '').trim().toLowerCase()
      return this.templates.filter(item => {
        const hitKeyword = !keyword || [
          item.templateCode,
          item.templateName,
          item.version,
          item.scope
        ].some(field => `${field || ''}`.toLowerCase().includes(keyword))
        const hitStatus = !this.appliedFilters.status || item.status === this.appliedFilters.status
        return hitKeyword && 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'
    },
    itemsTableGridStyle() {
      const extraCount = Array.isArray(this.form.extraColumns) ? this.form.extraColumns.length : 0
      return {
        gridTemplateColumns: `80px 1.2fr 1.2fr 1.2fr 0.8fr ${extraCount > 0 ? `repeat(${extraCount}, 1fr) ` : ''}90px`
      }
    }
  },
  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) {
      const extraColumns = (template.extraColumns || []).map((column, index) => ({
        key: column.key || `extra-${index + 1}`,
        label: column.label || `新增列${index + 1}`
      }))
      return {
        templateCode: template.templateCode,
        templateName: template.templateName || '',
        version: template.version || 'v1.0',
        scope: template.scope || '',
        status: template.status || 'enabled',
        updatedAt: template.updatedAt || todayString(),
        extraColumns,
        items: (template.items || []).map((item, index) => ({
          rowId: item.rowId || `${template.templateCode || 'TPL'}-${index}-${Date.now() + index}`,
          seq: item.seq || `${index + 1}.`,
          question: item.question || '',
          answer: item.answer || '',
          judgement: item.judgement || '',
          score: item.score || '',
          extraValues: extraColumns.reduce((values, column) => {
            values[column.key] = item.extraValues && typeof item.extraValues[column.key] !== 'undefined'
              ? item.extraValues[column.key]
              : ''
            return values
          }, {})
        }))
      }
    },
    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 `TPL-${String(next).padStart(3, '0')}`
    },
    createDefaultTemplate() {
      const code = this.buildNextTemplateCode()
      return this.normalizeTemplate({
        templateCode: code,
        templateName: '',
        version: 'v1.0',
        scope: '通用投资风控',
        status: 'enabled',
        updatedAt: todayString(),
        extraColumns: [],
        items: this.buildDefaultItems(code)
      })
    },
    buildDefaultItems(code) {
      return DEFAULT_ITEMS_A.map((item, index) => ({
        rowId: `${code}-${index}-${Date.now() + index}`,
        seq: item.seq,
        question: item.question,
        answer: '',
        judgement: '',
        score: '',
        extraValues: {}
      }))
    },
    statusLabel(status) {
      return status === 'enabled' ? '启用' : '停用'
    },
    applyFilters() {
      this.queryForm.pageNum = 1
      this.appliedFilters = { ...this.queryForm }
    },
    resetFilters() {
      this.queryForm = {
        keyword: '',
        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()
        }
      })
    },
    appendRow() {
      const index = this.form.items.length + 1
      this.form.items.push({
        rowId: `${this.form.templateCode}-${Date.now()}-${index}`,
        seq: `${index}.`,
        question: '',
        answer: '',
        judgement: '',
        score: '',
        extraValues: (this.form.extraColumns || []).reduce((values, column) => {
          values[column.key] = ''
          return values
        }, {})
      })
    },
    appendColumn() {
      if (!Array.isArray(this.form.extraColumns)) {
        this.$set(this.form, 'extraColumns', [])
      }
      const nextIndex = this.form.extraColumns.length + 1
      const column = {
        key: `extra-${Date.now()}-${nextIndex}`,
        label: `新增列${nextIndex}`
      }
      this.form.extraColumns.push(column)
      this.form.items.forEach(item => {
        if (!item.extraValues) {
          this.$set(item, 'extraValues', {})
        }
        this.$set(item.extraValues, column.key, '')
      })
    },
    removeItem(index) {
      if (this.form.items.length <= 1) {
        this.$message.warning('至少保留一条评估项')
        return
      }
      this.form.items.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()
      })
    },
    toggleStatus(row) {
      const nextStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
      this.templates = this.templates.map(item => {
        if (item.templateCode !== row.templateCode) {
          return item
        }
        return {
          ...item,
          status: nextStatus,
          updatedAt: todayString()
        }
      })
      this.persistTemplates()
      this.$message.success(nextStatus === 'enabled' ? '模板已启用' : '模板已停用')
      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";

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

.assessment-task-template-page__field--keyword {
  flex: 0 1 300px;
  max-width: 340px;
  min-width: 220px;
}

.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--disabled {
  color: #6b7280;
  background: #f3f4f6;
}

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

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

.items-panel__title {
  margin-bottom: 10px;
  font-weight: 600;
  color: #374151;
}

.items-table {
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-x: auto;
}

.items-table__head,
.items-table__row {
  display: grid;
  gap: 10px;
  align-items: center;
  min-width: 860px;
}

.items-table__head {
  padding: 0 8px;
  color: #6b7280;
  font-size: 13px;
}

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

@media screen and (max-width: 1200px) {
  .items-table__head,
  .items-table__row {
    grid-template-columns: 80px 1fr;
  }

  .items-table__head .col-answer,
  .items-table__head .col-judge,
  .items-table__head .col-score,
  .items-table__head .col-action {
    display: none;
  }

  .items-table__row .col-answer,
  .items-table__row .col-judge,
  .items-table__row .col-score,
  .items-table__row .col-action {
    grid-column: 1 / -1;
  }
}

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