<template>
  <a-form :form="form" @submit="handleUpdate">
    <a-form-item
      label="Server Root"
      extra="绝对路径，例如 /opt/tophttpserver/1.1.9"
    >
      <a-input
        v-decorator="[
          'server_root',
          {
            rules: [
              {
                required: true,
                message: '请输入 server root!',
              },
            ],
          },
        ]"
      />
    </a-form-item>
    <a-form-item label="Service URL" extra="检查tophttpserver是否可用，仅支持GET">
      <a-row :gutter="24">
        <a-col :span="22">
          <a-input
            v-decorator="[
              'test_url',
              { rules: [{ required: true, message: '请输入 service url!' }] },
            ]"
          />
        </a-col>
        <a-col :span="2">
          <a-button @click="handleTest">测试</a-button>
        </a-col>
      </a-row>
    </a-form-item>
    <a-form-item >
      <a-button :disabled="restart" type="danger" @click="handleRestart">重启 httpserver</a-button>
      <a-button type="primary" html-type="submit" style="float: right">更新配置</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import { request } from "@/js/req";

export default {
  name: "ManageServer",
  data() {
    return {
      restart: window.localStorage.getItem("disable_restart") === "true"
    };
  },

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "serverForm" });
  },

  mounted() {
    let p = ["server_root", "test_url"];
    p.forEach(v => {
      this.form.getFieldDecorator(v, { initalValue: "" });
    });

    request(
      "GET",
      "/api/server",
      null,
      ok => {
        if (ok.code !== 0) {
          throw ok.msg;
        }
        window.localStorage.setItem("service_url", ok.data.test_url);
        this.form.setFieldsValue(ok.data);
      },
      err => {
        this.$message.error(`错误: ${err}`);
      }
    );
  },

  methods: {
    handleUpdate() {
      let data = {};
      let err = "";

      try {
        this.form.validateFields((e, values) => {
          if (e) {
            err = "server root 或 service url 为空";
            return;
          }
          if (
            !values.server_root ||
            values.server_root.length === 0 ||
            !values.test_url ||
            values.test_url.length === 0
          ) {
            err = "server root 或 service url 为空";
            return;
          }
          data = values;
        });

        if(data.test_url.indexOf('http://') == -1 && data.test_url.indexOf('https://') == -1) {
          throw "非法的 service url";
        }
        if (err) {
          throw err;
        }
      } catch (e) {
        this.$message.error(`错误: ${e}`);
        return;
      }

      request(
        "PUT",
        "/api/server",
        data,
        ok => {
          if (ok.code !== 0) {
            throw ok.msg;
          }
          window.localStorage.setItem("service_url", data.test_url);
          this.$message.info("更改已成功提交到服务端");
        },
        err => {
          this.$message.error(`错误: ${err}`);
        }
      );
    },

    handleTest() {
      let url = this.form.getFieldValue("test_url");
      if(!url || (url.indexOf('http://') == -1 && url.indexOf('https://') == -1)) {
        this.$message.error("请设置正确的 service url");
        return;
      }
      fetch(url)
        .then(response => {
          return response.text();
        })
        .then(txt => {
          this.restart = false;
          window.localStorage.setItem("disable_restart", "false");
          this.$message.info("服务可用");
        })
        .catch(err => {
          this.$message.error(`服务不可用：${err}`);
        });
    },

    handleRestart() {
      request(
        "POST",
        "/api/server",
        { command: "restart" },
        ok => {
          if (ok.code !== 0) {
            throw ok.msg;
          }
          this.$message.info("服务重启请求已发送，稍后可测试是否已启动");
          this.restart = true;
          window.localStorage.setItem("disable_restart", "true");
        },
        err => {
          this.$message.error(`服务重启失败：${err}`);
        }
      );
    }
  }
};
</script>