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

import { computed, ref } from 'vue';

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

import { Button, Image, message, Switch, 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 {
  checkSubscribeApi,
  deleteWarehouseDrugManagementStore,
  getStoreExportDataApi,
  subscribeApi,
  syncDrugApi,
  syncDrugPriceApi,
  updateWarehouseDrugManagementShopUpdateStatusApi,
  updateWarehouseDrugManagementStoreStatusApi,
} from './api';
import StorePriceBatchModal from './components/StorePriceBatchModal.vue';
import FormModalDemo from './components/modal.vue';
import { formOptions } from './config/search';
import { createGridOptions } from './config/table';
import {
  exportStoreListExcel,
  type StoreExportRow,
} from './utils/exportStorePriceExcel';

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

const hasTopTableDropDownActions = ref(false);

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 [StorePriceBatchModalComp, StorePriceBatchModalApi] = useVbenModal({
  connectedComponent: StorePriceBatchModal,
});

const showModal = (data: any = {}, isUpdate = false) => {
  // 绑定配送仓：直接提示不可改价，不打开编辑
  if (isUpdate && Number(data?.has_delivery_warehouse) === 1) {
    message.warning('该商品不可改价');
    return;
  }
  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);
  }
  deleteWarehouseDrugManagementStore({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};

/** 打开门店批量改价预览（ExcelJS 解析后确认） */
const openStorePriceBatchModal = () => {
  StorePriceBatchModalApi.setData({
    gridApi,
    productType: productType.value,
  });
  StorePriceBatchModalApi.open();
};

/** 门店导出：export-data + ExcelJS */
const exportStoreDrugs = async () => {
  try {
    const res = await getStoreExportDataApi({ type: productType.value });
    const rows = (res?.rows ?? []) as StoreExportRow[];
    if (rows.length === 0) {
      message.warning('暂无药品数据');
      return;
    }
    const buffer = await exportStoreListExcel(rows, '门店仓库');
    downloadByData(
      buffer,
      '萧康云医-门店仓库商品导出.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    message.success(`导出成功（${res?.total ?? rows.length} 条）`);
  } catch {
    message.error('导出失败');
  }
};

const syncDrugs = () => {
  syncDrugApi({ type: productType.value }).then(() => {
    message.success('同步成功!');
    gridApi.query();
  });
};

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

const updateWarehouseDrugManagementShopUpdateStatus = (id) => {
  updateWarehouseDrugManagementShopUpdateStatusApi(id).then(() => {
    message.success('修改成功!');
    gridApi.query();
  });
};

const syncDrugPrice = () => {
  gridApi.setLoading(true);
  syncDrugPriceApi({ type: productType.value }).then(() => {
    message.success('同步成功!');
    gridApi.setLoading(false);
    gridApi.query();
  });
};

const isSubscribe = ref(true);

const checkSubscribe = () => {
  checkSubscribeApi().then((res) => {
    isSubscribe.value = res;
  });
};

const subscribe = () => {
  subscribeApi().then(() => {
    message.success('操作成功!');
  });
};

checkSubscribe();
</script>

<template>
  <Page auto-content-height :title="typeLabel || '门店仓库管理'">
    <StorePriceBatchModalComp />
    <FormModal />
    <Grid v-if="productType">
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '批量改价预览',
              type: 'primary',
              icon: 'mdi:file-compare',
              onClick: openStorePriceBatchModal,
            },
            {
              label: '导出',
              type: 'primary',
              icon: 'lucide:download',
              onClick: exportStoreDrugs,
            },
            {
              label: '更新总仓库商品（只更新未同步的商品）',
              type: 'primary',
              icon: 'material-symbols:sync-alt',
              onClick: syncDrugs,
            },
            {
              label: '同步总仓库的价格',
              type: 'primary',
              icon: 'material-symbols:sync-alt',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: syncDrugPrice,
            },
            {
              label: '订阅仓库价格',
              type: 'primary',
              ifShow: !isSubscribe,
              icon: 'gridicons:reader-following',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: subscribe,
            },
          ]"
          :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
          :src="
            row.drug?.image ||
            'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20250510/cd470ebf97e31c4048ba502ba71b66a3.jpg'
          "
          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>-->
        <Switch
          :checked="row.status"
          :checked-value="2"
          :un-checked-value="1"
          checked-children="上架"
          un-checked-children="下架"
          @click="updateStatus(row.id)"
        />
      </template>
      <template #price_lock="{ row }">
        <Tag v-if="Number(row.has_delivery_warehouse) === 1" color="orange">
          不可改价
        </Tag>
        <span v-else class="text-slate-400">可改价</span>
      </template>
      <template #is_shop="{ row }">
        <Switch
          :checked="row.is_shop"
          :checked-value="2"
          :un-checked-value="1"
          checked-children="上架"
          un-checked-children="下架"
          @click="updateWarehouseDrugManagementShopUpdateStatus(row.id)"
        />
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label:
                Number(row.has_delivery_warehouse) === 1
                  ? '不可改价'
                  : '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              disabled: Number(row.has_delivery_warehouse) === 1,
              onClick: showModal.bind(null, row, true),
            },
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
  </Page>
</template>
