<script lang="ts" setup>
import type { SpreadsheetConfigJson } from '../config/spreadsheetDefaults';

import { ref } from 'vue';

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

import { Checkbox, Input, message, Space } from 'ant-design-vue';

import SpreadsheetFormulaField from './SpreadsheetFormulaField.vue';

const props = defineProps<{
  config: SpreadsheetConfigJson;
}>();

const emit = defineEmits<{
  save: [config: SpreadsheetConfigJson];
}>();

const title = ref('');
const fieldId = ref('');
const formula = ref('');
const filterable = ref(true);
const headerColor = ref<string | undefined>();

const [Modal, modalApi] = useVbenModal({
  title: '新增一列',
  class: 'w-[560px]',
  onConfirm: handleSave,
});

function resetForm() {
  title.value = '';
  fieldId.value = '';
  formula.value = '';
  filterable.value = true;
  headerColor.value = undefined;
}

function nextColIndex() {
  const cols = [
    ...props.config.headers.map((h) => h.col),
    ...props.config.columns.map((c) => c.col),
  ];
  return cols.length > 0 ? Math.max(...cols) + 1 : 0;
}

function buildConfig(): SpreadsheetConfigJson {
  const col = nextColIndex();
  const fid =
    fieldId.value.trim() ||
    `col_${col}_${Date.now().toString(36).slice(-4)}`;
  const fname = title.value.trim();

  return {
    ...props.config,
    headers: [
      ...props.config.headers,
      {
        title: fname,
        col,
        fieldId: fid,
        filterable: filterable.value,
        headerColor: headerColor.value,
      },
    ],
    columns: [
      ...props.config.columns,
      {
        fieldId: fid,
        fieldName: fname,
        cellType: 'formula',
        col,
        editable: false,
        formula: formula.value,
      },
    ],
  };
}

async function handleSave() {
  if (!title.value.trim()) {
    message.error('请输入列名');
    return false;
  }
  if (!formula.value.trim()) {
    message.error('请选择公式或手写表达式');
    return false;
  }
  emit('save', buildConfig());
  resetForm();
  return true;
}

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

<template>
  <Modal>
    <Space direction="vertical" style="width: 100%">
      <div>
        <div class="field-label">列名</div>
        <Input v-model:value="title" placeholder="如：毛利率" />
      </div>
      <div>
        <div class="field-label">字段 ID（可选）</div>
        <Input v-model:value="fieldId" placeholder="自动生成" />
      </div>

      <SpreadsheetFormulaField
        v-model="formula"
        :headers="config.headers"
        :show-preview="true"
      />

      <Checkbox v-model:checked="filterable">可筛选</Checkbox>
    </Space>
  </Modal>
</template>

<style scoped>
.field-label {
  font-size: 12px;
  color: #86909c;
  margin-bottom: 4px;
}
</style>
