<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 { downloadByData } from '#/util/tool';

import { deleteWesternMedicine, exportWesternMedicineApi } from './api';
import FormModalDemo from './components/modal.vue';
import ExcelUpload from './components/ExcelUpload.vue';
import CategoryModal from './components/CategoryModal.vue';
import MinPriceModal from './components/MinPriceModal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

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 [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 [MinPriceModalComp, minPriceModalApi] = useVbenModal({
  connectedComponent: MinPriceModal,
});

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

const openMinPriceModal = (row: any) => {
  minPriceModalApi.setData({
    id: row.id,
    drugName: row.drug_name,
    min_adjust_price: row.min_adjust_price,
    gridApi,
  });
  minPriceModalApi.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);
  }
  deleteWesternMedicine({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};
/**
 * 西药导出
 */
const passApplication = () => {
  // 新标签跳转到 exportWesternMedicineApi
  exportWesternMedicineApi().then((res) => {
    // 创建新的URL表示指定的File对象或者Blob对象。
    downloadByData(res.data, '萧康云医-西药导出.xlsx');
    message.success('导出成功!');
  });
};

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

<template>
  <Page auto-content-height title="西（中成）药管理">
    <ExcelUploadModal />
    <FormModal />
    <CategoryModalComp />
    <MinPriceModalComp />
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :flex="false"
          :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),
            },
            {
              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),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #image="{ row }">
        <Image :src="row.image" height="30" width="30" />
      </template>
      <template #supplier="{ row }">
        {{ row.supplier?.name || row.source }}
      </template>
      <template #zone="{ row }">
        <a class="text-primary cursor-pointer hover:underline" @click="openCategoryModal(row)">
          {{ row.zone_name || '未设置' }}
        </a>
      </template>
      <template #category="{ row }">
        <a class="text-primary cursor-pointer hover:underline" @click="openCategoryModal(row)">
          {{ row.category_name || '未设置' }}
        </a>
      </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 #is_otc="{ row }">
        <Tag :color="row.is_otc === 0 ? 'red' : 'green'">
          {{ row.is_otc === 0 ? '处方药' : '非处方药' }}
        </Tag>
      </template>
      <template #status="{ row }">
        <Tag :color="row.status_color">{{ row.status_txt }}</Tag>
      </template>
      <template #toolbar-tools></template>
      <template #min_adjust_price="{ row }">
        <a
          class="text-primary cursor-pointer hover:underline"
          @click="openMinPriceModal(row)"
        >
          <span v-if="row.min_adjust_price && row.min_adjust_price > 0">
            ￥{{ Number(row.min_adjust_price).toFixed(2) }}
          </span>
          <span v-else style="color: #999">未设置</span>
        </a>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              // auth: ['western-medicine', 'sys:role:detail'],
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '设置底价',
              type: 'link',
              icon: 'ant-design:dollar-outlined',
              size: 'small',
              onClick: openMinPriceModal.bind(null, row),
            },
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              // auth: ['western-medicine', 'sys:role:detail'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, row.id),
              },
            },
          ]"
          :drop-down-actions="[
            // {
            //   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>
