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

import { computed, onMounted, ref, watch } from 'vue';

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

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

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

import { useWarehouseDrugTypeRoute } from '../shared/useWarehouseDrugTypeRoute';
import WarehouseDrugNameCell from '../shared/components/WarehouseDrugNameCell.vue';
import {
  deleteWarehouseDrugManagement,
  getWarehouseExportDataApi,
  updateWarehouseDrugManagementStatusApi
} from './api';
import BindListModalDemo from '#/views/system/delivery-warehouse-drug/components/bind-list-modal.vue';
import { resolveCentralPrice } from '#/views/system/delivery-warehouse-drug/utils/resolve-central-price';

import FormModalDemo from './components/modal.vue';
import ExcelUpload from './components/ExcelUpload.vue';
import SpreadsheetTableConfigModal from './components/SpreadsheetTableConfigModal.vue';
import TcmPriceBatchModal from './components/TcmPriceBatchModal.vue';
import ViewModeFloatButton from './components/ViewModeFloatButton.vue';
import WarehouseDrugExcelView from './components/WarehouseDrugExcelView.vue';
import { formOptions } from './config/search';
import { createGridOptions } from './config/table';
import {
  exportWarehouseListExcel,
  type WarehouseExportRow,
} from './utils/exportWarehousePriceExcel';
import {
  readWarehouseViewMode,
  writeWarehouseViewMode,
} from './utils/warehouseViewModeStorage';
import { canManageSpreadsheetConfig } from './utils/spreadsheetAdminRole';

const userStore = useUserStore();

const { productType, typeLabel } = useWarehouseDrugTypeRoute(
  '/warehouse-drug-management/type/1',
);

const hasTopTableDropDownActions = ref(false);
const viewMode = ref<'excel' | 'list'>('list');

onMounted(() => {
  if (productType.value === 1) {
    viewMode.value = readWarehouseViewMode(productType.value) ?? 'list';
  }
});

watch(viewMode, (mode) => {
  if (productType.value === 1) {
    writeWarehouseViewMode(productType.value, mode);
  }
});

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const gridOptions = computed(() => createGridOptions(productType.value));

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

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

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

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

const [TcmPriceBatchModalComp, TcmPriceBatchModalApi] = useVbenModal({
  connectedComponent: TcmPriceBatchModal,
});

const spreadsheetConfigModalRef = ref<InstanceType<
  typeof SpreadsheetTableConfigModal
> | null>(null);

const excelViewRef = ref<InstanceType<typeof WarehouseDrugExcelView> | null>(
  null,
);

const TCM_PLACEHOLDER_IMAGE =
  'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20250510/cd470ebf97e31c4048ba502ba71b66a3.jpg';

function rowProductImageSrc(row: any) {
  const drug = row?.drug;
  const isChinese = drug?.type === 1;
  if (isChinese) {
    return drug?.image || TCM_PLACEHOLDER_IMAGE;
  }
  return drug?.image || '';
}

/**
 * 打开某药品的配送仓绑定列表/新增
 */
function openBindList(row: Record<string, any>, autoCreate = false) {
  const drug = row?.drug || {};
  const drugId = Number(row?.drug_id || drug?.id || 0);
  if (drugId < 1) {
    message.warning('无法识别药品');
    return;
  }
  bindListModalApi.setData({
    drug_id: drugId,
    drug_name: drug.drug_name || row.drug_name || '',
    specification: drug.specification || '',
    image: drug.image || '',
    // ?? 与 || 混用必须加括号，否则 vue/compiler-sfc 打包报错
    central_price: (resolveCentralPrice(row) ?? Number(row.price || 0)) || null,
    values: row,
    gridApi,
    autoCreate,
  });
  bindListModalApi.open();
}

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

