<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <!--      <user-search :where="defaultWhere" @search="reload" />-->
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="orderId"
        :columns="columns"
        :datasource="datasource"
        :scroll="{ x: 1000 }"
        :where="defaultWhere"
        v-model:selection="selection"
        cache-key="proSystemUserTable"
      >
        <template #toolbar>
          <a-space>
            <a-button
              type="primary"
              class="ele-btn-icon"
              :disabled="selection.length === 0"
              @click="openEdit()"
            >
              <template #icon>
                <MoneyCollectOutlined />
              </template>
              <span>批量充值</span>
            </a-button>
            <!--            <a-button-->
            <!--              danger-->
            <!--              type="primary"-->
            <!--              class="ele-btn-icon"-->
            <!--              @click="removeBatch"-->
            <!--            >-->
            <!--              <template #icon>-->
            <!--                <delete-outlined />-->
            <!--              </template>-->
            <!--              <span>删除</span>-->
            <!--            </a-button>-->
            <a-input-search
              allow-clear
              v-model:value="searchText"
              placeholder="请输入关键词"
              @search="reload"
              @pressEnter="reload"
            >
              <template #addonBefore>
                <a-select
                  v-model:value="type"
                  style="width: 100px; margin: -5px -12px"
                >
                  <a-select-option value="keywords">模糊搜索</a-select-option>
                  <a-select-option value="username">账号</a-select-option>
                  <a-select-option value="phone">手机号码</a-select-option>
                  <a-select-option value="userId">用户ID</a-select-option>
                  <a-select-option value="nickname">昵称</a-select-option>
                </a-select>
              </template>
            </a-input-search>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'nickname'">
            <a-tooltip :title="`用户ID：${record.userId}`">
              <a-avatar
                :size="30"
                :src="`${record.avatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <span @click="openInfo(record)">{{ record.nickname }}</span>
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'rechargeType'">
            <a-tag v-if="record.rechargeType === 10"> 自定义金额 </a-tag>
            <a-tag v-if="record.rechargeType === 20"> 套餐充值 </a-tag>
          </template>
          <template v-if="column.key === 'balance'">
            <span class="ele-text-success">
              ￥{{ formatNumber(record.balance) }}
            </span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-switch
              :checked="record.status === 0"
              @change="(checked: boolean) => editStatus(checked, record)"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a @click="resetPsw(record)">重置密码</a>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="topRight"
                title="确定要删除此用户吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <Recharge v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, reactive } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    MoneyCollectOutlined,
    // DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString, messageLoading, formatNumber } from 'ele-admin-pro/es';
  import Recharge from './components/recharge.vue';
  import {
    pageRechargeOrder,
    removeRechargeOrder,
    removeBatchRechargeOrder
  } from '@/api/user/recharge/order';
  import type {
    RechargeOrder,
    RechargeOrderParam
  } from '@/api/user/recharge/order/model';
  import { uuid } from 'ele-admin-pro';
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '姓名',
      key: 'nickname',
      dataIndex: 'nickname',
      showSorterTooltip: false
    },
    {
      title: '场景',
      dataIndex: 'rechargeType',
      key: 'rechargeType',
      showSorterTooltip: false
    },
    {
      title: '充值金额',
      dataIndex: 'payPrice',
      sorter: true,
      customRender: ({ text }) => '￥' + text
    },
    {
      title: '可用余额',
      dataIndex: 'balance',
      sorter: true,
      customRender: ({ text }) => '￥' + text
    },
    {
      title: '管理员备注',
      dataIndex: 'comments'
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    }
  ]);
  // 表格选中数据
  const selection = ref<RechargeOrder[]>([]);
  // 当前编辑数据
  const current = ref<RechargeOrder | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示用户详情
  const showInfo = ref(false);
  // 是否显示用户导入弹窗
  const showImport = ref(false);
  const type = ref('keywords');
  const searchText = ref('');
  // 默认搜索条件
  const defaultWhere = reactive({
    username: '',
    nickname: ''
  });

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    where = {};
    if (type.value == 'username') {
      where.username = searchText.value;
    }
    if (type.value == 'nickname') {
      where.nickname = searchText.value;
    }
    if (type.value == 'phone') {
      where.phone = searchText.value;
    }
    if (type.value == 'userId') {
      where.userId = searchText.value;
    }
    // where.roleId = filters.roles;
    return pageRechargeOrder({ ...where, ...orders, page, limit });
  };

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

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

  /* 打开用户详情弹窗 */
  const openInfo = (row?: RechargeOrder) => {
    current.value = row ?? null;
    showInfo.value = true;
  };

  /* 打开编辑弹窗 */
  const openImport = () => {
    showImport.value = true;
  };

  /* 删除单个 */
  const remove = (row: RechargeOrder) => {
    const hide = messageLoading('请求中..', 0);
    removeRechargeOrder(row.userId)
      .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 = messageLoading('请求中..', 0);
        removeBatchRechargeOrder(selection.value.map((d) => d.orderId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };
</script>

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