<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="userId"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        :scroll="{ x: 1300 }"
        :customRow="customRow"
        cache-key="proSystemUserTable"
      >
        <template #toolbar>
          <search
            :selection="selection"
            @search="reload"
            @add="openEdit"
            @remove="removeBatch"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'nickname'">
            <div class="user-box">
              <a-avatar
                :size="30"
                :src="`${record.avatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <div class="user-info">
                <span>{{ record.realName }}</span>
                <span class="ele-text-placeholder">{{ record.nickname }}</span>
              </div>
            </div>
          </template>
          <template v-else-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 === 'balance'">
            <span class="ele-text-success">
              ￥{{ formatNumber(record.balance) }}
            </span>
          </template>
          <template v-else-if="column.key === 'gradeName'">
            <a-tag color="orange">
              {{ record.gradeName }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'region'">
            <div class="ele-text-info"
              >{{ record.province }} {{ record.city }} {{ record.region }}</div
            >
            <div class="ele-text-warning"
              >{{ record.userProfile.provinceMate }}
              {{ record.userProfile.cityMate }}
              {{ record.userProfile.regionMate }}</div
            >
          </template>
          <template v-if="column.key === 'expendMoney'">
            <span class="ele-text-warning">
              ￥{{ formatNumber(record.expendMoney) }}
            </span>
          </template>
          <template v-else-if="column.key === 'recommend'">
            <a-switch
              :checked="record.recommend !== 0"
              @change="(checked: boolean) => editRecommend(checked, record)"
            />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button @click="openEdit(record)">修改</a-button>
              <a-divider type="vertical" />
              <a-button @click="resetPsw(record)">重置密码</a-button>
              <!--              <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>
    <!-- 编辑弹窗 -->
    <user-edit
      v-model:visible="showEdit"
      :data="current"
      :organization-list="data"
      @done="reload"
    />
    <!-- 导入弹窗 -->
    <!--    <user-import v-model:visible="showImport" @done="reload" />-->
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    PlusOutlined,
    DeleteOutlined,
    UploadOutlined,
    EditOutlined,
    UserOutlined,
    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 UserImport from './components/user-import.vue';
  import {
    pageUsers,
    removeUser,
    removeUsers,
    updateUserRecommend,
    updateUserPassword
  } 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 Search from './components/search.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 showImport = ref(false);

  // 加载角色
  const roles = ref<any[]>([]);
  const filters = () => {
    listRoles().then((result) => {
      result.map((d) => {
        roles.value.push({
          text: d.roleName,
          value: d.roleId
        });
      });
    });
  };
  filters();
  // 加载机构
  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];
        }
      } else {
        selectedRowKeys.value = [];
      }
    })
    .catch((e) => {
      loading.value = false;
      message.error(e.message);
    });

  // 表格实例
  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: 'ID',
      dataIndex: 'userId',
      width: 80,
      showSorterTooltip: false
    },
    {
      title: '昵称',
      key: 'nickname',
      dataIndex: 'nickname',
      width: 200,
      showSorterTooltip: false
    },
    {
      title: '出生日期',
      dataIndex: 'birthday',
      key: 'birthday'
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age'
    },
    {
      title: '证件号码',
      dataIndex: 'idCard'
    },
    {
      title: '地区/择偶',
      dataIndex: 'region',
      key: 'region'
    },
    {
      title: '推荐',
      key: 'recommend',
      dataIndex: 'recommend',
      width: 90,
      align: 'center'
    }
  ]);

  // 默认搜索条件
  // const { where, resetFields } = useSearch<User>({
  //   merchantId: undefined,
  //   merchantName: '',
  //   merchantCode: '',
  //   gradeId: undefined,
  //   gradeName: ''
  // });
  // // 默认搜索条件
  // const defaultWhere = reactive({
  //   username: '',
  //   nickname: '',
  //   keywords: ''
  // });

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    where.showProfile = true;
    where.roleId = filters.roles;
    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 openImport = () => {
    showImport.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 removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的用户吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        removeUsers(selection.value.map((d) => d.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 editRecommend = (checked: boolean, row: User) => {
    const recommend = checked ? 1 : 0;
    updateUserRecommend({
      userId: row.userId,
      recommend,
      userProfile: {
        id: row.userProfile?.id,
        recommend
      }
    })
      .then((msg) => {
        row.recommend = recommend;
        message.success(msg);
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

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

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

<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
