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

import { ref } from 'vue';

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

import { Button, Modal as AntModal, message, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import { downloadByData } from '#/util/tool';
import CategoryWarehouseCell from '#/views/business/product/_shared/category-warehouse-cell.vue';
import CentralPriceCell from '#/views/business/product/_shared/central-price-cell.vue';
import CentralStockInModal from '#/views/business/product/_shared/central-stock-in-modal.vue';
import DrugDetailModal from '#/views/business/product/_shared/drug-detail-modal.vue';
import DrugFreeShippingCell from '#/views/business/product/_shared/drug-free-shipping-cell.vue';
import ProductInfoCell from '#/views/business/product/_shared/product-info-cell.vue';
import WarehouseDrugPriceModal from '#/views/business/warehouse-drug-management/admin/components/modal.vue';
import BindListModal from '#/views/system/delivery-warehouse-drug/components/bind-list-modal.vue';
import { resolveCentralPrice } from '#/views/system/delivery-warehouse-drug/utils/resolve-central-price';

import {
  deleteMedicalDevice,
  exportMedicalDeviceApi,
  syncMedicalDevicePinyin,
} from './api';
import FormModalDemo from './components/modal.vue';
import ExcelUpload from './components/ExcelUpload.vue';
import CategoryModal from './components/CategoryModal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

/** 医疗器械产品类型 */
const PRODUCT_TYPE = 7;

const hasTopTableDropDownActions = ref(false);
const syncing = ref(false);

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,
  gridOptions,
  gridEvents,
});

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

const [ExcelUploadModal, ExcelUploadModalApi] = useVbenModal({
  connectedComponent: ExcelUpload,
});

const [CategoryModalComp, categoryModalApi] = useVbenModal({
  connectedComponent: CategoryModal,
});

const [BindListModalComp, bindListModalApi] = useVbenModal({
  connectedComponent: BindListModal,
});

const [CentralStockInModalComp, centralStockInModalApi] = useVbenModal({
  connectedComponent: CentralStockInModal,
});

const [WarehousePriceModalComp, warehousePriceModalApi] = useVbenModal({
  connectedComponent: WarehouseDrugPriceModal,
});

const [DrugDetailModalComp, drugDetailModalApi] = useVbenModal({
  connectedComponent: DrugDetailModal,
});

/** 点击药名：打开详情 / 别名维护弹窗 */
function openDrugDetail(row: any) {
  drugDetailModalApi.setData({
    drug_id: row?.id,
    gridApi,
  });
  drugDetailModalApi.open();
}

/** 同步本类型空拼音（首拼/全拼/数字） */
function handleSyncPinyin() {
  AntModal.confirm({
    title: '同步拼音',
    content:
      '将扫描本类型药品中首拼/全拼/数字串为空的记录并自动生成，已有值不会覆盖。确认执行？',
    onOk: async () => {
      syncing.value = true;
      try {
        const res = await syncMedicalDevicePinyin();
        message.success(
          `同步完成：更新 ${Number(res?.updated || 0)} 条，跳过 ${Number(res?.skipped || 0)} 条`,
        );
        gridApi.query();
      } finally {
        syncing.value = false;
      }
    },
  });
}

/**
 * 打开某产品的配送仓绑定列表（带总仓售价供费用封顶/默认平台费）
 * @param autoCreate 为 true 时打开后立刻弹出新增绑定表单
 */
function openBindList(row: any, autoCreate = false) {
  const price = resolveCentralPrice(row);
  bindListModalApi.setData({
    drug_id: row.id,
    drug_name: row.drug_name,
    specification: row.specification,
    image: row.image,
    central_price: price,
    values: row,
    gridApi,
    autoCreate,
  });
  bindListModalApi.open();
}

/** 列上「新增绑定」：打开列表并自动弹出新增表单 */
function openBindCreate(row: any) {
  openBindList(row, true);
}

/** 未入总仓时打开入库弹窗 */
function openStockIn(row: any) {
  if (row.in_central_warehouse) {
    message.info('该药品已在总仓库');
    return;
  }
  centralStockInModalApi.setData({
    drug_id: row.id,
    drug_name: row.drug_name,
    productType: PRODUCT_TYPE,
    values: row,
    gridApi,
  });
  centralStockInModalApi.open();
}

/** 已入库：打开总仓调价弹窗 */
function openCentralPriceAdjust(row: any) {
  const cwd = row.central_warehouse_drug;
  if (!cwd?.id) {
    message.warning('未找到总仓药品记录');
    return;
  }
  warehousePriceModalApi.setData({
    update: true,
    listDrugType: PRODUCT_TYPE,
    gridApi,
    values: {
      id: cwd.id,
      price: cwd.price ?? row.central_price,
      market_price: cwd.market_price ?? row.central_market_price,
    },
  });
  warehousePriceModalApi.open();
}

const openCategoryModal = (row: any) => {
  categoryModalApi.setData({
    row,
    gridApi,
  });
  categoryModalApi.open();
};

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

const deleteApi = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  deleteMedicalDevice({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};

const passApplication = () => {
  exportMedicalDeviceApi().then((res) => {
    downloadByData(res.data, '萧康云医-医疗器械导出.xlsx');
    message.success('导出成功!');
  });
};

const openExcelUploadModal = () => {
  ExcelUploadModalApi.setData({
    gridApi,
  });
  ExcelUploadModalApi.open();
};
</script>

<template>
  <Page auto-content-height title="医疗器械管理">
    <ExcelUploadModal />
    <FormModal />
    <DrugDetailModalComp />
    <CategoryModalComp />
    <BindListModalComp />
    <CentralStockInModalComp />
    <WarehousePriceModalComp />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :flex="false"
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: showModal.bind(null),
            },
            {
              label: '导入',
              type: 'primary',
              icon: 'ix:export-check',
              onClick: openExcelUploadModal.bind(null),
            },
            {
              label: '导出',
              type: 'primary',
              icon: 'mingcute:download-3-fill',
              onClick: passApplication.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
        <Button class="ml-2" :loading="syncing" @click="handleSyncPinyin">
          同步拼音
        </Button>
      </template>
      <template #product_info="{ row }">
        <ProductInfoCell :row="row" @name-click="openDrugDetail" />
      </template>
      <template #category_warehouse="{ row }">
        <CategoryWarehouseCell
          :row="row"
          @category="openCategoryModal"
          @bind="openBindList"
          @bind-create="openBindCreate"
          @stock-in="openStockIn"
        />
      </template>
      <template #central_price="{ row }">
        <CentralPriceCell
          :row="row"
          @adjust="openCentralPriceAdjust"
          @stock-in="openStockIn"
        />
      </template>
      <template #supplier="{ row }">
        {{ row.supplier?.name || row.source }}
      </template>
      <template #is_free_shipping="{ row }">
        <DrugFreeShippingCell :row="row" />
      </template>
      <template #status="{ row }">
        <Tag :color="row.status_color">{{ row.status_txt }}</Tag>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '绑定配送仓',
              type: 'link',
              icon: 'mdi:warehouse',
              size: 'small',
              onClick: openBindList.bind(null, row),
            },
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, row.id),
              },
            },
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
  </Page>
</template>








