<template>
  <div class="frame-body adaption-frame-body effect-content-form-page">
    <div class="page-card">
      <div class="page-header">
        <div>
          <div class="page-title">考核内容</div>
          <div class="page-subtitle">保留旧版的核心结构：内容基础信息、维度、指标明细和加减分规则。</div>
        </div>
        <div class="page-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" :loading="submitting" @click="submit">保存考核内容</el-button>
        </div>
      </div>

      <div class="page-content">
        <div class="main-panel">
          <div class="panel">
            <div class="panel-title">基础信息</div>
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
              <el-form-item label="内容名称" prop="name">
                <el-input v-model="form.name" maxlength="120" show-word-limit placeholder="请输入考核内容名称" />
              </el-form-item>
              <el-form-item label="评分上限">
                <el-input-number v-model="form.score" :min="1" :max="200" />
              </el-form-item>
              <el-form-item label="内容说明">
                <el-input v-model="form.description" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入考核内容说明" />
              </el-form-item>
            </el-form>
          </div>

          <div class="panel">
            <div class="panel-headline">
              <div class="panel-title">考核维度</div>
              <el-button type="primary" plain @click="appendDimension">新增维度</el-button>
            </div>

            <div v-for="(dimension, dIndex) in form.dimensions" :key="dimension.localId" class="dimension-card">
              <div class="dimension-header">
                <div class="dimension-header-fields">
                  <el-input v-model="dimension.dimensionName" placeholder="维度名称，如：业绩达成" />
                  <el-select v-model="dimension.type" style="width: 160px">
                    <el-option label="定量指标" value="定量指标" />
                    <el-option label="定性指标" value="定性指标" />
                    <el-option label="加分项" value="加分项" />
                    <el-option label="减分项" value="减分项" />
                  </el-select>
                </div>
                <div class="dimension-actions">
                  <el-button text type="primary" @click="appendItem(dIndex)">新增指标</el-button>
                  <el-button text type="danger" @click="removeDimension(dIndex)">删除维度</el-button>
                </div>
              </div>

              <el-table :data="dimension.items" border class="dimension-table">
                <el-table-column label="指标名称" min-width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入指标名称" />
                  </template>
                </el-table-column>
                <el-table-column label="考核标准" min-width="260">
                  <template #default="scope">
                    <el-input v-model="scope.row.standard" type="textarea" :rows="2" placeholder="请输入考核标准" />
                  </template>
                </el-table-column>
                <el-table-column label="门槛值" width="110">
                  <template #default="scope">
                    <el-input-number v-if="isQuantitative(dimension.type)" v-model="scope.row.thresholdValue" :min="0" :controls="false" style="width: 100%" />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="目标值" width="110">
                  <template #default="scope">
                    <el-input-number v-if="isQuantitative(dimension.type)" v-model="scope.row.targetValue" :min="0" :controls="false" style="width: 100%" />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="挑战值" width="110">
                  <template #default="scope">
                    <el-input-number v-if="isQuantitative(dimension.type)" v-model="scope.row.challengeValue" :min="0" :controls="false" style="width: 100%" />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="权重" width="110">
                  <template #default="scope">
                    <el-input-number
                      v-if="supportsWeight(dimension.type)"
                      v-model="scope.row.weight"
                      :min="1"
                      :max="100"
                      :controls="false"
                      style="width: 100%"
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="评分上限" width="120">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.scoreLimit" :min="0" :max="100" :controls="false" style="width: 100%" />
                  </template>
                </el-table-column>
                <el-table-column label="备注" min-width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right">
                  <template #default="scope">
                    <el-button text type="danger" @click="removeItem(dIndex, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div class="dimension-summary">
                <span>指标数：{{ dimension.items.length }}</span>
                <span v-if="supportsWeight(dimension.type)">总权重：{{ sumWeight(dimension.items) }}</span>
                <span>总评分上限：{{ sumScoreLimit(dimension.items) }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="side-panel">
          <div class="panel sticky-panel">
            <div class="panel-title">结构概览</div>
            <div class="summary-row"><span>维度数量</span><strong>{{ form.dimensions.length }}</strong></div>
            <div class="summary-row"><span>指标数量</span><strong>{{ totalItems }}</strong></div>
            <div class="summary-row"><span>加分项上限</span><strong>{{ bonusScore }}</strong></div>
            <div class="summary-row"><span>减分项上限</span><strong>{{ penaltyScore }}</strong></div>
            <div class="summary-row"><span>基础评分上限</span><strong>{{ form.score }}</strong></div>
            <div class="summary-row"><span>理论总分上限</span><strong>{{ form.score + bonusScore }}</strong></div>
            <el-alert
              v-if="bonusScore > 20 || penaltyScore > 20"
              title="加分项或减分项上限超过 20 分，请调整。"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { effectContentGet, effectContentSave } from '@/api/otr/effect/core'

const route = useRoute()
const router = useRouter()
const formRef = ref<ElFormInstance>()
const submitting = ref(false)
const localSeed = ref(1000)

const form = reactive({
  id: '',
  name: '',
  score: 100,
  description: '',
  dimensions: [] as any[],
})

const rules = reactive({
  name: [{ required: true, message: '请输入考核内容名称', trigger: 'blur' }],
})

function nextLocalId() {
  localSeed.value += 1
  return localSeed.value
}

function createItem() {
  return {
    localId: nextLocalId(),
    name: '',
    standard: '',
    thresholdValue: undefined,
    targetValue: undefined,
    challengeValue: undefined,
    weight: 10,
    scoreLimit: 10,
    remark: '',
  }
}

function createDimension() {
  return {
    localId: nextLocalId(),
    dimensionName: '',
    type: '定量指标',
    items: [createItem()],
  }
}

function supportsWeight(type: string) {
  return type === '定量指标' || type === '定性指标'
}

function isQuantitative(type: string) {
  return type === '定量指标'
}

function appendDimension() {
  form.dimensions.push(createDimension())
}

function removeDimension(index: number) {
  form.dimensions.splice(index, 1)
}

function appendItem(index: number) {
  form.dimensions[index].items.push(createItem())
}

function removeItem(dIndex: number, iIndex: number) {
  form.dimensions[dIndex].items.splice(iIndex, 1)
}

function sumWeight(items: any[]) {
  return items.reduce((sum, item) => sum + Number(item.weight || 0), 0)
}

function sumScoreLimit(items: any[]) {
  return items.reduce((sum, item) => sum + Number(item.scoreLimit || 0), 0)
}

const totalItems = computed(() => form.dimensions.reduce((sum, item) => sum + item.items.length, 0))
const bonusScore = computed(() =>
  form.dimensions.filter((item) => item.type === '加分项').reduce((sum, item) => sum + sumScoreLimit(item.items), 0),
)
const penaltyScore = computed(() =>
  form.dimensions.filter((item) => item.type === '减分项').reduce((sum, item) => sum + sumScoreLimit(item.items), 0),
)

function normalizeDimension(raw: any) {
  return {
    localId: nextLocalId(),
    id: raw.id,
    dimensionName: raw.dimensionName || '',
    type: raw.type || '定量指标',
    items: (raw.items || raw.performCheckItemList || []).map((item: any) => ({
      localId: nextLocalId(),
      id: item.id,
      name: item.name || '',
      standard: item.standard || '',
      thresholdValue: item.thresholdValue ?? undefined,
      targetValue: item.targetValue ?? undefined,
      challengeValue: item.challengeValue ?? undefined,
      weight: Number(item.weight || 0),
      scoreLimit: Number(item.scoreLimit || 0),
      remark: item.remark || '',
    })),
  }
}

async function load() {
  const id = String(route.query.id || '')
  if (!id) {
    if (!form.dimensions.length) appendDimension()
    return
  }
  const res: any = await effectContentGet(id)
  const result = res?.result || {}
  form.id = String(result.id || id)
  form.name = result.name || ''
  form.score = Number(result.score || 100)
  form.description = result.description || ''
  form.dimensions = (result.dimensions || []).map(normalizeDimension)
  if (!form.dimensions.length) appendDimension()
}

function validateBusiness() {
  if (!form.dimensions.length) {
    ElMessage.warning('请至少新增一个考核维度')
    return false
  }
  if (bonusScore.value > 20) {
    ElMessage.warning('加分项上限不能超过 20 分')
    return false
  }
  if (penaltyScore.value > 20) {
    ElMessage.warning('减分项上限不能超过 20 分')
    return false
  }
  for (const dimension of form.dimensions) {
    if (!dimension.dimensionName) {
      ElMessage.warning('请填写维度名称')
      return false
    }
    if (!dimension.items.length) {
      ElMessage.warning(`维度“${dimension.dimensionName}”至少需要一个指标`)
      return false
    }
    for (const item of dimension.items) {
      if (!item.name || !item.standard) {
        ElMessage.warning(`维度“${dimension.dimensionName}”下存在未填写完整的指标`)
        return false
      }
      if (isQuantitative(dimension.type)) {
        const quantitativeFields = [item.thresholdValue, item.targetValue, item.challengeValue]
        if (quantitativeFields.some((field) => field === undefined || field === null || field === '')) {
          ElMessage.warning(`维度“${dimension.dimensionName}”下的定量指标必须填写门槛值、目标值和挑战值`)
          return false
        }
      }
    }
  }
  return true
}

async function submit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid || !validateBusiness()) return

  submitting.value = true
  try {
    const payload = {
      id: form.id || undefined,
      name: form.name,
      score: form.score,
      description: form.description,
      dimensions: form.dimensions.map((dimension) => ({
        id: dimension.id,
        dimensionName: dimension.dimensionName,
        type: dimension.type,
        items: dimension.items.map((item: any) => ({
          id: item.id,
          name: item.name,
          standard: item.standard,
          thresholdValue: item.thresholdValue,
          targetValue: item.targetValue,
          challengeValue: item.challengeValue,
          weight: item.weight,
          scoreLimit: item.scoreLimit,
          remark: item.remark,
        })),
      })),
    }
    await effectContentSave(payload)
    ElMessage.success('考核内容已保存')
    router.push('/otr/effect/template')
  } finally {
    submitting.value = false
  }
}

