<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';

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

import { Button, Image, message, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import {
  deleteSpecialPrescription,
  updateSpecialPrescriptionFreeShipping,
  updateSpecialPrescriptionSkuFreeShipping,
  updateSpecialPrescriptionSkuStatus,
  updateSpecialPrescriptionStatus,
} from './api';
import EditPrescriptionModal from './components/EditPrescriptionModal.vue';
import FreeShippingDoseModal from './components/FreeShippingDoseModal.vue';
import SpecialPrescriptionModal from './components/modal.vue';
import PriceConfigModal from './components/PriceConfigModal.vue';
import { formOptions as searchFormOptions } from './config/search';
import { gridOptions } from './config/table';
import {
  formatFreeShippingThreshold,
  formatListRowName,
  type SpecialPrescriptionListRow,
} from './utils/flattenList';

const hasTopTableDropDownActions = ref(false);
const statusLoadingKey = ref<null | string>(null);
const shippingLoadingKey = ref<null | string>(null);

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: searchFormOptions,
  gridOptions,
  gridEvents,
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: SpecialPrescriptionModal,
});

const [EditPrescriptionModalComp, editPrescriptionModalApi] = useVbenModal({
  connectedComponent: EditPrescriptionModal,
});

const [PriceConfigModalComp, priceConfigModalApi] = useVbenModal({
  connectedComponent: PriceConfigModal,
});

const [FreeShippingDoseModalComp, freeShippingDoseModalApi] = useVbenModal({
  connectedComponent: FreeShippingDoseModal,
});

