<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 {
  deleteSpecialPrescription,
  updateSpecialPrescriptionStatus,
} from './api';
import EditPrescriptionModal from './components/EditPrescriptionModal.vue';
import PriceConfigModal from './components/PriceConfigModal.vue';
import SpecialPrescriptionModal from './components/modal.vue';
import { formOptions as searchFormOptions } from './config/search';
import { gridOptions } from './config/table';

const hasTopTableDropDownActions = ref(false);
const statusLoadingId = ref<number | null>(null);

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

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

const [EditPrescriptionModalComp, editPrescriptionModalApi] = useVbenModal({
  connectedComponent: EditPrescriptionModal,
});

const [PriceConfigModalComp, priceConfigModalApi] = useVbenModal({
  connectedComponent: PriceConfigModal,
});

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

const showEditPrescriptionModal = (row: any) => {
  editPrescriptionModalApi.setData({
    values: row,
    gridApi,
  });
  editPrescriptionModalApi.open();
};

const showPriceConfigModal = (row: any) => {
  priceConfigModalApi.setData({
    values: row,
    gridApi,
  });
  priceConfigModalApi.open();
};

/** 点击状态 Tag 切换上下架 */
const toggleStatus = async (row: any) => {
  if (statusLoadingId.value === row.id) {
    return;
  }
  const newStatus = row.status === 1 ? 0 : 1;
  statusLoadingId.value = row.id;
  try {
    await updateSpecialPrescriptionStatus({ id: row.id, status: newStatus });
    message.success(newStatus === 1 ? '已上架' : '已下架');
    gridApi.query();
  } finally {
    statusLoadingId.value = null;
  }
};

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

<template>
  <Page auto-content-height title="特色方管理">
    <FormModal />
    <EditPrescriptionModalComp />
    <PriceConfigModalComp />

    <div class="p-4">
      <TableAction
        :actions="[
          {
            label: '新增特色方',
            type: 'primary',
            icon: 'ant-design:plus-outlined',
            onClick: () => showModal({}, false),
          },
        ]"
      />

      <Grid>
        <template #cover="{ row }">
          <Image
            v-if="row.cover_image"
            :width="60"
            :height="60"
            :src="row.cover_image"
            :fallback="'/static/mine/avatar_1.png'"
          />
        </template>

        <template #tags="{ row }">
          <Tag v-for="tag in row.tags || []" :key="tag" class="mb-1">
            {{ tag }}
          </Tag>
        </template>

        <template #status="{ row }">
          <Tag
            :color="row.status === 1 ? 'success' : 'default'"
            class="cursor-pointer select-none"
            @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? '上架' : '下架' }}
          </Tag>
        </template>

        <template #toolbar-buttons>
          <Button
            v-if="hasTopTableDropDownActions"
            danger
            type="primary"
            @click="deleteApi()"
          >
            删除
          </Button>
        </template>

        <template #action="{ row }">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: () => showModal(row, true),
              },
              {
                label: '编辑药方',
                ifShow: row.prescription_sub_type === 1,
                onClick: () => showEditPrescriptionModal(row),
              },
              {
                label: '价格配置',
                onClick: () => showPriceConfigModal(row),
              },
              {
                label: '删除',
                color: 'error',
                popConfirm: {
                  title: '确定要删除该特色方吗？',
                  onConfirm: () => deleteApi(row.id),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </div>
  </Page>
</template>
