const { remote } = require("electron");
const simpleGit = require("simple-git");
import { formatTime } from "./utils.js";

new Vue({
  el: "#app",
  data() {
    const opConfig = remote.getGlobal("opConfig");
    console.log({ ...opConfig.get().userInfo });

    return {
      host: "http://test-code.csdn.net",
      defaultBranch: "master",
      userInfo: { ...opConfig.get().userInfo },
      token: "-y8xo_X_DShoUGBMxRH9",
      activePanel: "",
      list: []
    };
  },
  created() {
    this.getProjectList();
  },
  methods: {
    getProjectList() {
      axios
        .get(
          this.host +
            `/api/v4/users/${this.userInfo.UserName}/projects?skip_namespace=true`
        )
        .then(res => {
          this.list = res.data;
        });
    },
    checkProject(visibility, e) {
      const { path, name } = e;
      const git = simpleGit(path);
      git
        .checkIsRepo()
        .then(() => {
          // const status = await git.status();
          // console.log(status);
          // return
          const branchName =
            "version-" + formatTime("yyyy-MM-dd-hh-mm-ss", new Date());
          git
            .checkoutLocalBranch(branchName)
            .add("./*")
            .commit("更新项目")
            .push(["origin", branchName], () => {
              console.log("update");
              remote
                .Notification({
                  title: "通知",
                  body: "更新成功"
                })
                .show();
              this.getRepositoryBranches();
            });
          // 已存在仓库，新建一个分支去提交
        })
        .catch(() => {
          // 新建项目和仓库
          this.createProject(visibility, e);
        });
    },
    createProject(visibility, e) {
      const { path, name } = e;
      axios
        .post(
          this.host + "/api/v4/projects",
          {
            name,
            visibility
          },
          {
            headers: {
              "PRIVATE-TOKEN": this.token
            }
          }
        )
        .then(res => {
          console.log(res);
          const repo = res.data.http_url_to_repo.replace(
            /^((http|https):\/\/)/,
            `$1quicker:${this.token}@`
          );
          const git = simpleGit(path);
          // const git = simpleGit("/Users/guoweijia/Desktop/test");
          git
            .init()
            .addConfig("user.name", this.userInfo.UserName)
            .addConfig("user.email", this.userInfo.UserEmail)
            .add("./*")
            .commit("上传项目")
            .addRemote("origin", `${repo}`)
            .push(["origin", "master"], () => {
              console.log("done");
              remote
                .Notification({
                  title: "通知",
                  body: "上传成功"
                })
                .show();
              this.getProjectList();
            });
        })
        .catch(
          ({
            response: {
              data: { message: e }
            }
          }) => {
            let errMsg;
            if (e.name) {
              errMsg = "名字重复了";
            } else {
              errMsg = "网络错误，请重新上传";
            }
            remote
              .Notification({
                title: "通知",
                body: errMsg
              })
              .show();
          }
        );
    },
    getRepositoryBranches() {
      const id = this.activePanel;
      if (!id) return;
      axios
        .get(this.host + `/api/v4/projects/${id}/repository/branches`)
        .then(({ data: res }) => {
          console.log(res);
          const currentProject = this.list.find(item => item.id === id);
          this.$set(currentProject, "branches", res);
        });
    },
    deleteBranch(item, branch) {
      axios
        .delete(
          this.host +
            `/api/v4/projects/${item.id}/repository/branches/${encodeURI(
              branch.name
            )}`,
          {
            headers: {
              "PRIVATE-TOKEN": this.token
            }
          }
        )
        .then(res => {
          remote
            .Notification({
              title: "通知",
              body: "删除分支成功"
            })
            .show();
          this.getRepositoryBranches();
        });
    },
    downloadProject(item, branch) {
      const downloadPath = encodeURI(
        `${item.web_url}/-/archive/${branch.name}/${item.path}-${branch.name}.zip`
      );
      console.log(downloadPath);
      location.href = downloadPath;
    }
  }
});
