<template>
  <div class="frame-body adaption-frame-body effect-template-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="周期类型" prop="cycleType">
                <el-radio-group v-model="form.cycleType">
                  <el-radio value="月度">月度</el-radio>
                  <el-radio value="季度">季度</el-radio>
                  <el-radio value="半年度">半年度</el-radio>
                  <el-radio value="年度">年度</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="考核对象可见">
                <div class="visibility-row">
                  <el-checkbox v-model="isOpenScore">评分人的评分</el-checkbox>
                  <el-checkbox v-model="isOpenRemark">评分人的评分说明</el-checkbox>
                </div>
              </el-form-item>
            </el-form>
          </div>

          <div class="panel">
            <div class="panel-headline">
              <div class="panel-title">考核内容</div>
              <div class="content-actions">
                <el-select v-model="selectedContentId" placeholder="请选择考核内容" style="width: 320px" @change="handleContentChange">
                  <el-option
                    v-for="item in contentOptions"
                    :key="item.contentMainId || item.id"
                    :label="item.name"
                    :value="String(item.contentMainId || item.id)"
                  />
                </el-select>
                <el-button type="primary" plain @click="goCreateContent">新建考核内容</el-button>
              </div>
            </div>

            <el-empty v-if="!contentDetail" description="请选择考核内容" />
            <div v-else class="content-preview">
              <div class="content-summary">
                <span>内容名称：{{ contentDetail.name }}</span>
                <span>评分上限：{{ contentDetail.score }} 分</span>
                <span>维度数量：{{ contentDetail.dimensions?.length || 0 }}</span>
              </div>
              <el-table :data="contentPreviewRows" border>
                <el-table-column prop="dimensionName" label="维度" min-width="160" />
                <el-table-column prop="type" label="类型" width="100" />
                <el-table-column prop="name" label="指标名称" min-width="180" />
                <el-table-column prop="standard" label="考核标准" min-width="240" />
                <el-table-column prop="weight" label="权重" width="90" />
                <el-table-column prop="scoreLimit" label="评分上限" width="110" />
              </el-table>
            </div>
          </div>

          <div class="panel">
            <div class="panel-title">考核流程</div>
            <div class="process-grid">
              <div class="process-card">
                <div class="process-header">
                  <span>考核内容确认</span>
                  <el-switch v-model="isContentEdit" />
                </div>
                <div v-if="isContentEdit" class="process-body">
                  <el-radio-group v-model="confirmerMode">
                    <el-radio value="self">考核对象本人</el-radio>
                    <el-radio value="assign">指定成员</el-radio>
                  </el-radio-group>
                  <SelectUser v-if="confirmerMode === 'assign'" v-model="form.confirmerUser" placeholder="请选择确认人" />
                </div>
              </div>

              <div class="process-card">
                <div class="process-header">
                  <span>结果值录入</span>
                  <el-switch v-model="isResultEntry" />
                </div>
                <div v-if="isResultEntry" class="process-body">
                  <el-radio-group v-model="resultEntryMode">
                    <el-radio value="self">考核对象本人</el-radio>
                    <el-radio value="assign">指定成员</el-radio>
                  </el-radio-group>
                  <SelectUser v-if="resultEntryMode === 'assign'" v-model="form.resultEntryUser" placeholder="请选择录入人" />
                </div>
              </div>
            </div>
          </div>

          <div class="panel">
            <div class="panel-headline">
              <div class="panel-title">评分人配置</div>
              <el-button type="primary" plain @click="appendAppraiser">新增评分人</el-button>
            </div>
            <el-table :data="form.appraisers" border>
              <el-table-column label="评分人角色" width="180">
                <template #default="scope">
                  <el-select v-model="scope.row.roleType" style="width: 100%" @change="handleRoleTypeChange(scope.row)">
                    <el-option label="考核对象本人" value="考核对象本人" />
                    <el-option label="直属上级" value="直属上级" />
                    <el-option label="指定成员" value="指定成员" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="评分人" min-width="240">
                <template #default="scope">
                  <span v-if="scope.row.roleType === '考核对象本人'" class="inline-text">系统自动取考核对象本人</span>
                  <SelectUser v-else v-model="scope.row.userId" placeholder="请选择评分人" />
                </template>
              </el-table-column>
              <el-table-column label="权重" width="120">
                <template #default="scope">
                  <el-input-number v-model="scope.row.weight" :min="1" :max="100" :controls="false" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column label="评分可见" width="110">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.scoreVisible" />
                </template>
              </el-table-column>
              <el-table-column label="评分说明可见" width="130">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.remarkVisible" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="90" fixed="right">
                <template #default="scope">
                  <el-button text type="danger" @click="removeAppraiser(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="side-panel">
          <div class="panel sticky-panel">
            <div class="panel-title">模板概览</div>
            <div class="summary-row"><span>关联内容</span><strong>{{ contentDetail?.name || '未选择' }}</strong></div>
            <div class="summary-row"><span>内容满分</span><strong>{{ contentDetail?.score || 0 }}</strong></div>
            <div class="summary-row"><span>评分人数</span><strong>{{ form.appraisers.length }}</strong></div>
            <div class="summary-row"><span>评分总权重</span><strong>{{ totalWeight }}</strong></div>
            <div class="summary-row"><span>内容确认</span><strong>{{ isContentEdit ? '开启' : '关闭' }}</strong></div>
            <div class="summary-row"><span>结果录入</span><strong>{{ isResultEntry ? '开启' : '关闭' }}</strong></div>
            <el-alert
              v-if="totalWeight !== 100 && form.appraisers.length"
              title="评分人权重建议合计为 100%。"
              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 SelectUser from '@/components/SelectUser/SelectUser.vue'
