<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.text"
                :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"
            :disabled="is_loading"
            @click="sub_yy_form('step1_form', 1)"
          >
            下一步
          </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"
          :rules="app_set_rules"
        >
          <div v-for="(item, index) in step2_arr" :key="index + 10000">
            <el-form-item :label="item.text" v-if="item.type == 'text'">
              <el-input v-model="item.value"></el-input>
            </el-form-item>

            <el-form-item :label="item.text" v-if="item.type == 'radio'">
              <div
                :class="{ select_box: true, is_select: item.val == vision }"
                v-for="vision in item.value"
                :key="vision"
                @click="change_appset(item, 'val', vision)"
              >
                {{ vision }}
              </div>
            </el-form-item>

            <el-form-item
              :label="item.text + '-内存：'"
              class="limitsd"
              v-if="item.type == 'resource'"
            >
              <el-input
                type="number"
                class="limitinput"
                v-model="item.memory"
                placeholder="请输入内存"
              ></el-input>
              <el-select
                v-model="item.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="item.text + '-CPU：'"
              v-if="item.type == 'resource'"
            >
              <el-input
                type="number"
                v-model="item.cpu"
                placeholder="请输入标题"
              >
                <template slot="append">M</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="item.text" v-if="item.type == 'switch'">
              <div
                class="openbgc"
                @click="openstart(item, 'value')"
                :style="
                  !item.value
                    ? {
                        backgroundImage:
                          'url(' +
                          require('@/assets/imgs/btn_off_hov.png') +
                          ')',
                      }
                    : {}
                "
              ></div>
            </el-form-item>
            <el-form-item :label="item.text" v-if="item.type == 'storage'">
              <div
                :class="{
                  select_box: true,
                  is_select: item.storage == save,
                }"
                v-for="save in save_arr[item.dwtype]"
                :key="save"
                @click="change_appset(item, 'storage', save)"
              >
                {{ save }}
              </div>
            </el-form-item>
          </div>
        </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="pre_step">
            上一步
          </el-button>
          <el-button
            type="primary"
            :disabled="is_loading"
            @click="sub_app_set()"
          >
            下一步
          </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-if="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"
            :disabled="is_loading"
            @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"
            v-if="finallyState === 1"
            @click="finallyAction1"
          >
            前往查看
          </el-button>
          <el-button
            type="primary"
            v-if="finallyState === 2"
            @click="finallyAction2"
          >
            重新部署
          </el-button>
        </div>
      </app-build-step>
    </app-build-steps>
  </div>
</template>

