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

import {
  Button,
  Image,
  Input,
  InputNumber,
  message,
  Select,
  Table,
} from 'ant-design-vue';

import {
  getDrugCommissionCopyFromApi,
  getDrugCommissionListApi,
  salespersonListApi,
  type DrugCommissionListItem,
} from '#/views/business/store/settings/api';

export interface DrugCommissionRow extends DrugCommissionListItem {}

const props = defineProps<{
  salespersonId?: number;
  excludeSalespersonId?: number;
}>();

const keyword = ref('');
const loading = ref(false);
const items = ref<DrugCommissionRow[]>([]);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const editingDrugId = ref<number | null>(null);
const dirtyMap = ref<Record<number, string>>({});

const salespersonOptions = ref<{ label: string; value: number }[]>([]);
const selectedCopyFromId = ref<number | undefined>();

const columns = [
  { title: '药品', key: 'drug_info', width: 280 },
  { title: '供货价', dataIndex: 'buy_price', width: 90, align: 'right' as const },
  { title: '售价', dataIndex: 'price', width: 90, align: 'right' as const },
  { title: '分成(元/件)', key: 'commission', width: 120, align: 'right' as const },
];

function formatMoney(val: string | number) {
  const n = Number(val);
  return Number.isFinite(n) ? `¥${n.toFixed(2)}` : '-';
}

function mergeRowCommission(row: DrugCommissionRow): DrugCommissionRow {
  const dirty = dirtyMap.value[row.drug_id];
  return dirty !== undefined ? { ...row, commission: dirty } : row;
}

async function loadList() {
  loading.value = true;
  try {
    const res = await getDrugCommissionListApi({
      salesperson_id: props.salespersonId || 0,
      keyword: keyword.value,
      page: page.value,
      pageSize: pageSize.value,
    });
    items.value = (res?.items || []).map((row) => mergeRowCommission(row));
    total.value = res?.total || 0;
  } finally {
    loading.value = false;
  }
}

async function loadSalespersonOptions() {
  const res = await salespersonListApi();
  const list = res?.items || [];
  salespersonOptions.value = list
    .filter((sp: any) => Number(sp.id) !== Number(props.excludeSalespersonId || 0))
    .map((sp: any) => ({
      label: sp.nick_name || sp.phone || `推广员#${sp.id}`,
      value: Number(sp.id),
    }));
}

function onPageChange(p: number) {
  page.value = p;
  loadList();
}

function startEdit(drugId: number) {
  editingDrugId.value = drugId;
}

function finishEdit(record: DrugCommissionRow) {
  const val = String(record.commission ?? '0');
  dirtyMap.value[record.drug_id] = val;
  editingDrugId.value = null;
}

function applyCommissionItems(
  commissionItems: { drug_id: number; commission: string }[],
) {
  commissionItems.forEach((item) => {
    dirtyMap.value[item.drug_id] = String(item.commission ?? '0');
  });
  items.value = items.value.map((row) => mergeRowCommission(row));
  message.success(`已复制 ${commissionItems.length} 条药品分成`);
}

function getDirtyItems(): { drug_id: number; commission: string }[] {
  return Object.entries(dirtyMap.value).map(([drugId, commission]) => ({
    drug_id: Number(drugId),
    commission,
  }));
}

function resetDirty() {
  dirtyMap.value = {};
  selectedCopyFromId.value = undefined;
}

async function onCopyFromSelect(id: number | undefined) {
  if (!id) return;
  try {
    const res = await getDrugCommissionCopyFromApi(id);
    applyCommissionItems(res?.items || []);
  } catch {
    message.error('复制失败');
  } finally {
    selectedCopyFromId.value = undefined;
  }
}

const dirtyCount = computed(() => Object.keys(dirtyMap.value).length);

watch(
  () => props.salespersonId,
  () => {
    page.value = 1;
    resetDirty();
    loadList();
  },
  { immediate: true },
);

watch(
  () => props.excludeSalespersonId,
  () => {
    loadSalespersonOptions();
  },
);

onMounted(() => {
  loadSalespersonOptions();
});

defineExpose({
  getDirtyItems,
  resetDirty,
  loadList,
  applyCommissionItems,
});
</script>

<template>
  <div class="salesperson-drug-editor">
    <div class="mb-3 flex flex-wrap items-center gap-2">
      <Input
        v-model:value="keyword"
        allow-clear
        placeholder="药品名称 / 拼音首拼"
        style="width: 220px"
        @press-enter="loadList"
      />
      <Button type="primary" @click="loadList">查询</Button>
      <Select
        v-model:value="selectedCopyFromId"
        :options="salespersonOptions"
        allow-clear
        placeholder="复用推广员分成"
        style="width: 200px"
        @change="onCopyFromSelect"
      />
      <span class="text-xs text-gray-500">
        选择已有推广员可一键复制其药品分成（不含中药）；点击「分成」可编辑；待保存
        {{ dirtyCount }} 条
      </span>
    </div>
    <Table
      :columns="columns"
      :data-source="items"
      :loading="loading"
      :pagination="{ current: page, pageSize, total, onChange: onPageChange }"
      :row-key="(r) => r.drug_id"
      :scroll="{ y: 360 }"
      size="small"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'drug_info'">
          <div class="flex items-center gap-2">
            <Image
              v-if="record.image"
              :src="record.image"
              :width="40"
              :height="40"
              class="shrink-0 rounded object-cover"
            />
            <div
              v-else
              class="flex h-10 w-10 shrink-0 items-center justify-center rounded bg-gray-100 text-xs text-gray-400"
            >
              无图
            </div>
            <div class="min-w-0 flex-1">
              <div class="truncate font-medium">{{ record.drug_name }}</div>
              <div v-if="record.pinyin_simple" class="text-xs text-gray-400">
                {{ record.pinyin_simple }}
              </div>
              <div v-if="record.drug_spec" class="truncate text-xs text-gray-500">
                {{ record.drug_spec }}
              </div>
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'commission'">
          <InputNumber
            v-if="editingDrugId === record.drug_id"
            v-model:value="record.commission"
            :min="0"
            :precision="2"
            class="w-full"
            size="small"
            autofocus
            @blur="finishEdit(record)"
            @press-enter="finishEdit(record)"
          />
          <span
            v-else
            class="commission-cell"
            @click="startEdit(record.drug_id)"
          >
            {{ formatMoney(record.commission) }}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'buy_price'">
          {{ formatMoney(record.buy_price) }}
        </template>
        <template v-else-if="column.dataIndex === 'price'">
          {{ formatMoney(record.price) }}
        </template>
      </template>
    </Table>
  </div>
</template>

<style scoped>
.commission-cell {
  display: inline-block;
  min-width: 72px;
  padding: 2px 8px;
  color: #1677ff;
  cursor: pointer;
  border-radius: 4px;
}
.commission-cell:hover {
  background: #e6f4ff;
}
</style>
