<template>
  <a-drawer v-model:visible="visible" :title="`管理细则 - ${dimension?.dimensionName || ''}`">
    <a-button type="primary" @click="openRuleDrawer()">新增细则</a-button>
    <a-table :data="ruleList" :columns="ruleColumns" row-key="ruleId" style="margin-top: 16px;">
      <template #status="{ record }">
        <a-tag :color="record.status === 0 ? 'green' : 'red'">
          {{ record.status === 0 ? '启用' : '禁用' }}
        </a-tag>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button type="text" @click="openRuleDrawer(record)">编辑</a-button>
          <a-button type="text" status="danger" @click="handleDeleteRule(record.ruleId)">删除</a-button>
        </a-space>
      </template>
    </a-table>
    <RuleDrawer ref="ruleDrawerRef" :dimension="dimension" @success="loadRules" />
  </a-drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import RuleDrawer from './RuleDrawer.vue'
import { deleteRule, getRuleList } from '@/apis/performance-setting'
import type { PerformanceDimension, PerformanceRule } from '@/apis/performance-setting/type'

const visible = ref(false)
const dimension = ref<PerformanceDimension>()
const ruleList = ref<PerformanceRule[]>([])
const ruleDrawerRef = ref()

const ruleColumns = [
  { title: '细则名称', dataIndex: 'ruleName' },
  { title: '描述', dataIndex: 'description' },
  { title: '分数', dataIndex: 'score' },
  { title: '权重', dataIndex: 'weight' },
  { title: '奖金', dataIndex: 'bonus' },
  { title: '状态', slotName: 'status' },
  { title: '操作', slotName: 'action' },
]

const open = (dim: PerformanceDimension) => {
  dimension.value = dim
  visible.value = true
  loadRules()
}

const loadRules = async () => {
  if (!dimension.value) return
  const res = await getRuleList({ dimensionName: dimension.value.dimensionName })
  ruleList.value = res.data || []
}

const openRuleDrawer = (record?: PerformanceRule) => {
  ruleDrawerRef.value.open(record)
}

const handleDeleteRule = async (id: string) => {
  await deleteRule(id)
  loadRules()
}

defineExpose({ open })
</script>
