<template>
  <a-modal
    v-model:visible="visible"
    title="细则管理"
    :width="800"
    @before-ok="handleSave"
    @cancel="reset"
  >
    <a-table :data="rules" :columns="columns" row-key="id">
      <template #action="{ record }">
        <a-space>
          <a-button type="text" @click="RuleDrawerRef?.openUpdate(record.id)">
            编辑
          </a-button>
          <a-button type="text" status="danger" @click="handleDelete(record.id)">
            删除
          </a-button>
        </a-space>
      </template>
    </a-table>

    <a-button type="primary" @click="RuleDrawerRef?.openAdd()">
      <icon-plus /> 新增细则
    </a-button>
  </a-modal>

  <RuleDrawer ref="RuleDrawerRef" @success="load" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import RuleDrawer from './RuleDrawer.vue'
import { deleteRule, getRuleList } from '@/apis/performance'
import type { RuleResp } from '@/apis/performance/type'
import { Message } from '@arco-design/web-vue'

const visible = ref(false)
const rules = ref<RuleResp[]>([])
const RuleDrawerRef = ref()

const columns = [
  { title: '细则名称', dataIndex: 'name' },
  { title: '评分规则描述', dataIndex: 'ruleDesc' },
  { title: '满分', dataIndex: 'score' },
  { title: '权重', dataIndex: 'weight' },
  { title: '是否加分项', dataIndex: 'isExtra', render: ({ record }) => record.isExtra ? '是' : '否' },
  { title: '操作', slotName: 'action' },
]

const open = async (dimensionId: string) => {
  visible.value = true
  rules.value = await getRuleList(dimensionId)
}

const handleDelete = async (id: string) => {
  await deleteRule(id)
  Message.success('删除成功')
  load()
}

const load = async () => {
  // 重新加载规则列表
  rules.value = await getRuleList(dimensionId.value)
}

defineExpose({ open })
</script>
