<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { Button, Card, Space, notification, Modal } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import AppList from './appList.vue';
import { getServerListApi, getAppListApi, updateAppApi, updateAppReviewApi } 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';
import { $t } from '#/locales'
const appId = ref<number>(1);
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);
          appId.value = 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({ AppId: 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);
const reloadReview = 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: $t('page.server.' + item.AppName),
            value: item.AppId,
          })),
        },
        fieldName: 'fieldOptions',
      },
    ]);
    const serverResponse = await getServerListApi({ AppId: app.AppId });
    ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
    setInterval(async () => {
      const serverResponse = await getServerListApi({ AppId: appId.value });
      ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
    }, 60000);
  } catch (e) {
    appList.value = serverList;
    //console.log(e);
  }
});

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





function confirmUpdate() {
  Modal.confirm({
    title: '确认更新',
    content: `你确定要更新吗？`,
    onOk() {
      update();
    },
    onCancel() {
      //console.log('取消更新');
    },
  });
}

function confirmUpdateReview() {
  Modal.confirm({
    title: '确认更新',
    content: `你确定要更新吗？`,
    onOk() {
      updateReview();
    },
    onCancel() {
      //console.log('取消更新');
    },
  });
}

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: "服务器更新失败"
    })
  }
}

async function updateReview() {
  reloadReview.value = true;
  const Value = await BaseFormApi.getValues();
  try {
    await updateAppReviewApi(Value.fieldOptions);
    reloadReview.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) {
    reloadReview.value = false;
    notification.error({
      duration: 10,
      message: "服务器更新失败"
    })
  }
}
</script>
<template>
  <Page>
    <addServerM class="w-[50%]" @hidden="update" />
    <editServerM class="w-[50%]" @hidden="update" />
    <Card class="mb-5" title="服务器操作">
      <BaseForm />
      <Space>
        <Button type="primary" @click="addServer">新增</Button>
        <Button type="primary" @click="confirmUpdate" :loading="reload"> 更新正式环境 </Button>
        <Button type="primary" @click="confirmUpdateReview" :loading="reloadReview"> 更新review环境 </Button>
        <Button type="primary"> 更新配置 </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">
          <h1 class="text-md font-semibold md:text-ml text-center">
            <span>SERVER INFO</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>TAGS</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>PLAYERS</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>CPU LOAD</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>MEMORY</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>CLIENT VERSION</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>LATENCY</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>RESTART</span>
          </h1>
        </div>
      </div>
      <AppList :items="ServerList" title="服务器列表" />
    </div>
  </Page>
</template>
