<template>
  <!-- 表格 -->
  <ele-pro-table
    ref="tableRef"
    row-key="userId"
    :columns="columns"
    :datasource="datasource"
    v-model:selection="selection"
    height="calc(100vh - 290px)"
    tool-class="ele-toolbar-form"
    :scroll="{ x: 800 }"
    tools-theme="default"
    bordered
    cache-key="proSystemOrgUserTable"
    class="sys-org-table"
  >
    <template #toolbar>
      <OrgUserSearch
        @search="reload"
        :selection="selection"
        :total-balance="totalBalance"
        @add="openEdit()"
      />
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'roles'">
        <a-tag v-for="item in record.roles" :key="item.roleId" color="blue">
          {{ item.roleName }}
        </a-tag>
      </template>
      <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="onRecharge(record)">充值</a>
        </a-space>
      </template>
    </template>
  </ele-pro-table>
  <!-- 编辑弹窗 -->
  <Recharge
    v-model:visible="showEdit"
    :selection="selection"
    :data="current"
    @done="reload"
  />
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import Recharge from '../components/recharge.vue';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import OrgUserSearch from './org-user-search.vue';
  import { formatNumber } from 'ele-admin-pro/es';
  import { pageUsers, countUserBalance } from '@/api/system/user';
  import type { User } from '@/api/system/user/model';
  import type { Organization } from '@/api/system/organization/model';
  import {
    RechargeOrder,
    RechargeOrderParam
  } from '@/api/user/recharge/order/model';

  const props = defineProps<{
    // 机构 id
    organizationId?: number;
    // 全部机构
    organizationList: Organization[];
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  // 表格选中数据
  const selection = ref<RechargeOrder[]>([]);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '用户ID',
      dataIndex: 'userId',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '用户账号',
      dataIndex: 'username',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '角色',
      key: 'roles'
    },
    {
      title: '余额',
      dataIndex: 'balance',
      sorter: true,
      key: 'balance',
      customRender: ({ text }) => '￥' + text
    }
  ]);

  // 当前编辑数据
  const current = ref<User | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 统计用户余额
  const totalBalance = ref<number>(0);

  /* 表格数据源 */
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    if (props.organizationId) {
      where.organizationId = props.organizationId;
    }
    return pageUsers({ ...where, ...orders, page, limit });
  };

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

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

  const totalPrice = () => {
    countUserBalance({ organizationId: props.organizationId }).then(
      (balance) => {
        totalBalance.value = Number(balance);
      }
    );
  };
  totalPrice();
  // 监听机构 id 变化
  watch(
    () => props.organizationId,
    () => {
      reload();
      totalPrice();
    }
  );
</script>

<style lang="less" scoped>
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
</style>
