<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <SuperAdmin />
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="userId"
        :columns="columns"
        :datasource="datasource"
        class="sys-org-table"
        :scroll="{ x: 1300 }"
        :where="defaultWhere"
        :customRow="customRow"
        cache-key="proSystemUserTable"
      >
        <template #toolbar>
          <a-space>
            <a-button
              type="primary"
              class="ele-btn-icon"
              @click="openInvitation"
            >
              <template #icon>
                <plus-outlined />
              </template>
              <span>邀请注册</span>
            </a-button>
            <a-input-search
              allow-clear
              v-model:value="searchText"
              placeholder="请输入关键词"
              @search="reload"
              @pressEnter="reload"
            />
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar
              :size="30"
              :src="`${record.avatar}`"
              style="margin-right: 4px"
            >
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
          </template>
          <template v-if="column.key === 'realName'">
            <div class="flex flex-col items-center">
              <span>{{ record.realName }}</span>
              <span class="text-gray-400" v-if="hasRole('superAdmin')">{{
                record.phone
              }}</span>
              <span class="text-gray-400" v-else>{{ record.mobile }}</span>
            </div>
          </template>
          <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 === 'platform'">
            <WechatOutlined v-if="record.platform === 'MP-WEIXIN'" />
            <Html5Outlined v-if="record.platform === 'H5'" />
            <ChromeOutlined v-if="record.platform === 'WEB'" />
          </template>
          <template v-if="column.key === 'balance'">
            <span class="ele-text-success">
              ￥{{ formatNumber(record.balance) }}
            </span>
          </template>
          <template v-if="column.key === 'expendMoney'">
            <span class="ele-text-warning">
              ￥{{ formatNumber(record.expendMoney) }}
            </span>
          </template>
          <template v-if="column.key === 'isAdmin'">
            <a-switch
              :checked="record.isAdmin == 1"
              @change="updateIsAdmin(record)"
            />
          </template>
          <template v-if="column.key === 'action'">
            <div>
              <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>
            </div>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <user-edit
      v-model:visible="showEdit"
      :data="current"
      :organization-list="data"
      @done="reload"
    />
    <!-- 导入弹窗 -->
    <user-import v-model:visible="showImport" @done="reload" />
    <!-- 用户详情 -->
    <user-info v-model:visible="showInfo" :data="current" @done="reload" />
    <!-- 邀请注册弹窗 -->
    <invitation-modal
      v-model:visible="showInvitation"
      :inviter-id="currentUserId"
    />
  </a-page-header>
</template>

<script lang="ts" setup>
  import { createVNode, ref, reactive, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    PlusOutlined,
    UserOutlined,
    Html5Outlined,
    ChromeOutlined,
    WechatOutlined,
    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 { messageLoading, formatNumber } from 'ele-admin-pro/es';
  import UserEdit from './components/user-edit.vue';
  import InvitationModal from './components/invitation-modal.vue';
  import { toDateString } from 'ele-admin-pro';
  import {
    pageUsers,
    removeUser,
    updateUserPassword,
    updateUser
  } from '@/api/system/user';
  import type { User, UserParam } from '@/api/system/user/model';
  import { toTreeData, uuid } from 'ele-admin-pro';
  import { listRoles } from '@/api/system/role';
  import { listOrganizations } from '@/api/system/organization';
  import { Organization } from '@/api/system/organization/model';
  import { hasRole } from '@/utils/permission';
  import { getPageTitle } from '@/utils/common';
  import router from '@/router';
  import SuperAdmin from './components/super-admin.vue';

  // 加载状态
  const loading = ref(true);
  // 树形数据
  const data = ref<Organization[]>([]);
  // 树展开的key
  const expandedRowKeys = ref<number[]>([]);
  // 树选中的key
  const selectedRowKeys = ref<number[]>([]);
  // 表格选中数据
  const selection = ref<User[]>([]);
  // 当前编辑数据
  const current = ref<User | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示用户详情
  const showInfo = ref(false);
  // 是否显示用户导入弹窗
  const showImport = ref(false);
  // 是否显示邀请注册弹窗
  const showInvitation = ref(false);
  const searchText = ref('');
  // 当前用户ID
  const currentUserId = ref<number>();

  // 加载角色
  const roles = ref<any[]>([]);
  // 加载机构
  listOrganizations()
    .then((list) => {
      loading.value = false;
      const eks: number[] = [];
      list.forEach((d) => {
        d.key = d.organizationId;
        d.value = d.organizationId;
        d.title = d.organizationName;
        if (typeof d.key === 'number') {
          eks.push(d.key);
        }
      });
      expandedRowKeys.value = eks;
      data.value = toTreeData({
        data: list,
        idField: 'organizationId',
        parentIdField: 'parentId'
      });
      if (list.length) {
        if (typeof list[0].key === 'number') {
          selectedRowKeys.value = [list[0].key];
        }
        // current.value = list[0];
      } else {
        selectedRowKeys.value = [];
        // current.value = null;
      }
    })
    .catch((e) => {
      loading.value = false;
      message.error(e.message);
    });

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'userId',
      width: 90,
      showSorterTooltip: false
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      align: 'center',
      showSorterTooltip: false
    },
    // {
    //   title: '所属部门',
    //   dataIndex: 'organizationName',
    //   key: 'organizationName',
    //   align: 'center'
    // },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      align: 'center'
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      sorter: true,
      align: 'center',
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      align: 'center'
    }
  ]);

  // 默认搜索条件
  const defaultWhere = reactive({
    username: '',
    nickname: ''
  });

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    where = {};
    where.roleId = filters.roles;
    where.keywords = searchText.value;
    where.isAdmin = 1;
    return pageUsers({ page, limit, ...where, ...orders });
  };

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

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

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

  /* 重置用户密码 */
  const resetPsw = (row: User) => {
    Modal.confirm({
      title: '提示',
      content: '确定要重置此用户的密码吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        const password = uuid(8);
        updateUserPassword(row.userId, password)
          .then((msg) => {
            hide();
            message.success(msg + '，新密码：' + password);
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 修改用户状态 */
  const updateIsAdmin = (row: User) => {
    row.isAdmin = !row.isAdmin;
    updateUser(row)
      .then((msg) => {
        message.success(msg);
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 自定义行属性 */
  const customRow = (record: User) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  const query = async () => {
    const info = await listRoles({});
    if (info) {
      roles.value = info;
    }
  };

  /* 打开邀请注册弹窗 */
  const openInvitation = () => {
    // 获取当前用户ID
    const userId = localStorage.getItem('UserId');
    if (userId) {
      currentUserId.value = Number(userId);
      showInvitation.value = true;
    } else {
      message.error('获取用户信息失败');
    }
  };

  watch(
    () => router.currentRoute.value.query,
    () => {
      query();
    },
    { immediate: true }
  );
</script>

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

<style lang="less" scoped>
  .sys-org-table {
    :deep(.ant-table) {
      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 600;
        color: #262626;
        border-bottom: 2px solid #f0f0f0;
      }

      .ant-table-tbody > tr > td {
        padding: 12px 8px;
        border-bottom: 1px solid #f5f5f5;
      }

      .ant-table-tbody > tr:hover > td {
        background: #f8f9ff;
      }

      .ant-tag {
        margin: 0;
        border-radius: 4px;
        font-size: 12px;
        padding: 2px 8px;
      }
    }
  }

  .ele-text-primary {
    color: #1890ff;

    &:hover {
      color: #40a9ff;
    }
  }

  .ele-text-danger {
    color: #ff4d4f;

    &:hover {
      color: #ff7875;
    }
  }
</style>