import {
  effectContentGet,
  effectContentList,
  effectTemplateGet,
  effectTemplateSave,
} from '@/api/otr/effect/core'

const route = useRoute()
const router = useRouter()
const formRef = ref<ElFormInstance>()
const submitting = ref(false)
const selectedContentId = ref('')
const contentOptions = ref<any[]>([])
const contentDetail = ref<any>(null)
const localSeed = ref(2000)

const form = reactive({
  id: '',
  name: '',
  cycleType: '月度',
  confirmerUser: undefined as string | number | undefined,
  resultEntryUser: undefined as string | number | undefined,
  appraisers: [] as any[],
})

const isOpenScore = ref(true)
const isOpenRemark = ref(true)
const isContentEdit = ref(false)
const isResultEntry = ref(false)
const confirmerMode = ref<'self' | 'assign'>('self')
const resultEntryMode = ref<'self' | 'assign'>('self')

const rules = reactive({
  name: [{ required: true, message: '请输入考核模板名称', trigger: 'blur' }],
  cycleType: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
})

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

function createAppraiser() {
  return {
    localId: nextLocalId(),
    roleType: '直属上级',
    userId: undefined as string | number | undefined,
    weight: 100,
    scoreVisible: false,
    remarkVisible: false,
  }
}

function normalizeAppraiser(item: any) {
  return {
    localId: nextLocalId(),
    id: item.id,
    roleType: item.roleType || '直属上级',
    userId: item.userId === 0 ? undefined : item.userId,
    weight: Number(item.weight || 0),
    scoreVisible: Number(item.isScoreVisibility || 0) === 1,
    remarkVisible: Number(item.isRemarkVisibility || 0) === 1,
  }
}

function appendAppraiser() {
  form.appraisers.push(createAppraiser())
}

function removeAppraiser(index: number) {
  form.appraisers.splice(index, 1)
}

function handleRoleTypeChange(row: any) {
  if (row.roleType === '考核对象本人') {
    row.userId = undefined
  }
}

async function loadContentOptions() {
  const res: any = await effectContentList({ pageNo: 1, pageSize: 999 })
  const result = res?.result || {}
  contentOptions.value = result.records || result.list || []
}

async function loadContentDetail(id: string | number) {
  if (!id) {
    contentDetail.value = null
    return
  }
  const res: any = await effectContentGet(id)
  const result = res?.result || {}
  contentDetail.value = {
    ...result,
    dimensions: result.dimensions || [],
  }
}

async function handleContentChange(id: string) {
  selectedContentId.value = id
  await loadContentDetail(id)
}

const contentPreviewRows = computed(() => {
  const dimensions = contentDetail.value?.dimensions || []
  return dimensions.flatMap((dimension: any) =>
    (dimension.items || []).map((item: any) => ({
      dimensionName: dimension.dimensionName,
      type: dimension.type,
      name: item.name,
      standard: item.standard,
      weight: item.weight ?? '-',
      scoreLimit: item.scoreLimit ?? '-',
    })),
  )
})

const totalWeight = computed(() => form.appraisers.reduce((sum, item) => sum + Number(item.weight || 0), 0))

