<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { Button, Card,  Space, notification } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import AppList from './appList.vue';
import { getServerListApi, getAppListApi, updateAppApi } from '#/api/core/server';
import type { AppData, ServerData } from '#/api/core/server';
import { useVbenModal } from '@vben/common-ui' 
import { ref,onMounted } from 'vue';
import addServerModal from './addServer.vue';
import dayjs from 'dayjs';
const [BaseForm, BaseFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },

  // 使用 tailwindcss grid布局
  // 提交函数
  // 垂直布局，label和input在不同行，值为vertical
  layout: 'horizontal',
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        onChange: async (value: number) => {
          const serverResponse = await getServerListApi({AppId:value});
          ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
          const app = appList.value.find((item) => item.AppId === value);
          if (!app) return;
          const updateTime = dayjs((app.Update ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') 
          BaseFormApi.setFieldValue("update", updateTime)
        },
        filterOption: true,
        options: [
          
        ],
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'fieldOptions',
      label: 'APP：',
    },
    {
      component: 'Input',
      disabled: true,
      defaultValue: "",
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'update',
      label: '更新时间：',
    }
  ],
  // handleSubmit: async (values: Record<string, any>) => {
  //   console.log(values);
  // },
  showDefaultActions: false,
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-2 ',
});
const [addServerM, addServerApi] = useVbenModal({
  connectedComponent: addServerModal,
  onClosed: async () => {
    const Value = await BaseFormApi.getValues();
    const serverResponse = await getServerListApi(Value.fieldOptions);
    ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
    addServerApi.close();
  },
});

const serverList = [
  {
    AppId: 1,
    AppName: '测试版本',
    WsHost: '1.226.16.67',
    Status: 'Online',
  },
  {
    AppId: 1,
    AppName: '测试版本',
    WsHost: '1.226.16.67',
    Status: 'Online',
  },
  {
    AppId: 1,
    AppName: '测试版本',
    WsHost: '1.226.16.67',
    Status: 'Online',
  },
];
const appList = ref<AppData[]>([]);
const ServerList = ref<ServerData[]>([]);
const reload = ref(false);
onMounted(async() => {
  try{
    const response = await getAppListApi();
    appList.value = Array.isArray(response) ? response : [];
    const app = appList.value[0];
    if (!app) return;
    const updateTime = dayjs((app.Update ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') 
    BaseFormApi.setFieldValue("update", updateTime)
    BaseFormApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: appList.value.map((item) => ({
            label: item.AppName,
            value: item.AppId,
          })),
        },
        fieldName: 'fieldOptions',
      }, 
    ]);
    const serverResponse = await getServerListApi({AppId:app.AppId});
    ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
  }catch(e){
    appList.value = serverList;
    //console.log(e);
  }
});

async function addServer() {
  const Value = await BaseFormApi.getValues();
  addServerApi.setData({AppId: Value.fieldOptions});
  addServerApi.open();
}





async function update() {
  reload.value = true;
  const Value = await BaseFormApi.getValues();
  try{
    await updateAppApi(Value.fieldOptions);
    reload.value = false;
    notification.info({
      duration:10,
      message:"服务器更新成功"
    })
    const response = await getAppListApi();
    appList.value = Array.isArray(response) ? response : [];
    const app = appList.value.find((item) => item.AppId === Value.fieldOptions);
    if (!app) return;
    const updateTime = dayjs((app.Update ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') 
    BaseFormApi.setFieldValue("update", updateTime)
  }catch(e){
    reload.value = false;
    notification.error({
      duration:10,
      message:"服务器更新失败"
    })
  }
}
</script>
<template>
  <Page>
    <addServerM class="w-[50%]" @hidden="update"/>
    <Card class="mb-5" title="服务器操作">
      <BaseForm />
      <Space>
        <Button @click="addServer">新增</Button>
        <Button type="primary" @click="update" :loading="reload"> 更新 </Button>
        <Button> 删除 </Button>
        <Button danger> 更新配置 </Button>
      </Space>
    </Card>
    <div class="p-5">
      <div class="card-box p-4 py-6 flex justify-between h-12">
        
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h2 class="text-md font-semibold md:text-ml  text-center">
            <span>ServerId</span>
          </h2>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml text-center">
            <span>ServerName</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>Status</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>StartTime</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>PlayerNum</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>OpenServerTime</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>Handle</span>
          </h1>
        </div>
        <div class="flex flex-col justify-center  md:mt-0 lg:w-1/12">
          <h1 class="text-md font-semibold md:text-ml  text-center">
            <span>Config</span>
          </h1>
        </div>
      </div>
      <!-- <template>
        <AppList :items="ServerList" title="服务器列表"/>
      </template> -->
      <AppList :items="ServerList" title="服务器列表"/>

    </div>
  </Page>
</template>
