<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :actionColumn="actionColumn"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable"> 重启服务 </n-button>
        </template>
      </BasicTable>
    </n-card>

    <n-modal
      :block-scroll="false"
      :mask-closable="false"
      v-model:show="showModal"
      style="width: 60%"
      :show-icon="false"
      preset="dialog"
      title="重启服务"
    >
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="游戏版本号" path="name">
          <n-input placeholder="请输入版本号" v-model:value="formParams.version" :required="true" />
        </n-form-item>
        <n-form-item label="重启日志" path="log" style="height: 450px; width: 100%">
          <n-code
            id="n-code"
            :code="code"
            :word-wrap="true"
            language="html"
            style="
              height: 450px;
              width: 100%;
              overflow: auto;
              background: #2f3129;
              color: wheat;
              padding: 10px;
            "
          />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">关闭</n-button>
          <n-button
            type="info"
            :loading="formBtnLoading"
            :disabled="formBtnDisabled"
            @click="confirmForm"
            >执行重启</n-button
          >
        </n-space>
      </template>
    </n-modal>

    <!--    :block-scroll="false"-->
    <!--    :mask-closable="false"-->
    <n-modal
      v-model:show="showStdout"
      style="width: 60%"
      :show-icon="false"
      preset="dialog"
      :title="data.id > 0 ? '重启详情(' + data.id + ')' : '正在加载'"
    >
      <n-form ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="操作人ID" path="name">
          <n-input placeholder="" v-model:value="data.admin_id" disabled />
        </n-form-item>
        <n-form-item label="用户名" path="name">
          <n-input placeholder="" v-model:value="data.username" disabled />
        </n-form-item>
        <n-form-item label="IP" path="name">
          <n-input placeholder="" v-model:value="data.ip" disabled />
        </n-form-item>
        <n-form-item label="访问代理" path="name">
          <n-input placeholder="" v-model:value="data.user_agent" type="textarea" disabled />
        </n-form-item>

        <n-form-item label="转发指令" path="name">
          <n-input placeholder="版本号" v-model:value="data.command" disabled />
        </n-form-item>

        <n-form-item label="耗时(秒)" path="name">
          <n-input placeholder="版本号" v-model:value="data.latency" disabled />
        </n-form-item>
        <n-form-item label="重启时间" path="name">
          <n-input placeholder="版本号" v-model:value="data.created_at" disabled />
        </n-form-item>

        <n-form-item label="游戏版本号" path="name">
          <n-input placeholder="版本号" v-model:value="data.version" disabled />
        </n-form-item>

        <n-form-item label="重启日志" path="log" style="height: 450px; width: 100%">
          <n-code
            id="n-code"
            :word-wrap="true"
            :code="data.stdout ?? ''"
            language="html"
            style="
              height: 450px;
              width: 100%;
              overflow: auto;
              background: #2f3129;
              color: wheat;
              padding: 10px;
            "
          />
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { inject, reactive, ref, nextTick, watch, h } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { rebootTable, reboot, GetRestartView } from '@/api/echarts/rebootTable';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { storage } from '@/utils/Storage';
  import { SocketEnum } from '@/enums/socketEnum';
  import { addOnMessage } from '@/utils/websocket';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  const useUserStore = useUserStoreWidthOut();
  const jsonVersion = ref(useUserStore.config.json_version);

  const rules = {
    version: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入版本号',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'createtime',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showStdout = ref(false);
  const data = ref({});
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formBtnDisabled = ref(false);
  const formParams = reactive({
    version: storage.get('reVersion', jsonVersion),
  });

  const params = ref({
    pageSize: 10,
  });

  const code = ref();

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function addTable() {
    showModal.value = true;
    code.value = '\n';
    formBtnLoading.value = false;
    formBtnDisabled.value = false;
  }

  const loadDataTable = async (res) => {
    return await rebootTable({ ...formParams, ...params.value, ...res });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function confirmForm(e) {
    e.preventDefault();
    code.value = '\n';
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));

        message.success('已提交重启任务成功,正在执行重启..');
        storage.set('reVersion', formParams.version);
        // showModal.value = false;
        reboot({ ...formParams })
          .then((_res) => {
            // dataSource.value = res.rows;
            // message.success('操作成功，请刷新！');
          })
          .catch((error) => {
            message.error(error.toString());
          });
      } else {
        message.error('请填写完整信息');
      }
      // formBtnLoading.value = false;
    });
  }

  const onMessageList = inject('onMessageList'); // 接收注入
  const restartLogNotice = (res) => {
    // console.log('子页面接收ws：', res.data);
    const data = JSON.parse(res.data);

    // 不是重启日志消息忽略
    if (data.type !== SocketEnum.TypeRestartLog) {
      return;
    }

    if (data.code == SocketEnum.CodeErr) {
      message.error('查询用户出错，cid:' + data.cid);
      router.push({ name: 'account-list' });
      return;
    }
    if (data.msg !== undefined && data.msg !== null) {
      if (data.msg === 'restart complete') {
        formBtnLoading.value = false;
        message.success('重启脚本执行结束，请查看重启日志！');
        formBtnDisabled.value = true;
        return;
      }
      code.value = code.value + data.msg;
    }
  };

  addOnMessage(onMessageList, restartLogNotice);

  watch(
    () => code,
    () => {
      nextTick(() => {
        handleScroll();
      });
    },
    {
      deep: true, //深度监听
      immediate: false,
    }
  );

  const handleScroll = () => {
    // 跟随内容，滚动条保持底部显示
    let dom = document.getElementById('n-code');
    if (dom !== null && dom !== undefined) {
      dom.scrollTop = dom.scrollHeight;
    }
  };

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '查看详情',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });

  async function handleEdit(record: Recordable) {
    showStdout.value = true;
    data.value = {};
    data.value = await GetRestartView(record);
    console.log('data.value :' + JSON.stringify(data.value));
  }
</script>

<style lang="less" scoped></style>
