<template>
  <a-page-header title="积分兑换商品" @back="() => router.go(-1)">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
        v-model:selection="selection"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'productName'">
            <a-space>
              <a-image
                v-if="record.productImage"
                :src="record.productImage"
                :width="50"
                :height="50"
                :preview="false"
                style="object-fit: cover; border-radius: 4px"
              />
              <span class="ele-text-wrap">{{ record.productName }}</span>
            </a-space>
          </template>
          <template v-else-if="column.key === 'pointsPrice'">
            <span class="ele-text-danger">{{ record.pointsPrice }}积分</span>
          </template>
          <template v-else-if="column.key === 'stock'">
            <span v-if="record.stock === -1">不限</span>
            <span v-else>{{ record.stock }}</span>
          </template>
          <template v-else-if="column.key === 'isHot'">
            <a-tag :color="record.isHot ? 'red' : 'default'">
              {{ record.isHot ? '是' : '否' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-switch
              :checked="record.status === 1"
              checkedValue="1"
              uncheckedValue="0"
              @change="(checked: any) => onStatusChange(record, checked)"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定删除该商品？"
                @confirm="onDelete(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <ShopPointsProductEdit
      v-model:visible="showEdit"
      :data="current"
      @done="reload"
    />
  </a-page-header>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { message } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import ShopPointsProductEdit from './components/shopPointsProductEdit.vue';
  import {
    pageShopPointsProduct,
    removeShopPointsProduct,
    updateShopPointsProduct,
    type ShopPointsProduct,
    type ShopPointsProductParam
  } from '@/api/shop/shopPointsProduct';

  const router = useRouter();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<ShopPointsProduct[]>([]);
  // 当前编辑数据
  const current = ref<ShopPointsProduct | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where }) => {
    return pageShopPointsProduct({
      ...where,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    // {
    //   title: 'ID',
    //   dataIndex: 'id',
    //   key: 'id',
    //   align: 'center',
    //   width: 80
    // },
    {
      title: '商品名称',
      key: 'productName',
      minWidth: 200
    },
    {
      title: '所需积分',
      key: 'pointsPrice',
      align: 'center',
      width: 100
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      align: 'center',
      width: 80
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
      align: 'center',
      width: 80
    },
    {
      title: '热销',
      key: 'isHot',
      align: 'center',
      width: 70
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      key: 'sortNumber',
      align: 'center',
      width: 70
    },
    {
      title: '状态',
      key: 'status',
      align: 'center',
      width: 80
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 160
    },
    {
      title: '操作',
      key: 'action',
      width: 140,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 搜索
  const reload = (where?: ShopPointsProductParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  // 打开编辑弹窗
  const openEdit = (row?: ShopPointsProduct) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  // 修改状态
  const onStatusChange = (record: ShopPointsProduct, status: string) => {
    updateShopPointsProduct({
      id: record.id,
      status: parseInt(status)
    })
      .then(() => {
        message.success('状态修改成功');
        reload();
      })
      .catch((e) => {
        message.error(e.message || '修改失败');
        reload();
      });
  };

  // 删除
  const onDelete = (record: ShopPointsProduct) => {
    if (!record.id) return;
    removeShopPointsProduct(record.id)
      .then(() => {
        message.success('删除成功');
        reload();
      })
      .catch((e) => {
        message.error(e.message || '删除失败');
      });
  };

  // 自定义行属性
  const customRow = (record: ShopPointsProduct) => {
    return {
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'ShopPointsProduct'
  };
</script>

<style lang="less" scoped></style>
