<template>
  <div class="deployment-container">
    <div class="apass_breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="`/yygl/${$route.params.level}/0`">
          我的应用
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="`/yygl/${$route.params.level}/${$route.params.type}`"
        >
          应用仓库
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          应用部署
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <app-build-steps :active-step="step">
      <app-build-step
        title="部署基本信息"
        :step="0"
        :active-icon="require('@/assets/imgs/progress_ic_xinxitx.png')"
      >
        <el-form
          ref="step1_form"
          class="step_form"
          label-position="top"
          :model="baseInfoForm"
          :rules="image_rules"
        >
          <el-form-item label="工作区域：" prop="namespace">
            <el-select
              v-model="baseInfoForm.namespace"
              placeholder="请选择工作区域"
            >
              <el-option
                v-for="item in area_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用部署名称：" prop="name">
            <el-input
              v-model="baseInfoForm.name"
              placeholder="请输入应用部署名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="apass_button step_action">
          <el-button type="primary" @click="sub_yy_form('step1_form')">
            下一步
          </el-button>
        </div>
      </app-build-step>
      <app-build-step
        title="应用配置"
        :step="1"
        :active-icon="require('@/assets/imgs/progress_ic_yingyongpz.png')"
      >
        <!-- content  -->
        <el-form
          v-show="!senior_flag"
          ref="step2_form"
          class="step_form"
          label-position="top"
          :model="app_set"
          :rules="app_set_rules"
        >
          <el-form-item label="标题：" prop="title">
            <el-input
              v-model="app_set.title"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>

          <el-form-item label="镜像版本：" prop="vision">
            <div
              :class="{ select_box: true, is_select: app_set.vision == vision }"
              v-for="vision in vision_arr"
              :key="vision"
              @click="app_set.vision = vision"
            >
              {{ vision }}
            </div>
          </el-form-item>

          <el-form-item label="资源限制-内存：" prop="memory" class="limitsd">
            <el-input
              type="number"
              class="limitinput"
              v-model="app_set.memory"
              placeholder="请输入内存"
            ></el-input>
            <el-select
              v-model="app_set.memory_type"
              class="timeslect"
              placeholder="请选择内存"
            >
              <el-option
                v-for="item in memory_arr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="资源限制-CPU：" prop="cpu">
            <el-input
              type="number"
              v-model="app_set.cpu"
              placeholder="请输入标题"
            >
              <template slot="append">M</template>
            </el-input>
          </el-form-item>

          <el-form-item label="是否监控：" prop="watch">
            <div
              class="openbgc"
              @click="openstart"
              :style="
                !app_set.watch
                  ? {
                      backgroundImage:
                        'url(' + require('@/assets/imgs/btn_off_hov.png') + ')',
                    }
                  : {}
              "
            ></div>
          </el-form-item>
          <el-form-item label="储存容量：" prop="save_memory">
            <div
              :class="{
                select_box: true,
                is_select: app_set.save_memory == save,
              }"
              v-for="save in save_arr"
              :key="save"
              @click="app_set.save_memory = save"
            >
              {{ save }}
            </div>
          </el-form-item>
        </el-form>
        <div class="senior_box" @click="senior_flag = true" v-if="!senior_flag">
          高级配置
        </div>
        <div class="apass_button step_action" v-if="!senior_flag">
          <el-button type="primary" plain @click="preStep">
            上一步
          </el-button>
          <el-button type="primary" @click="sub_yy_form('step2_form')">
            下一步
          </el-button>
        </div>
        <p
          v-if="senior_flag"
          style="color: #58617a;font-size: 14px;margin-bottom:10px;margin-top:30px;"
        >
          高级配置：
        </p>
        <v-apaas-code v-show="senior_flag" :datas="app_set.code"></v-apaas-code>
        <div class="apass_button step_action" v-if="senior_flag">
          <el-button type="primary" plain @click="deal_code(0)">
            取消
          </el-button>
          <el-button type="primary" @click="deal_code(1)">
            保存
          </el-button>
        </div>
      </app-build-step>
      <app-build-step
        title="应用部署"
        :step="2"
        :active-icon="require('@/assets/imgs/progress_ic_bushudata.png')"
      >
        <deployment-info
          :data="stateList"
          style="margin-top: 30px;"
        ></deployment-info>
        <div class="apass_button step_action">
          <el-button type="primary">
            前往查看
          </el-button>
          <el-button type="primary">
            重新部署
          </el-button>
        </div>
      </app-build-step>
    </app-build-steps>

    <apass-dialog
      ref="dialog"
      :title="dialogInfo.title"
      :msg="dialogInfo.msg"
      :submit="dialogInfo.submit"
    ></apass-dialog>
  </div>
