<script setup lang="ts">
import { getUserListApi } from '#/api';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import dayjs from 'dayjs'; // 使用 dayjs 库来格式化时间戳
import { Tag } from 'ant-design-vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { VbenFormProps } from '#/adapter/form';
import { Page } from '@vben/common-ui';
import type { VxeGridListeners } from 'vxe-table';
import { useVbenModal } from '@vben/common-ui'
import { onMounted, ref, inject } from 'vue';
import { globalState } from '#/store/globalState';
import { getServerListApi, getAppListApi } from '#/api/core/server';
import type { AppData, ServerData } from '#/api/core/server';
import { $t } from '#/locales'

const state = inject('globalState', globalState);
const appList = ref<AppData[]>([]);
const ServerList = ref<ServerData[]>([]);
import userModalDemo from './user.vue';
// import { PlayerInfo } from '#/model/player';
const [userModal, userModalApi] = useVbenModal({
  connectedComponent: userModalDemo,
});
interface RowType {
  Uid: number;
  UserName: string;
  Level: string;
  Exp: string;
  Diamond: string;
  Star: string;
  Energy: string;
  LoginTime: number;
  Online: string;
  Node: number;
  Nickname: string;
}
const startDate = dayjs().subtract(7, 'day').startOf('day');
const endDate = dayjs().endOf('day');
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        onChange: async (value: number) => {
          const serverResponse = await getServerListApi({ AppId: value, Type: 1 });
          ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
          GridApi.formApi.updateSchema([
            {
              component: 'Select',
              componentProps: {
                options: ServerList.value.map((item) => ({
                  label: item.ServerId,
                  value: item.ServerId,
                })),
              },
              fieldName: 'ServerId',
            },
          ]);
          GridApi.formApi.setValues({ ServerId: 1 });
        },
        filterOption: true,
        options: [

        ],
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'AppId',
      label: 'APP：',
    },
    {
      component: 'Input',
      componentProps: {
        filterOption: true,
        options: [

        ],
        placeholder: '请输入',
        showSearch: true,
      },
      fieldName: 'Uid',
      label: 'Uid：',
    },
    {
      component: 'Input',
      componentProps: {
        filterOption: true,
        options: [

        ],
        placeholder: '请输入',
        showSearch: true,
      },
      fieldName: 'Nickname',
      label: '昵称：',
    },
    {
      component: 'DatePicker',
      defaultValue: startDate,
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'StartTime',
      label: '开始时间',
      formItemClass: 'col-start-1',
    },
    {
      component: 'DatePicker',
      defaultValue: endDate,
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'EndTime',
      label: '结束时间',

    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-5',
  // 是否在字段值改变时提交表单
  submitOnChange: true,
  // 按下回车时是否提交表单
  submitOnEnter: false,
}
const gridEvents: VxeGridListeners<RowType> = {
  cellClick: async ({ row }) => {
    const value = await GridApi.formApi.getValues();
    userModalApi.setData({ uid: row.Uid, AppId: value.AppId, Node: row.Node });
    userModalApi.open();
    state.uid = row.Uid;
  },
};


const gridOptions: VxeGridProps<RowType> = {
  columns: [
    { field: 'Uid', title: 'id' , sortable: true, sortBy: 'Uid'},
    { field: 'UserName', title: '登录名' },
    { field: 'Level', title: '等级', formatter: ({ cellValue }: { cellValue: string | number }) => `${cellValue} 级`, sortable: true, sortBy: 'Level' },
    { field: 'Node', title: '节点', },
     { field: 'Nickname', title: '昵称',  },
    { field: 'Diamond', title: '钻石', formatter: ({ cellValue }: { cellValue: string | number }) => `${cellValue} 💎`, sortable: true, sortBy: 'Diamond' },
    { field: 'Star', title: '星星', formatter: ({ cellValue }: { cellValue: string | number }) => `${cellValue} ⭐`, sortable: true, sortBy: 'Star' },
    { field: 'Energy', title: '能量', formatter: ({ cellValue }: { cellValue: string | number }) => `${cellValue} ⚡`, sortable: true, sortBy: 'Energy' },
    { field: 'LoginTime', sortable: true, title: '登录时间', formatter: ({ cellValue }: { cellValue: number }) => dayjs(cellValue * 1000).format('YYYY-MM-DD HH:mm:ss'),sortBy: 'LoginTime' },
    { field: 'Online', title: '在线状态', slots: { default: 'online' } , sortable: true, sortBy: 'Online' },
  ],
  height: 'auto',
  pagerConfig: {},
  sortConfig: {
    multiple: true,
  },
  toolbarConfig: {
    refresh: true,
    zoom: true,
    custom: true,

  },
  proxyConfig: {
    response: {
      total: "total",
      result: "data"
    },
    ajax: {
      query: async (
        { page }: { page: { pageSize: number; currentPage: number } },
        formValues: Record<string, any>,
      ) => {
        let Id = parseInt(formValues.AppId, 10);
        let ServerId = 1;
        let Uid = parseInt(formValues.Uid, 10);
        let Nickname = formValues.Nickname ? String(formValues.Nickname) : '';
        let r = await getUserListApi({ Id: Id, ServerId: ServerId, pageSize: page.pageSize, currentPage: page.currentPage, Uid: Uid, Nickname:Nickname, StartTime: formValues.StartTime ? Math.floor(new Date(formValues.StartTime).getTime() / 1000) : undefined, EndTime: formValues.EndTime ? Math.floor(new Date(formValues.EndTime).getTime() / 1000) : undefined });
        return r;
      },
    },
  },

  rowConfig: {
    isHover: true,
  },

};

const [Grid, GridApi] = useVbenVxeGrid({ formOptions, gridOptions, gridEvents });

onMounted(async () => {
  try {
    const response = await getAppListApi();
    appList.value = Array.isArray(response) ? response : [];
    const app = appList.value[0];
    if (!app) return;
    GridApi.formApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: appList.value.map((item) => ({
            label: $t('page.server.' + item.AppName),
            value: item.AppId,
          })),
        },
        fieldName: 'AppId',
      },
    ]);
    const serverResponse = await getServerListApi({ AppId: app.AppId, Type: 1 });
    ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
    GridApi.formApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: ServerList.value.map((item) => ({
            label: item.ServerId,
            value: item.ServerId,
          })),
        },
        fieldName: 'ServerId',
      },
    ]);
  } catch (e) {
    appList.value = [];
    console.log(e);
  }
});
function getTagColor(online: string): string {
  let color = online == '在线' ? 'green' : 'red';
  return color;
}
</script>

<template>
  <Page auto-content-height class="h-[1200px]">
    <Grid>
      <template #online="{ row }">
        <Tag :color="getTagColor(row.Online)">{{ row.Online }}</Tag>
      </template>
    </Grid>
    <userModal class="w-[100%]" />
  </Page>

</template>

<style lang="css">
.broder-bottom-1 {
  border-bottom: 0.5px solid rgb(136, 134, 134);
}
</style>