const deleteApi = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  deleteWarehouseDrugManagement({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};
/**
 * 导出：后端 export-data 出 JSON，前端 ExcelJS 生成文件（对齐订单导出）
 */
const passApplication = async () => {
  try {
    const res = await getWarehouseExportDataApi({ type: productType.value });
    const rows = (res?.rows ?? []) as WarehouseExportRow[];
    if (rows.length === 0) {
      message.warning('暂无药品数据');
      return;
    }
    const buffer = await exportWarehouseListExcel(rows, '仓库商品');
    downloadByData(
      buffer,
      '萧康云医-仓库商品导出.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    message.success(`导出成功（${res?.total ?? rows.length} 条）`);
  } catch {
    message.error('导出失败');
  }
};

const openExcelUploadModal = (type = 1) => {
  ExcelUploadModalApi.setData({
    gridApi,
    type,
    uploadType: productType.value,
    passApplication,
  });
  ExcelUploadModalApi.open();
};

const openTcmPriceBatchModal = () => {
  TcmPriceBatchModalApi.setData({
    gridApi,
    productType: productType.value,
  });
  TcmPriceBatchModalApi.open();
};

const updateStatus = (id: number) => {
  updateWarehouseDrugManagementStatusApi(id).then(() => {
    message.success('修改成功!');
    gridApi.query();
  });
};

function openSpreadsheetConfigModal() {
  spreadsheetConfigModalRef.value?.open();
}

function onSpreadsheetConfigSaved() {
  excelViewRef.value?.reloadConfig();
}
</script>

<template>
  <Page auto-content-height :title="typeLabel || '总仓库管理'">
    <ExcelUploadModal />
    <TcmPriceBatchModalComp />
    <FormModal />
    <BindListModal />
    <SpreadsheetTableConfigModal
      v-if="productType === 1"
      ref="spreadsheetConfigModalRef"
      :product-type="productType"
      @saved="onSpreadsheetConfigSaved"
    />
    <ViewModeFloatButton
      v-if="productType === 1"
      v-model="viewMode"
    />
    <div
      v-if="productType === 1 && viewMode === 'excel'"
      class="warehouse-excel-shell"
    >
      <WarehouseDrugExcelView
        ref="excelViewRef"
        :product-type="productType"
        @open-config="openSpreadsheetConfigModal"
      />
    </div>
    <Grid v-if="productType && viewMode === 'list'">
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: showModal.bind(null),
            },
            {
              label: '导入',
              type: 'primary',
              icon: 'ix:export-check',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: openExcelUploadModal.bind(null, 1),
            },
            // 旧「批量修改价格」直传入口已停用，改走「批量改价预览」
            // {
            //   label: '批量修改价格',
            //   type: 'primary',
            //   icon: 'ix:export-check',
            //   // auth: ['超级西（中成）药', 'sys:user:save'],
            //   onClick: openExcelUploadModal.bind(null, 2),
            // },
            {
              label: '批量改价预览',
              type: 'primary',
              icon: 'mdi:file-compare',
              ifShow: () => productType === 1,
              onClick: openTcmPriceBatchModal,
            },
            {
              label: 'Excel 配置',
              type: 'default',
              icon: 'mdi:table-cog',
              ifShow: () =>
                productType === 1 &&
                canManageSpreadsheetConfig(userStore.userInfo),
              onClick: openSpreadsheetConfigModal,
            },
            {
              label: '导出',
              type: 'primary',
              icon: 'mingcute:download-3-fill',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: passApplication.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              // auth: ['超级西（中成）药', 'sys:user:save'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, false),
              },
            },
          ]"
          :flex="false"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <!-- 药名/拼音：搜索命中别名时展示匹配别名（对齐开方） -->
      <template #drug_name="{ row }">
        <WarehouseDrugNameCell :row="row" />
      </template>
      <template #drug_pinyin="{ row }">
        <span>
          {{
            row.matched_alias_pinyin ||
            row.drug?.matched_alias_pinyin ||
            row.drug?.pinyin_simple ||
            '-'
          }}
        </span>
      </template>
      <template #image="{ row }">
        <Image
          v-if="rowProductImageSrc(row)"
          :src="rowProductImageSrc(row)"
          height="30"
          width="30"
        />
      </template>
      <template #instruction="{ row }">
        <div class="div" style="width: 120px; height: 120px; overflow: scroll">
          <Image :src="row.instruction" height="30" width="30" />
        </div>
      </template>
      <template #status="{ row }">
        <Tag :color="row.status === 2 ? 'green' : 'red'">
          {{ row.status === 2 ? '上架' : '下架' }}
        </Tag>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '上架/下架',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              // auth: ['western-medicine', 'sys:role:detail'],
              onClick: updateStatus.bind(null, row.id),
            },
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              // auth: ['western-medicine', 'sys:role:detail'],
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '配送仓绑定',
              type: 'link',
              icon: 'mdi:truck-delivery-outline',
              size: 'small',
              onClick: openBindList.bind(null, row, false),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              // auth: ['western-medicine', 'sys:role:detail'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, row.id),
              },
            },
            // {
            //   label: '编辑',
            //   type: 'link',
            //   icon: 'ant-design:delete-outlined',
            //   size: 'small',
            //   // auth: ['western-medicine', 'sys:role:detail'],
            //   onClick: showModal.bind(null, row, true),
            // },
            // {
            //   label: '删除',
            //   type: 'link',
            //   icon: 'ant-design:delete-outlined',
            //   size: 'small',
            //   // auth: ['western-medicine', 'sys:role:detail'],
            //   popConfirm: {
            //     title: '确定删除吗？',
            //     confirm: deleteApi.bind(null, row.id),
            //   },
            // },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>

<style scoped lang="scss">
.warehouse-excel-shell {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  height: calc(100vh - 180px);
  overflow: hidden;
}
</style>
