<template>
  <div class="ele-body ele-body-card">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="orderId"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
            @remove="removeBatch"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'logo'">
            <a-avatar :src="record.logo" size="large" />
          </template>
          <template v-if="column.key === 'name'">
            <div>{{ record.name }}</div>
            <div class="ele-text-placeholder">编号：{{ record.orderId }}</div>
          </template>
          <template v-if="column.key === 'money'">
            <span class="ele-text-danger">
              ￥{{ formatNumber(record.money) }}
            </span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag v-if="record.status === 1" color="green">已上架</a-tag>
            <a-tag v-if="record.status === 0">已下架</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="onDetail(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>
    <!-- 编辑弹窗 -->
    <OrderEdit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type { DatasourceFunction } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import { pageOrder, removeOrder, removeBatchOrder } from '@/api/oa/order';
  import type { Order, OrderParam } from '@/api/oa/order/model';
  import { useUserStore } from '@/store/modules/user';
  import { hasRole } from '@/utils/permission';
  import { Assets } from '@/api/oa/assets/model';
  import OrderEdit from './components/order-edit.vue';
  import { formatNumber } from 'ele-admin-pro/es';

  const userStore = useUserStore();
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  const selection = ref<any[]>();
  // 当前编辑数据
  const current = ref<Order | null>(null);
  const status = ref<number>();
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    where.userId = undefined;
    where.commander = userStore.info?.userId;
    if (where.status != 1) {
      where.status = 0;
    }
    // 订单发起人
    if (hasRole('promoter') || hasRole('user')) {
      where.commander = undefined;
      where.userId = userStore.info?.userId;
    }
    // 管理人员
    if (hasRole('superAdmin') || hasRole('admin')) {
      where.commander = undefined;
    }
    // 订单受理人员
    if (hasRole('commander')) {
      where.commander = userStore.info?.userId;
    }
    return pageOrder({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '订单号',
      dataIndex: 'orderId',
      width: 80,
      hideInTable: true
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo'
    },
    {
      title: '价格',
      width: 120,
      align: 'center',
      dataIndex: 'money',
      key: 'money'
    },
    {
      title: '销量',
      width: 120,
      align: 'center',
      dataIndex: 'salesActual'
    },
    {
      title: '库存',
      width: 120,
      align: 'center',
      dataIndex: 'stockTotal'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 120
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      align: 'center',
      key: 'sortNumber',
      width: 120
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      showSorterTooltip: true,
      hideInSetting: true,
      ellipsis: true,
      width: 180,
      customRender: ({ text }) => toDateString(text, 'MM月dd日 HH:mm')
    }
  ]);

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

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

  const onDetail = (record?: Order) => {
    window.location.href = 'detail?id=' + record?.orderId;
  };

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

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

  // 是否展现多选按钮及批量删除按钮
  if (hasRole('superAdmin') || hasRole('admin')) {
    selection.value = [];
  }

  /* 自定义行属性 */
  const customRow = (record: Order) => {
    return {
      // 行双击事件
      onDblclick: () => {
        window.location.href = '/oa/order/detail?id=' + record.orderId;
        // window.open('/oa/order/detail?id=' + record.orderId);
      }
    };
  };
  //
</script>

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

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