function goBack() {
  router.back()
}

load()
</script>

<style scoped lang="scss">
.effect-content-form-page {
  .page-card {
    background: #fff;
    border-radius: 10px;
    padding: 24px;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #eef2f6;
  }

  .page-title {
    font-size: 22px;
    font-weight: 600;
    color: #111827;
  }

  .page-subtitle {
    margin-top: 6px;
    font-size: 13px;
    color: #6b7280;
  }

  .page-actions {
    display: flex;
    gap: 12px;
  }

  .page-content {
    display: grid;
    grid-template-columns: minmax(0, 2fr) 320px;
    gap: 20px;
  }

  .main-panel,
  .side-panel {
    min-width: 0;
  }

  .panel {
    padding: 20px;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
  }

  .main-panel {
    display: grid;
    gap: 20px;
  }

  .panel-title {
    font-size: 16px;
    font-weight: 600;
    color: #111827;
  }

  .panel-headline {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
  }

  .dimension-card {
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    padding: 16px;
    margin-bottom: 16px;
    background: #fff;
  }

  .dimension-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 12px;
  }

  .dimension-header-fields {
    display: flex;
    gap: 12px;
    flex: 1;
  }

  .dimension-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }

  .dimension-summary {
    display: flex;
    gap: 18px;
    margin-top: 12px;
    color: #6b7280;
    font-size: 13px;
    flex-wrap: wrap;
  }

  .sticky-panel {
    position: sticky;
    top: 16px;
  }

  .summary-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f4f6;
    color: #374151;
  }

  .summary-row strong {
    color: #111827;
  }

  :deep(.el-alert) {
    margin-top: 16px;
  }

  @media (max-width: 1200px) {
    .page-content {
      grid-template-columns: 1fr;
    }

    .dimension-header,
    .page-header {
      flex-direction: column;
      align-items: stretch;
    }

    .dimension-header-fields {
      flex-direction: column;
    }
  }
}
</style>