async function load() {
  await loadContentOptions()
  const id = String(route.query.id || '')
  if (!id) {
    if (!form.appraisers.length) appendAppraiser()
    return
  }

  const res: any = await effectTemplateGet(id)
  const result = res?.result || {}
  form.id = String(result.id || id)
  form.name = result.name || ''
  form.cycleType = result.cycleType || '月度'
  isOpenScore.value = Number(result.isOpenScore || 0) === 1
  isOpenRemark.value = Number(result.isOpenRemark || 0) === 1
  isContentEdit.value = Number(result.isContentEdit || 0) === 1
  isResultEntry.value = Number(result.isResultEntry || 0) === 1

  confirmerMode.value = result.confirmerUser === 0 || result.confirmerUser === '0' || !result.confirmerUser ? 'self' : 'assign'
  resultEntryMode.value = result.resultEntryUser === 0 || result.resultEntryUser === '0' || !result.resultEntryUser ? 'self' : 'assign'
  form.confirmerUser = confirmerMode.value === 'assign' ? result.confirmerUser : undefined
  form.resultEntryUser = resultEntryMode.value === 'assign' ? result.resultEntryUser : undefined

  const contentId = String(result.contentId || result.contentMainId || '')
  selectedContentId.value = contentId
  if (contentId) {
    await loadContentDetail(contentId)
  }

  form.appraisers = (result.appraisers || []).map(normalizeAppraiser)
  if (!form.appraisers.length) appendAppraiser()
}

function validateBusiness() {
  if (!selectedContentId.value) {
    ElMessage.warning('请选择考核内容')
    return false
  }
  if (isContentEdit.value && confirmerMode.value === 'assign' && !form.confirmerUser) {
    ElMessage.warning('请选择考核内容确认人')
    return false
  }
  if (isResultEntry.value && resultEntryMode.value === 'assign' && !form.resultEntryUser) {
    ElMessage.warning('请选择结果值录入人')
    return false
  }
  if (!form.appraisers.length) {
    ElMessage.warning('请至少配置一个评分人')
    return false
  }
  for (const item of form.appraisers) {
    if (!item.roleType) {
      ElMessage.warning('评分人角色不能为空')
      return false
    }
    if (item.roleType !== '考核对象本人' && !item.userId) {
      ElMessage.warning('请补全评分人信息')
      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,
      cycleType: form.cycleType,
      isOpenScore: isOpenScore.value ? 1 : 0,
      isOpenRemark: isOpenRemark.value ? 1 : 0,
      isContentEdit: isContentEdit.value ? 1 : 0,
      isResultEntry: isResultEntry.value ? 1 : 0,
      contentId: selectedContentId.value,
      contentMainId: selectedContentId.value,
      confirmerUser: isContentEdit.value ? (confirmerMode.value === 'assign' ? form.confirmerUser : 0) : 0,
      resultEntryUser: isResultEntry.value ? (resultEntryMode.value === 'assign' ? form.resultEntryUser : 0) : 0,
      appraisers: form.appraisers.map((item) => ({
        id: item.id,
        roleType: item.roleType,
        userId: item.roleType === '考核对象本人' ? 0 : item.userId,
        weight: item.weight,
        isScoreVisibility: item.scoreVisible ? 1 : 0,
        isRemarkVisibility: item.remarkVisible ? 1 : 0,
      })),
    }
    await effectTemplateSave(payload)
    ElMessage.success('考核模板已保存')
    router.push('/otr/effect/template')
  } finally {
    submitting.value = false
  }
}

function goCreateContent() {
  router.push('/otr/effect/content-form')
}

function goBack() {
  router.back()
}

load()
</script>

<style scoped lang="scss">
.effect-template-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 {
    display: grid;
    gap: 20px;
    min-width: 0;
  }

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

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

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

  .content-actions {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
  }

  .visibility-row {
    display: flex;
    gap: 24px;
    flex-wrap: wrap;
  }

  .content-preview {
    display: grid;
    gap: 16px;
  }

  .content-summary {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    color: #6b7280;
    font-size: 13px;
  }

  .process-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
  }

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

  .process-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }

  .process-body {
    margin-top: 14px;
    display: grid;
    gap: 12px;
  }

  .inline-text {
    color: #6b7280;
    font-size: 13px;
  }

  .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;
    gap: 12px;
    color: #374151;
  }

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

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

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

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

    .process-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>