const showModal = (data = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

const showEditPrescriptionModal = (row: SpecialPrescriptionListRow) => {
  editPrescriptionModalApi.setData({
    values: row,
    gridApi,
  });
  editPrescriptionModalApi.open();
};

const showPriceConfigModal = (row: SpecialPrescriptionListRow) => {
  priceConfigModalApi.setData({
    values: row,
    gridApi,
  });
  priceConfigModalApi.open();
};

/** 打开包邮条件弹窗（无 SKU 特色方专用） */
const openFreeShippingDoseModal = (
  row: SpecialPrescriptionListRow,
  modalMode: 'edit' | 'enable',
) => {
  freeShippingDoseModalApi.setData({
    id: row.id,
    name: row.name,
    free_shipping_min_doses: row.free_shipping_min_doses ?? 0,
    mode: modalMode,
    gridApi,
  });
  freeShippingDoseModalApi.open();
};

/** 是否为无 SKU 的特色方主行 */
const isSpWithoutSku = (row: SpecialPrescriptionListRow) =>
  row.rowType === 'sp' && !row.has_sku;

/** 点击状态 Tag 切换上下架（特色方 / SKU） */
const toggleStatus = async (row: SpecialPrescriptionListRow) => {
  const loadingKey =
    row.rowType === 'sku' ? `sku-status-${row.sku_id}` : `sp-status-${row.id}`;
  if (statusLoadingKey.value === loadingKey) {
    return;
  }
  const newStatus = row.status === 1 ? 0 : 1;
  statusLoadingKey.value = loadingKey;
  try {
    await (row.rowType === 'sku' && row.sku_id
      ? updateSpecialPrescriptionSkuStatus({
          sku_id: row.sku_id,
          status: newStatus,
        })
      : updateSpecialPrescriptionStatus({ id: row.id, status: newStatus }));
    message.success(newStatus === 1 ? '已上架' : '已下架');
    gridApi.query();
  } finally {
    statusLoadingKey.value = null;
  }
};

/** 点击包邮 Tag 切换（特色方无 SKU 开启包邮弹窗 / SKU 子行直接切换） */
const toggleFreeShipping = async (row: SpecialPrescriptionListRow) => {
  if (row.rowType === 'sp' && row.has_sku) {
    return;
  }

  // 无 SKU 特色方：不包邮 → 包邮时打开弹窗设置剂数
  if (isSpWithoutSku(row) && row.is_free_shipping !== 1) {
    openFreeShippingDoseModal(row, 'enable');
    return;
  }

  const loadingKey =
    row.rowType === 'sku' ? `sku-ship-${row.sku_id}` : `sp-ship-${row.id}`;
  if (shippingLoadingKey.value === loadingKey) {
    return;
  }

  shippingLoadingKey.value = loadingKey;
  try {
    if (row.rowType === 'sku' && row.sku_id) {
      const newVal = row.is_free_shipping === 1 ? 0 : 1;
      await updateSpecialPrescriptionSkuFreeShipping({
        sku_id: row.sku_id,
        is_free_shipping: newVal,
      });
      message.success(newVal === 1 ? '已设为包邮' : '已设为不包邮');
    } else {
      // 无 SKU 特色方：包邮 → 不包邮，直接关闭
      await updateSpecialPrescriptionFreeShipping({
        id: row.id,
        is_free_shipping: 0,
        free_shipping_min_doses: row.free_shipping_min_doses ?? 0,
      });
      message.success('已设为不包邮');
    }
    gridApi.query();
  } finally {
    shippingLoadingKey.value = null;
  }
};

const deleteApi = (row?: any) => {
  let ids: (number | string)[] = [];
  if (row) {
    ids.push(typeof row === 'object' ? row.id : row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item: any) => item.id);
  }
  deleteSpecialPrescription({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};
</script>

<template>
  <Page auto-content-height title="特色方管理">
    <FormModal />
    <EditPrescriptionModalComp />
    <PriceConfigModalComp />
    <FreeShippingDoseModalComp />

    <div class="p-4">
      <TableAction
        :actions="[
          {
            label: '新增特色方',
            type: 'primary',
            icon: 'ant-design:plus-outlined',
            onClick: () => showModal({}, false),
          },
        ]"
      />

      <Grid>
        <template #name="{ row }">
          <span :class="{ 'sku-row-name': row.rowType === 'sku' }">
            {{ formatListRowName(row) }}
          </span>
        </template>
        <template #cover="{ row }">
          <Image
            v-if="row.rowType === 'sp' && row.cover_image"
            :height="60"
            :src="row.cover_image"
            :width="60"
            fallback="/static/mine/avatar_1.png"
          />
        </template>

        <template #tags="{ row }">
          <template v-if="row.rowType === 'sp'">
            <Tag v-for="tag in row.tags || []" :key="tag" class="mb-1">
              {{ tag }}
            </Tag>
          </template>
        </template>

        <template #status="{ row }">
          <Tag
            :color="row.status === 1 ? 'success' : 'default'"
            class="cursor-pointer select-none"
            @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? '上架' : '下架' }}
          </Tag>
        </template>

        <template #free_shipping="{ row }">
          <template v-if="row.rowType === 'sp' && row.has_sku">
            <Tag color="default">见 SKU</Tag>
          </template>
          <template
            v-else-if="isSpWithoutSku(row) && row.is_free_shipping === 1"
          >
            <div class="free-shipping-cell">
              <Tag
                class="cursor-pointer select-none"
                color="success"
                @click="toggleFreeShipping(row)"
              >
                包邮
              </Tag>
              <span class="shipping-threshold-text">
                {{ formatFreeShippingThreshold(row.free_shipping_min_doses) }}
              </span>
              <Button
                class="shipping-edit-link"
                size="small"
                type="link"
                @click.stop="openFreeShippingDoseModal(row, 'edit')"
              >
                编辑
              </Button>
            </div>
          </template>
          <template v-else>
            <Tag
              :color="row.is_free_shipping === 1 ? 'success' : 'default'"
              class="cursor-pointer select-none"
              @click="toggleFreeShipping(row)"
            >
              {{ row.is_free_shipping === 1 ? '包邮' : '不包邮' }}
            </Tag>
          </template>
        </template>

        <template #toolbar-actions>
          <Button
            v-if="hasTopTableDropDownActions"
            danger
            type="primary"
            @click="deleteApi()"
          >
            删除
          </Button>
        </template>

        <template #action="{ row }">
          <TableAction
            v-if="row.rowType === 'sp'"
            :actions="[
              {
                label: '编辑',
                onClick: () => showModal(row, true),
              },
              {
                label: '编辑药方',
                ifShow: row.prescription_sub_type === 1,
                onClick: () => showEditPrescriptionModal(row),
              },
              {
                label: '价格配置',
                onClick: () => showPriceConfigModal(row),
              },
              {
                label: '删除',
                color: 'error',
                popConfirm: {
                  title: '确定要删除该特色方吗？',
                  onConfirm: () => deleteApi(row.id),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </div>
  </Page>
</template>

<style scoped>
.sku-row-name {
  padding-left: 16px;
  color: #666;
}

.free-shipping-cell {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
}

.shipping-threshold-text {
  font-size: 12px;
  color: #999;
}

.shipping-edit-link {
  padding: 0 4px;
  height: auto;
  font-size: 12px;
}
</style>