</template>

<script>
import appBuildSteps from "@/components/app-build-steps/app-build-steps";
import appBuildStep from "@/components/app-build-steps/app-build-step";
import apassDialog from "@/components/apass-dialog";
import codes from "@/components/codes";
var checkNumber = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("不能为空"));
  }
  setTimeout(() => {
    if (new RegExp("^[1-9][0-9]*$").test(value)) {
      callback();
    } else {
      callback(new Error("请输入正整数"));
    }
  });
};
var checkName = (rule, value, callback) => {
  if (new RegExp("^[a-z]([0-9]||[a-z]||-)*$").test(value)) {
    callback();
  } else {
    callback(new Error("小写字母开头,可以由小写字母、数字、- 组成"));
  }
};
import deploymentInfo from "@/components/deployment-info";

export default {
  components: {
    appBuildSteps,
    appBuildStep,
    apassDialog,
    deploymentInfo,
    "v-apaas-code": codes,
  },
  data: () => ({
    step: 0,
    senior_flag: false,
    begin_code: "",
    dialogInfo: {
      title: "",
      msg: "",
      submit: null,
    },
    baseInfoForm: {
      namespace: "",
      name: "",
    },
    app_set: {
      title: "",
      vision: "",
      memory: "",
      memory_type: 1,
      cpu: "",
      watch: 0,
      save_memory: "",
      code: "",
    },
    area_options: [
      {
        name: "12312",
        value: 1,
      },
    ],
    vision_arr: ["1.0.1", "10.1.2", "2.2.3"],
    save_arr: [
      "2GI",
      "4GI",
      "8GI",
      "16GI",
      "32GI",
      "64GI",
      "128GI",
      "256GI",
      "512GI",
    ],
    memory_arr: [
      {
        value: 1,
        label: "MI",
      },
      {
        value: 2,
        label: "GI",
      },
    ],
    image_rules: {
      namespace: [
        { required: true, message: "请选择工作区域", trigger: "change" },
      ],
      name: [
        { required: true, message: "请输入应用部署名称", trigger: "blur" },
        { validator: checkName, trigger: "blur" },
      ],
    },
    app_set_rules: {
      title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      memory: [
        { required: true, message: "请输入内存", trigger: "blur" },
        { validator: checkNumber, trigger: "blur" },
      ],
      cpu: [
        { required: true, message: "请输入cpu", trigger: "blur" },
        { validator: checkNumber, trigger: "blur" },
      ],
      vision: [{ required: true, message: "请选择版本号", trigger: "change" }],
      save_memory: [
        { required: true, message: "请选择存储容量", trigger: "change" },
      ],
    },
    evtUuid: "",
    evtSource: null,
    listStatus: [],
    state: "",
    text: "",
    url: "",
    act: 0,
    stateList: [
      {
        name: "获取部署参数",
        value: "values",
        content: "获取部署参数",
        state: 1,
      },
      {
        name: "拉取部署文件",
        value: "pull-chart",
        content: "拉取部署文件",
        state: 1,
      },
      {
        name: "开始部署",
        value: "install",
        content: "开始部署",
        state: 1,
      },
      {
        name: "部署状态",
        value: "deploy-status",
        content: "部署状态",
        state: 2,
      },
    ],
  }),
  methods: {
    get_step_info() {
      this.$http
        .get(`/apaas/hubApi/market/step/${this.$route.params.app_id}`)
        .then((response) => {
          console.log(JSON.parse(response.data.data));
        });
    },
    deal_code(n) {
      if (n) {
        this.begin_code = this.app_set.code;
      } else {
        this.app_set.code = this.begin_code;
      }
      this.senior_flag = false;
    },
    sub_yy_form(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.nextStep();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    openstart() {
      if (this.app_set.watch) {
        this.app_set.watch = 0;
      } else {
        this.app_set.watch = 1;
      }
    },
    preStep() {
      this.step--;
    },
    nextStep() {
      this.step++;
    },
    getStatus() {
      let evtUuid = Math.random()
        .toString(16)
        .substr(3);
      let evtSource = new EventSource(
        `/apaas/hubApi/event/subscribe/deploy/${evtUuid}`
      );

      this.evtUuid = evtUuid;
      this.evtSource = evtSource;

      evtSource.addEventListener("message", function(e) {
        if (this.listStatus.map((o) => o.status).indexOf(e.lastEventId) == -1) {
          if (this.listStatus.length) {
            this.listStatus[this.listStatus.length - 1].success = "success";
          }

          this.listStatus.push({
            status: e.lastEventId,
            success: JSON.parse(e.data).state,
            data: JSON.parse(e.data).data,
          });

          this.text = this.listStatus[this.listStatus.length - 1].data;
          this.text = "<span class='linenum'></span>" + this.text;
          this.text = this.text.replace(
            /\n/g,
            "\n<span class='linenum'></span>"
          );
          this.text = this.text.replace(/>==>/g, ">>");
          this.act = this.listStatus.length - 1;
        } else {
          let i = this.listStatus.map((o) => o.status).indexOf(e.lastEventId);
          let item = this.listStatus[i].data;

          item = item + "\n" + JSON.parse(e.data).data;

          this.listStatus[i].data = item;
          this.text = this.listStatus[this.listStatus.length - 1].data;
          this.text = "<span class='linenum'></span>" + this.text;
          this.text = this.text.replace(
            /\n/g,
            "\n<span class='linenum'></span>"
          );
          this.text = this.text.replace(/>==>/g, ">>");
          this.act = this.listStatus.length - 1;

          if (JSON.parse(e.data).state != "notes") {
            this.listStatus[i].success = JSON.parse(e.data).state;
          }
        }

        if (JSON.parse(e.data).state == "success") {
          this.state = "部署成功！";
          this.url = `https://${window.location.host}/apaas/ui/#/pods?namespace=${this.baseInfoForm.namespace}`;
        }

        for (let i = 0; i < this.listStatus.length; i++) {
          switch (this.listStatus[i].status) {
            case "values":
              this.listStatus[i].statusHan = "获取部署参数";
              break;
            case "pull-chart":
              this.listStatus[i].statusHan = "拉取部署文件";
              break;
            case "install":
              this.listStatus[i].statusHan = "开始部署";
              break;
            case "deploy-status":
              this.listStatus[i].statusHan = "部署状态";
              break;
            default:
              this.listStatus[i].statusHan = "其他";
              break;
          }
        }
      });
    },
  },
  created() {
    this.getStatus();
    this.get_step_info();
  },
};
</script>

<style scoped>
.openbgc {
  width: 56px;
  height: 23px;
  background-image: url("~@/assets/imgs/btn_on_hov.png");
  background-size: contain;
  cursor: pointer;
}
.deployment-container {
  margin: 20px 40px;
}
.deployment-container > .app_build_steps {
  border-radius: 12px;
  background-color: #fff;
  padding: 30px;
}
.step_action {
  text-align: right;
  margin-top: 45px;
}
.step_action .el-button:not(:last-child) {
  margin-right: 30px;
}
.select_box {
  height: 35px;
  width: 80px;
  line-height: 35px;
  background-color: #f7f8f9;
  border-radius: 6px;
  font-size: 14px;
  color: #6573ae;
  text-align: center;
  float: left;
  margin-right: 10px;
  cursor: pointer;
}
.is_select {
  background-color: #515fe7;
  color: #f8f9fd;
}
.limitsd {
  position: relative;
}
.deployment-container .step_form .el-form-item.limitsd .timeslect {
  position: absolute;
  width: 100px;
  right: 0;
  top: 0;
}
.senior_box {
  width: 124px;
  height: 44px;
  background-color: #0f2683;
  border-radius: 8px;
  font-size: 16px;
  color: #f8f9fd;
  line-height: 44px;
  text-align: center;
  cursor: pointer;
}
</style>

<style>
.deployment-container .step_form .el-form-item .el-input-group__append,
.el-input-group__prepend {
  border-radius: 0 8px 8px 0;
}
.limitsd .timeslect .el-input__inner {
  width: 100px;
  border-radius: 0 8px 8px 0;
  background-color: rgba(15, 38, 131, 1);
  color: rgba(248, 249, 253, 1);
  border: 0;
}
.limitsd .limitinput .el-input__inner {
  width: 860px;
}
.deployment-container .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.deployment-container .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.deployment-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.deployment-container .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.deployment-container .step_form {
  max-width: 970px;
  margin-top: 20px;
}
.deployment-container .step_form .el-form-item {
  margin: 0 10px 24px;
}
.deployment-container .step_form .el-form-item .el-select {
  width: 100%;
}
.deployment-container .step_form .el-form-item__label {
  padding-bottom: 8px;
  padding-left: 15px;
  line-height: 25px;
  color: #58617a;
}
.image_list .el-table th > .cell {
  color: #1a2236;
}
.image_list .el-table td,
.image_list .el-table th.is-leaf {
  border: none !important;
  line-height: 23px;
}
.image_list .el-table::before {
  display: none;
}
.image_list .el-table {
  width: 100%;
}
.image_list .el-table__row:nth-child(odd) td {
  background-color: #f8f9fd;
}
</style>
