<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Input,
  message,
  Popconfirm,
  Space,
  Table,
} from 'ant-design-vue';

import {
  createSpreadsheetFormula,
  deleteSpreadsheetFormula,
  listSpreadsheetFormula,
  type SpreadsheetFormulaItem,
  updateSpreadsheetFormula,
} from '#/api/spreadsheet-formula';

const emit = defineEmits<{
  updated: [];
}>();

const items = ref<SpreadsheetFormulaItem[]>([]);
const loading = ref(false);
const editingId = ref<number | null>(null);
const formCode = ref('');
const formName = ref('');
const formDesc = ref('');
const formExpression = ref('');
const formRefSlots = ref('[{"slot":"REF0","label":"参数1"}]');

const [Modal, modalApi] = useVbenModal({
  title: '全局公式库',
  class: 'w-[720px]',
  onOpenChange(isOpen) {
    if (isOpen) void loadList();
  },
});

async function loadList() {
  loading.value = true;
  try {
    items.value = await listSpreadsheetFormula();
  } finally {
    loading.value = false;
  }
}

function resetForm() {
  editingId.value = null;
  formCode.value = '';
  formName.value = '';
  formDesc.value = '';
  formExpression.value = '';
  formRefSlots.value = '[{"slot":"REF0","label":"参数1"}]';
}

function startEdit(item: SpreadsheetFormulaItem) {
  editingId.value = item.id;
  formCode.value = item.code;
  formName.value = item.name;
  formDesc.value = item.description;
  formExpression.value = item.expression_template;
  formRefSlots.value = JSON.stringify(item.ref_slots, null, 2);
}

async function saveForm() {
  let refSlots: { slot: string; label: string }[];
  try {
    refSlots = JSON.parse(formRefSlots.value);
    if (!Array.isArray(refSlots)) throw new Error('invalid');
  } catch {
    message.error('ref_slots 必须是 JSON 数组');
    return;
  }
  try {
    if (editingId.value) {
      await updateSpreadsheetFormula({
        id: editingId.value,
        code: formCode.value,
        name: formName.value,
        description: formDesc.value,
        expression_template: formExpression.value,
        ref_slots: refSlots,
      });
      message.success('已更新');
    } else {
      await createSpreadsheetFormula({
        code: formCode.value,
        name: formName.value,
        description: formDesc.value,
        expression_template: formExpression.value,
        ref_slots: refSlots,
      });
      message.success('已创建');
    }
    resetForm();
    await loadList();
    emit('updated');
  } catch (err) {
    message.error(String(err));
  }
}

async function removeItem(id: number) {
  await deleteSpreadsheetFormula(id);
  message.success('已删除');
  await loadList();
  emit('updated');
}

const columns = computed(() => [
  { title: '编码', dataIndex: 'code', width: 120 },
  { title: '名称', dataIndex: 'name', width: 120 },
  { title: '表达式', dataIndex: 'expression_template' },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
]);

defineExpose({
  open: () => modalApi.open(),
});
</script>

<template>
  <Modal>
    <div class="formula-library">
      <Table
        :columns="columns"
        :data-source="items"
        :loading="loading"
        :pagination="false"
        row-key="id"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <Space>
              <Button size="small" type="link" @click="startEdit(record)">
                编辑
              </Button>
              <Popconfirm title="确认删除？" @confirm="removeItem(record.id)">
                <Button danger size="small" type="link">删除</Button>
              </Popconfirm>
            </Space>
          </template>
        </template>
      </Table>

      <div class="formula-form">
        <Space direction="vertical" style="width: 100%">
          <Input v-model:value="formCode" placeholder="编码 code" />
          <Input v-model:value="formName" placeholder="显示名称" />
          <Input v-model:value="formDesc" placeholder="说明" />
          <Input
            v-model:value="formExpression"
            placeholder="表达式模板，如 =(REF0-REF1)/REF0"
          />
          <Input.TextArea
            v-model:value="formRefSlots"
            :rows="4"
            placeholder='ref_slots JSON，如 [{"slot":"REF0","label":"被减数"}]'
          />
          <Space>
            <Button type="primary" @click="saveForm">
              {{ editingId ? '保存' : '新建' }}
            </Button>
            <Button @click="resetForm">清空</Button>
          </Space>
        </Space>
      </div>
    </div>
  </Modal>
</template>

<style scoped lang="scss">
.formula-library {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.formula-form {
  padding-top: 12px;
  border-top: 1px solid #e5e6eb;
}
</style>
