<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <ele-pro-table
          ref="tableRef"
          row-key="goodsId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          class="sys-org-table"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @batchMove="openMove"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'goodsName'">
              <a @click="openPreview(`/goods/detail/${record.goodsId}`)">{{
                record.goodsName
              }}</a>
            </template>
            <template v-if="column.key === 'image'">
              <a-image :src="record.image" :width="80" />
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === 0" color="green">已上架</a-tag>
              <a-tag v-if="record.status === 1">已下架</a-tag>
              <a-tag v-if="record.status === 2" color="red">待审核</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此记录吗？"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>

      <!-- 编辑弹窗 -->
      <GoodsEdit v-model:visible="showEdit" :data="current" @done="reload" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { EleProTable, toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import GoodsEdit from './components/goodsEdit.vue';
  import { pageGoods, removeGoods, removeBatchGoods } from '@/api/shop/goods';
  import type { Goods, GoodsParam } from '@/api/shop/goods/model';
  import { getMerchantId, openPreview, openUrl } from "@/utils/common";
  import { useRouter } from 'vue-router';
  const { currentRoute } = useRouter();

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

  // 表格选中数据
  const selection = ref<Goods[]>([]);
  // 当前编辑数据
  const current = ref<Goods | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示批量移动弹窗
  const showMove = ref(false);
  // 加载状态
  const loading = ref(true);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.status = filters.status;
    }
    where.merchantId = getMerchantId();
    return pageGoods({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      width: 90,
      dataIndex: 'goodsId'
    },
    {
      title: '封面图',
      dataIndex: 'image',
      width: 120,
      align: 'center',
      key: 'image'
    },
    {
      title: '课程名称',
      dataIndex: 'goodsName',
      key: 'goodsName'
    },
    {
      title: '课程售价',
      dataIndex: 'price',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'price'
    },
    {
      title: '销量',
      dataIndex: 'sales',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'sales'
    },
    {
      title: '库存',
      dataIndex: 'stock',
      width: 120,
      align: 'center',
      sorter: true,
      key: 'stock'
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      key: 'status'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      width: 120,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

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

  /* 打开编辑弹窗 */
  const openEdit = (row?: Goods) => {
    current.value = row ?? null;
    openUrl(`/goods/add`);
  };

  /* 打开批量移动弹窗 */
  const openMove = () => {
    showMove.value = true;
  };

  /* 删除单个 */
  const remove = (row: Goods) => {
    const hide = message.loading('请求中..', 0);
    removeGoods(row.goodsId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchGoods(selection.value.map((d) => d.goodsId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: Goods) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openUrl(`/booking/goods/add?goodsId=${record.goodsId}`);
      }
    };
  };

  watch(
    currentRoute,
    () => {
      reload();
    },
    { immediate: true }
  );
</script>

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

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