<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,
  exportWarehouseDrugManagementStoreApi,
  subscribeApi,
  syncDrugApi,
  syncDrugPriceApi,
  updateWarehouseDrugManagementShopUpdateStatusApi,
  updateWarehouseDrugManagementStoreStatusApi,
} from './api';
import ExcelUpload from './components/ExcelUpload.vue';
import FormModalDemo from './components/modal.vue';
import { formOptions } from './config/search';
import { createGridOptions } from './config/table';

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

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 [ExcelUploadModal, ExcelUploadModalApi] = useVbenModal({
  connectedComponent: ExcelUpload,
});

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();
  });
};
/**
 * 导出
 */
const passApplication = () => {
  // 新标签跳转到 exportWarehouseDrugManagementStoreApi
  exportWarehouseDrugManagementStoreApi().then((res) => {
    // 创建新的URL表示指定的File对象或者Blob对象。
    downloadByData(res.data, '萧康云医-仓库商品导出.xlsx');
    message.success('导出成功!');
  });
};

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

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 || '商城仓库管理'">
    <ExcelUploadModal />
    <FormModal />
    <Grid v-if="productType">
      <template #toolbar-actions>
        <TableAction
          :actions="[
            // {
            //   label: '批量修改价格',
            //   type: 'primary',
            //   icon: 'ix:export-check',
            //   // auth: ['超级西（中成）药', 'sys:user:save'],
            //   onClick: openExcelUploadModal.bind(null, 2),
            // },
            {
              label: '更新总仓库商品（只更新未同步的商品）',
              type: 'primary',
              icon: 'material-symbols:sync-alt',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              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 #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>
