<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, ImagePreviewGroup, message, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ProductDetail from '#/components/modal/ProductPreview.vue';
import { TableAction } from '#/components/table-action';
import ProductSkuDemo from '#/views/my-gen/sku/components/product-modal.vue';

import { deleteProductApi } from './api';
import FormModalDemo from './components/modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

const hasTopTableDropDownActions = ref(false);

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

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

const [ProductSkuDemoModal, ProductSkuDemoModalApi] = useVbenModal({
  connectedComponent: ProductSkuDemo,
});

const [ProductDetailModal, ProductDetailModalApi] = useVbenModal({
  connectedComponent: ProductDetail,
});

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

const showSkuModal = (data = {}, isUpdate = false) => {
  ProductSkuDemoModalApi.setData({
    // 表单值
    values: data,
    update: isUpdate,
    gridApi,
  });
  ProductSkuDemoModalApi.open();
};

const hasDelete = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  deleteProductApi({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.reload();
  });
};

const showProductDetailModal = (row: any) => {
  ProductDetailModalApi.setData({
    // 表单值
    values: row,
  });
  ProductDetailModalApi.open();
};
</script>

<template>
  <Page auto-content-height title="产品管理">
    <FormModal />
    <ProductDetailModal />
    <ProductSkuDemoModal />
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: showModal.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除吗？',
                confirm: hasDelete.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 16px"> 批量操作 </Button>
          </template>
        </TableAction>
      </template>
      <template #title="{ row }">
        <div
          class="h-20 w-20 flex-shrink-0 overflow-hidden rounded-full"
          style="margin: 0 auto"
        >
          <Image :src="row.cover" class="h-full w-full object-cover" />
        </div>
        <Button type="link" @click="showProductDetailModal(row.id)">
          {{ row.title }}
        </Button>
        <div>
          价格：<span class="font-bold text-red-500">￥{{ row.price }}</span>
        </div>
      </template>
      <template #mall="{ row }">
        <div class="items-center space-x-3">
          <div
            class="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full text-left"
            style="margin: 0 auto"
          >
            <Image
              :src="row.mall.avatar"
              :alt="row.mall.name"
              class="h-full w-full object-cover"
            />
          </div>
          <div>
            <div class="text-sm font-medium text-gray-900 dark:text-white">
              {{ row.mall.name }}
            </div>
            <div class="text-xs text-gray-500 dark:text-gray-400">
              ID: {{ row.mall.id }}
            </div>
          </div>
        </div>
      </template>
      <template #user="{ row }">
        <div class="flex items-center space-x-3">
          <div
            class="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full text-left"
          >
            <Image
              :src="row.user.avatar"
              :alt="row.user.nick_name"
              class="h-full w-full object-cover"
            />
          </div>
          <div>
            <div class="text-sm font-medium text-gray-900 dark:text-white">
              {{ row.user.nick_name }}
            </div>
            <div class="text-xs text-gray-500 dark:text-gray-400">
              ID: {{ row.user.id }}
            </div>
          </div>
        </div>
      </template>
      <template #classification="{ row }">
        <Tag color="#7166f0">{{ row.classification.name }}</Tag>
      </template>
      <template #label="{ row }">
        <Tag
          v-for="(item, index) in row.labels_name"
          :key="index"
          class="mt-3"
          color="#7166f0"
        >
          {{ item }}
        </Tag>
      </template>
      <template #images="{ row }">
        <div class="relative inline-block">
          <ImagePreviewGroup>
            <!-- 只渲染第一张图片，但保留所有图片在循环中（隐藏其他图片） -->
            <Image
              v-for="(item, index) in row.images"
              :key="index"
              :src="item"
              height="30"
              width="30"
              :style="{ display: index === 0 ? 'inline-block' : 'none' }"
            />
          </ImagePreviewGroup>
          <span
            v-if="row.images && row.images.length > 1"
            class="bg-primary absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full text-xs text-white"
          >
            {{ row.images.length }}
          </span>
        </div>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              // auth: ['admin', 'sys:role:detail'],
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '新增sku',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              // auth: ['admin', 'sys:role:detail'],
              onClick: showSkuModal.bind(null, row, false),
            },
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              // auth: ['admin', 'sys:role:detail'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: hasDelete.bind(null, row.id),
              },
            },
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
  </Page>
</template>
