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

import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Input,
  InputNumber,
  Radio,
  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;
  is_default?: number;
  sort: number;
  store_id?: number;
}

const props = withDefaults(
  defineProps<{
    modelValue?: SkuItem[];
    /** 当前查看分摊的 SKU（0=单帖，在 PriceConfigModal 中由父组件控制） */
    selectedPriceSkuId?: number;
  }>(),
  {
    modelValue: () => [],
    selectedPriceSkuId: 0,
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: SkuItem[]];
  /** 点击行切换左侧分摊视图 */
  'select-for-price': [skuId: number];
}>();

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: '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_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_default: skuList.value.length === 0 ? 1 : 0,
    sort: skuList.value.length,
    store_id: 0,
  });
  syncToParent();
}

function removeSku(index: number) {
  const removed = skuList.value[index];
  const removedDefault = removed?.is_default === 1;
  const removedId = Number(removed?.id || 0);
  skuList.value.splice(index, 1);
  if (removedDefault && skuList.value.length > 0) {
    skuList.value[0].is_default = 1;
  }
  syncToParent();
  if (removedId > 0 && props.selectedPriceSkuId === removedId) {
    emit('select-for-price', 0);
  }
}

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

function onFieldChange() {
  syncToParent();
}

/** 点击行查看该 SKU 分摊（需已保存有 id） */
function onRowClick(record: SkuItem) {
  const skuId = Number(record.id || 0);
  if (skuId <= 0) {
    return;
  }
  emit('select-for-price', skuId);
}

function customRow(record: SkuItem) {
  const skuId = Number(record.id || 0);
  return {
    class: skuId > 0 && skuId === Number(props.selectedPriceSkuId)
      ? 'sku-row--price-active'
      : '',
    onClick: () => onRowClick(record),
  };
}

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,
      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"
      :custom-row="customRow"
      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贴"
            @click.stop
            @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%"
            @click.stop
            @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%"
            @click.stop
            @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%"
            @click.stop
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'status'">
          <Select
            v-model:value="record.status"
            style="width: 100%"
            @click.stop
            @change="onFieldChange"
          >
            <SelectOption :value="1">上架</SelectOption>
            <SelectOption :value="0">下架</SelectOption>
          </Select>
        </template>
        <template v-else-if="column.key === 'sort'">
          <InputNumber
            v-model:value="record.sort"
            :min="0"
            style="width: 100%"
            @click.stop
            @change="onFieldChange"
          />
        </template>
        <template v-else-if="column.key === 'action'">
          <Button type="link" danger size="small" @click.stop="removeSku(index)">
            <DeleteOutlined />
          </Button>
        </template>
      </template>
    </Table>
    <div v-if="skuList.length === 0" class="sku-empty-tip">
      暂无 SKU，用户端将使用手动输入贴数
    </div>
    <div v-else class="sku-hint">
      点击已保存的 SKU 行可在左侧查看/编辑该规格分摊价
    </div>
  </div>
</template>

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

.sku-empty-tip,
.sku-hint {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

:deep(.sku-row--price-active) {
  background-color: #e6f4ff !important;
  cursor: pointer;
}

:deep(.sku-table .ant-table-row) {
  cursor: pointer;
}
</style>
