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

import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Input,
  InputNumber,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Table,
} from 'ant-design-vue';

export interface SkuItem {
  id?: number;
  _key?: number;
  sku_name: string;
  dose_count: number;
  buy_price?: number;
  sale_price?: number;
  status: number;
  /** 是否包邮：0否 1是 */
  is_free_shipping?: number;
  is_default?: number;
  sort: number;
  store_id?: number;
}

const props = withDefaults(
  defineProps<{
    modelValue?: SkuItem[];
  }>(),
  {
    modelValue: () => [],
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: SkuItem[]];
}>();

const skuList = ref<SkuItem[]>([]);

const columns = [
  { title: '默认', key: 'is_default', width: 70 },
  { title: 'SKU名称', key: 'sku_name', width: 120 },
  { title: '贴数', key: 'dose_count', width: 90 },
  { title: '供货总价', key: 'buy_price', width: 110 },
  { title: '销售总价', key: 'sale_price', width: 110 },
  { title: '状态', key: 'status', width: 90 },
  { title: '是否包邮', key: 'is_free_shipping', width: 130 },
  { title: '排序', key: 'sort', width: 80 },
  { title: '操作', key: 'action', width: 70 },
];

watch(
  () => props.modelValue,
  (val) => {
    skuList.value = (val || []).map((item, index) => ({
      ...item,
      _key: item._key ?? item.id ?? Date.now() + index,
      sort: item.sort ?? index,
      store_id: item.store_id ?? 0,
      status: item.status ?? 1,
      is_free_shipping: item.is_free_shipping ?? 0,
      is_default: item.is_default ?? 0,
      buy_price: item.buy_price ?? 0,
      sale_price: item.sale_price ?? 0,
    }));
  },
  { immediate: true, deep: true },
);

function syncToParent() {
  emit('update:modelValue', [...skuList.value]);
}

function addSku() {
  skuList.value.push({
    _key: Date.now(),
    sku_name: '',
    dose_count: 7,
    buy_price: 0,
    sale_price: 0,
    status: 1,
    is_free_shipping: 0,
    is_default: skuList.value.length === 0 ? 1 : 0,
    sort: skuList.value.length,
    store_id: 0,
  });
  syncToParent();
}

function removeSku(index: number) {
  const removedDefault = skuList.value[index]?.is_default === 1;
  skuList.value.splice(index, 1);
  if (removedDefault && skuList.value.length > 0) {
    skuList.value[0].is_default = 1;
  }
  syncToParent();
}

function setDefault(index: number) {
  skuList.value.forEach((item, i) => {
    item.is_default = i === index ? 1 : 0;
  });
  syncToParent();
}

function onFieldChange() {
  syncToParent();
}

defineExpose({
  getSkusPayload: () => skuList.value,
  setSkus: (skus: SkuItem[]) => {
    skuList.value = (skus || []).map((item, index) => ({
      ...item,
      _key: item._key ?? item.id ?? Date.now() + index,
      sort: item.sort ?? index,
      store_id: item.store_id ?? 0,
      is_default: item.is_default ?? 0,
      is_free_shipping: item.is_free_shipping ?? 0,
      buy_price: item.buy_price ?? 0,
      sale_price: item.sale_price ?? 0,
    }));
    syncToParent();
  },
});
</script>

<template>
  <div class="sku-editor">
    <div class="sku-editor-header">
      <span class="font-medium">SKU 规格（快捷选贴数，价格为套餐总价）</span>
      <Button type="dashed" size="small" @click="addSku">
        <PlusOutlined />
        添加 SKU
      </Button>
    </div>
    <Table
      :columns="columns"
      :data-source="skuList"
      :pagination="false"
      row-key="_key"
      size="small"
      bordered
      class="mt-2 sku-table"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'is_default'">
          <Radio
            :checked="record.is_default === 1"
            @click.stop="setDefault(index)"
          />
        </template>
        <template v-else-if="column.key === 'sku_name'">
          <Input
            v-model:value="record.sku_name"
            placeholder="如 7贴"
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'dose_count'">
          <InputNumber
            v-model:value="record.dose_count"
            :min="1"
            :max="99"
            style="width: 100%"
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'buy_price'">
          <InputNumber
            v-model:value="record.buy_price"
            :min="0"
            :precision="2"
            style="width: 100%"
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'sale_price'">
          <InputNumber
            v-model:value="record.sale_price"
            :min="0"
            :precision="2"
            style="width: 100%"
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'status'">
          <Select
            v-model:value="record.status"
            style="width: 100%"
            @change="onFieldChange"
          >
            <SelectOption :value="1">上架</SelectOption>
            <SelectOption :value="0">下架</SelectOption>
          </Select>
        </template>
        <template v-else-if="column.key === 'is_free_shipping'">
          <RadioGroup
            v-model:value="record.is_free_shipping"
            @change="onFieldChange"
          >
            <Radio :value="0">不包邮</Radio>
            <Radio :value="1">包邮</Radio>
          </RadioGroup>
        </template>
        <template v-else-if="column.key === 'sort'">
          <InputNumber
            v-model:value="record.sort"
            :min="0"
            style="width: 100%"
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'action'">
          <Button type="link" danger size="small" @click="removeSku(index)">
            <DeleteOutlined />
          </Button>
        </template>
      </template>
    </Table>
    <div v-if="skuList.length === 0" class="sku-empty-tip">
      暂无 SKU，用户端将使用手动输入贴数，并按单帖价 × 贴数计价
    </div>
  </div>
</template>

<style scoped>
.sku-editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sku-empty-tip {
  margin-top: 8px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
</style>