<script>
import appBuildSteps from "@/components/app-build-steps/app-build-steps";
import appBuildStep from "@/components/app-build-steps/app-build-step";
import codes from "@/components/general/codes";
import yaml from "js-yaml";
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,
    deploymentInfo,
    "v-apaas-code": codes,
  },
  data: () => ({
    step: 0,
    senior_flag: false,
    begin_code: "",
    baseInfoForm: {
      namespace: "",
      name: "",
    },
    app_set: {},
    app_set_info: {},
    area_options: [
      {
        name: "12312",
        value: 1,
      },
    ],
    save_arr: [
      ["2Gi", "4Gi", "8Gi", "16Gi", "32Gi", "64Gi", "128Gi", "256Gi", "512Gi"],
      ["2TB", "4TB", "8TB", "16TB", "32TB", "64TB", "128TB", "256TB", "512TB"],
    ],
    memory_arr: [
      {
        value: "Mi",
        label: "Mi",
      },
      {
        value: "Gi",
        label: "Gi",
      },
    ],
    image_rules: {
      namespace: [
        { required: true, message: "请选择工作区域", trigger: "change" },
      ],
      name: [
        { required: true, message: "请输入应用部署名称", trigger: "blur" },
        { validator: checkName, trigger: "blur" },
      ],
    },
    app_set_code: "",
    is_change: false,
    is_loading: false,
    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" },
      ],
    },
    step2_arr: [],
    deploy_id: "",
    evtUuid: "",
    evtSource: null,
    stateList: [],
    finallyState: 0,
  }),
  methods: {
    get_name_space() {
      this.$http.get(`/apaas/hubApi/market/namespaces`).then((response) => {
        console.log(response);
        this.area_options = response.data.data;
      });
    },
    get_step_info() {
      this.$http
        .get(`/apaas/hubApi/market/step/${this.$route.params.app_id}`)
        .then((response) => {
          let step2_arr = JSON.parse(response.data.data).configInfo;
          console.log(step2_arr);
          step2_arr.forEach((e) => {
            if (e.type == "radio") {
              e["val"] = e.value[0];
              // this.deal_key_value(this.app_set_info,e.name,e.type,e.value[0])
            } else if (e.type == "storage") {
              e["dwtype"] = e.storage.indexOf("Gi") == -1 ? 1 : 0;
              // this.deal_key_value(this.app_set_info,e.name,e.type,e.storage)
            } else if (e.type == "resource") {
              let memory = e.memory;
              let cpu = e.cpu;
              e["memory_type"] = memory.indexOf("Mi") == -1 ? "Gi" : "Mi";
              e["memory"] = parseInt(memory);
              e["cpu"] = parseInt(cpu);
              // this.deal_key_value(this.app_set_info,e.name,'resource',[memory,cpu])
            } else {
              // this.deal_key_value(this.app_set_info,e.name,e.type,e.value)
            }
          });
          this.step2_arr = step2_arr;
          console.log(this.app_set_info);
        });
    },
    get_step_file() {
      this.$http
        .get(`/apaas/hubApi/market/values/${this.$route.params.app_id}`)
        .then((response) => {
          this.app_set_code = response.data.data;
        });
    },
    change_appset(obj, key, val) {
      console.log(key, val);
      this.$set(obj, key, val);
    },
    deal_key_value(key_string, type, value) {
      var key_arr = key_string.split(".");
      var temp = this.app_set_info;
      key_arr.forEach((e, index) => {
        if (key_arr.length - 1 == index) {
          if (type == "resource") {
            temp[e] = {
              limits: {
                memory: value[1] + value[0],
                cpu: value[2] + "m",
              },
              requests: {
                memory: value[1] + value[0],
                cpu: value[2] + "m",
              },
            };
          } else if (type == "storage") {
            temp[e] = {
              volumeClaimTemplate: {
                spec: {
                  storageClassName: "nfs-client",
                  accessModes: ["ReadWriteOnce"],
                  resources: {
                    requests: {
                      storage: value,
                    },
                  },
                },
                selector: {},
              },
            };
          } else {
            temp[e] = value;
          }
        } else {
          if (temp[e]) {
          } else {
            temp[e] = {};
          }
          temp = temp[e];
        }
      });
    },
    deal_key_text(obj, key_string) {
      var key_arr = key_string.split(".");
      var temp = obj;
      key_arr.forEach((e, index) => {
        if (key_arr.length - 1 == index) {
        } else {
          temp = temp[e];
        }
      });
    },
    deal_code(n) {
      if (n) {
        //调用接口
        this.change_form_aploy(0);
      }
      this.senior_flag = false;
    },
    change_form_aploy(n) {
      this.is_loading = true;
      if (n == 1) {
        //表单提交
        var temp = {
          app_id: parseInt(this.$route.params.app_id),
          up_userid: this.$store.state.userInfo.user_id,
          name: this.baseInfoForm.name,
          namespace: this.baseInfoForm.namespace,
          uu: this.evtUuid,
          values: this.app_set_info,
        };
      } else {
        //编辑提交
        var temp = {
          app_id: parseInt(this.$route.params.app_id),
          up_userid: this.$store.state.userInfo.user_id,
          name: this.baseInfoForm.name,
          namespace: this.baseInfoForm.namespace,
          uu: this.evtUuid,
          values: yaml.load(this.app_set_code),
        };
      }
      this.next_step();
      this.$http
        .post(`/apaas/hubApi/market/build`, temp)
        .then((response) => {
          this.is_loading = false;
          if (response.data.success === 1) {
            // this.$message.success("开始部署成功");
            this.deploy_id = response.data.data.deploy_id;
          }
        })
        .catch(() => {
          this.is_loading = false;
        });
    },
    sub_yy_form(formName, n) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (n == 1) {
            this.get_work_name();
          } else if (n == 2) {
            this.sub_app_set();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    get_work_name() {
      this.is_loading = true;
      this.$http
        .get(
          `/apaas/hubApi/market/exist/${this.baseInfoForm.namespace}?name=${this.baseInfoForm.name}`
        )
        .then((response) => {
          console.log(response);
          this.is_loading = false;
          if (response.data.success) {
            if (response.data.data) {
              this.$message.error("工作名称已存在");
            } else {
              this.next_step();
            }
          }
        })
        .catch(() => {
          this.is_loading = false;
        });
    },
    sub_app_set() {
      this.is_loading = true;
      this.step2_arr.forEach((e) => {
        if (e.type == "radio") {
          this.deal_key_value(e.name, e.type, e.val);
        } else if (e.type == "storage") {
          this.deal_key_value(e.name, e.type, e.storage);
        } else if (e.type == "resource") {
          let memory = e.memory;
          let cpu = e.cpu;
          this.deal_key_value(e.name, "resource", [
            e.memory_type,
            e.memory,
            e.cpu,
          ]);
        } else {
          this.deal_key_value(e.name, e.type, e.value);
        }
      });
      console.log(this.app_set_info);
      console.log(this.step2_arr);
      //表单提交调用接口
      this.change_form_aploy(1);
    },
    openstart(item, key) {
      if (item[key]) {
        this.$set(item, key, false);
        // item[key] = false;
      } else {
        // item[key] = true;
        this.$set(item, key, true);
      }
    },
    pre_step() {
      this.step--;
    },
    next_step() {
      this.step++;
    },
    get_status() {
      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", (event) => {
        console.log(event);
        this.update_status({
          id: event.lastEventId,
          data: JSON.parse(event.data),
        });
      });
    },
    update_status(event) {
      let names = {
        values: "获取部署参数",
        "pull-chart": "拉取部署文件",
        install: "开始部署",
        "deploy-status": "部署状态",
      };
      let currentState = this.stateList.find((state) => {
        return state.value === event.id;
      });

      if (!currentState) {
        if (this.stateList.length > 0) {
          this.stateList[this.stateList.length - 1].state = 1;
        }

        this.stateList.push({
          name: names[event.id],
          value: event.id,
          content: [],
          state: 0,
        });

        currentState = this.stateList[this.stateList.length - 1];
      }

      currentState.content.push(...event.data.data.split("\n"));

      if (event.id === "deploy-status") {
        let finallyState = event.data.state === "success" ? 1 : 2;
        this.finallyState = finallyState;
        currentState.state = finallyState;
      } else {
        if (event.data.state !== "notes") {
          currentState.state = 2;
        }
      }
    },
    finallyAction1() {
      this.$router.push({
        path: `/yygl/0/1/deploydetail/${this.deploy_id}`,
        query: {
          showstate: true,
        },
      });
    },
    finallyAction2() {
      this.init();
    },
    init() {
      this.step = 0;
      this.get_status();
      this.get_name_space();
      this.get_step_info();
      this.get_step_file();
    },
  },
  created() {
    this.init();
  },
};
</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;
  line-height: 35px;
  background-color: #f7f8f9;
  border-radius: 6px;
  font-size: 14px;
  color: #6573ae;
  text-align: center;
  float: left;
  margin-right: 10px;
  cursor: pointer;
  padding: 0 20px;
}
.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>
