<script lang="ts" setup>
import { Descriptions, message } from 'ant-design-vue';

import { updateRegion } from '#/views/system/region/api';
import ConfigSectionHeader from '#/views/system/shared/config-section-header.vue';
import InlineFieldEditor from '#/views/system/process/components/inline-field-editor.vue';

import type { RegionRow } from '../constants';

const props = defineProps<{
  region: RegionRow | null | undefined;
}>();

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

function formatFee(value: unknown) {
  if (value === null || value === undefined || value === '') {
    return '点击设置';
  }
  const num = Number(value);
  return Number.isFinite(num) ? `¥${num.toFixed(2)}` : String(value);
}

async function saveField(payload: Record<string, unknown>) {
  if (!props.region) {
    return;
  }
  await updateRegion({
    id: props.region.id,
    ...payload,
  });
  emit('updated', payload as Partial<RegionRow>);
  message.success('保存成功');
}
</script>

<template>
  <section class="rounded-lg border border-border bg-muted/30 dark:border-gray-700">
    <ConfigSectionHeader class="mb-0 px-4 pt-3" title="地区信息" />

    <div v-if="region" class="px-4 pb-3 pt-1">
      <Descriptions
        bordered
        :column="3"
        size="small"
        class="region-info-descriptions"
      >
        <Descriptions.Item label="级别">地区</Descriptions.Item>
        <Descriptions.Item label="名称">
          <InlineFieldEditor
            :value="region.name"
            label="名称"
            placeholder="请输入名称"
            @save="(val) => saveField({ name: val })"
          />
        </Descriptions.Item>
        <Descriptions.Item label="地区编码">
          {{ region.code || '-' }}
        </Descriptions.Item>
        <Descriptions.Item label="快递费" :span="2">
          <InlineFieldEditor
            type="number"
            :value="region.express_fee"
            label="快递费"
            placeholder="请输入价格"
            :display-formatter="formatFee"
            @save="(val) => saveField({ express_fee: val })"
          />
        </Descriptions.Item>
      </Descriptions>
    </div>
  </section>
</template>

<style scoped>
.region-info-descriptions :deep(.ant-descriptions-view) {
  border-color: hsl(var(--border));
}

.region-info-descriptions :deep(.ant-descriptions-item-label) {
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 0.3);
}

.region-info-descriptions :deep(.ant-descriptions-item-content) {
  color: hsl(var(--foreground));
  background: hsl(var(--card));
}
</style>
