<template>
  <div class="app_build-container">
    <div class="apass_breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>在线组件工具</el-breadcrumb-item>
        <el-breadcrumb-item>应用构建（镜像形式）</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <app-build-steps
      :active-step="step"
      :done="done"
      :show-done="true"
      done-title="提交成功"
      done-sub-title="应用已创建，可前往应用仓库进行应用部署"
    >
      <app-build-step
        title="应用基础信息填写"
        :step="0"
        :active-icon="require('@/assets/imgs/progress_ic_xinxitx.png')"
        :done="done"
      >
        <el-form
          ref="app_info_form"
          class="step_form"
          label-position="top"
          :model="app_info"
          :rules="app_rules"
        >
          <el-form-item label="应用名称：" prop="name">
            <el-input
              v-model="app_info.name"
              placeholder="请输入应用名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="应用版本：" prop="version">
            <el-input
              v-model="app_info.version"
              placeholder="请输入应用版本，例：1.0.0"
            ></el-input>
          </el-form-item>
          <el-form-item label="业务领域：" prop="ywly">
            <el-select v-model="app_info.ywly" placeholder="请选择业务领域">
              <el-option
                v-for="item in ywlys"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用类型：" prop="type">
            <el-select v-model="app_info.type" placeholder="请选择应用类型">
              <el-option
                v-for="item in types"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用封面：" prop="logo">
            <upload-file
              :multiple="false"
              :max="1"
              type="cropper"
              :readOnly="false"
              fit="fill"
              :list="logo"
              @getNewList="getNewList"
              directory="hub"
            ></upload-file>
          </el-form-item>
          <el-form-item label="所属组织：" prop="org">
            <el-select
              v-model="app_info.org"
              placeholder="请选择所属组织"
              :disabled="true"
            >
              <el-option
                v-for="item in orgs"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应用简介：" prop="yyjj">
            <el-input
              v-model="app_info.yyjj"
              type="textywly"
              placeholder="请输入应用简介"
            ></el-input>
          </el-form-item>
          <el-form-item label="功能简介：" prop="gnjj">
            <el-input
              v-model="app_info.gnjj"
              type="textywly"
              placeholder="请输入功能简介"
            ></el-input>
          </el-form-item>
          <el-form-item label="应用场景示例：" prop="cjsl">
            <el-input
              v-model="app_info.cjsl"
              type="textywly"
              placeholder="请输入应用场景示例"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="apaas_button step_action">
          <el-button type="primary" @click="step1Action">
            下一步
          </el-button>
        </div>
      </app-build-step>
      <app-build-step
        title="上传部署文件"
        :step="1"
        :active-icon="require('@/assets/imgs/progress_ic_bushudata.png')"
      >
        <el-form
          ref="deploy_info_form"
          class="step_form"
          label-position="top"
          :model="deploy_info"
          :rules="deploy_rules"
        >
          <el-form-item
            label="上传部署文件："
            prop="file"
            ref="step2_upload_item"
          >
            <div class="description_info">
              <i class="el-icon-warning-outline"></i>
              <p
                v-html="
                  `1.必须包含以下文件：Chart.yaml，README.md，step.yaml，values.yaml，logo.png，templates/NOTES.txt；<br />
                  2.上述文件必须按照上述名称进行命名；<br />
                  3.step.yaml文件为values.yaml中的可配置参数，templates/NOTES.txt文件为应用的部署信息;<br />
                  4.templates/NOTES.txt主要用于用户部署后的访问,可以按照如下示例进行编写：<br />
                      &ensp;&ensp;this is a postgresql.<br />
                      &ensp;&ensp;author : Tom<br />
                      &ensp;&ensp;内部地址： {{ .Release.Name }}.{{ .Release.Namespace }}:5432<br />
                  5.请将文件夹压缩为“.zip”、“.tgz”、“.tar.gz”格式，如：名称为redis-ha的文件夹压缩为redis-ha.zip。<br />`
                "
              ></p>
            </div>
            <el-upload
              ref="step2_upload"
              :auto-upload="false"
              :limit="1"
              :data="app_info"
              action="/apaas/hubApi/market/app"
              :on-change="deployUploadChange"
              :on-remove="deployUploadRemove"
              :on-success="deployUploadSuccess"
              :on-error="deployUploadError"
              name="file"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将部署文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div class="apaas_button step_action" style="margin-top: 120px;">
          <el-button
            type="defalut"
            :loading="step2Loading"
            plain
            @click="step = 0"
          >
            上一步
          </el-button>
          <el-button
            type="primary"
            :loading="step2Loading"
            @click="step2Action"
          >
            创建应用
          </el-button>
        </div>
      </app-build-step>
      <app-build-step
        title="上传应用镜像"
        :step="2"
        :active-icon="require('@/assets/imgs/progress_ic_jingxiang.png')"
      >
        <el-form
          ref="image_info_form"
          class="step_form"
          label-position="top"
          :model="image_info"
          :rules="image_rules"
        >
          <el-form-item label="镜像名称：" prop="image_name">
            <el-input
              v-model="image_info.image_name"
              placeholder="请输入镜像名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号：" prop="tag">
            <el-input
              v-model="image_info.tag"
              placeholder="请输入版本号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="上传镜像包："
            prop="file"
            ref="step1_upload_item"
          >
            <el-upload
              ref="step1_upload"
              :auto-upload="false"
              :data="{
                app_id: app_id,
                image_name: image_info.image_name,
                tag: image_info.tag,
              }"
              :limit="1"
              :on-change="imageUploadChange"
              :on-remove="imageUploadRemove"
              :on-success="imageUploadSuccess"
              :on-error="imageUploadError"
              action="/apaas/hubApi/image/upload"
              name="file"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将镜像文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
          <div class="apaas_button upload_action">
            <el-button
              type="primary"
              @click="addImage"
              :loading="addImageLoading"
            >
              确认
            </el-button>
          </div>
          <div class="form_line"></div>
          <el-form-item label="上传镜像列表：">
            <div
              v-if="image_datas"
              class="image_list_container"
              v-infinite-scroll="loadImageList"
            >
              <apass-table
                :header="image_headers"
                :data="image_datas"
                :padding-left="60"
              ></apass-table>

              <p style="text-align: center" v-if="image_loading">
                加载中...
              </p>
              <p style="text-align: center" v-else-if="image_noMore">
                没有更多了
              </p>
            </div>
          </el-form-item>
        </el-form>
        <div class="apaas_button step_action">
          <el-button type="primary" @click="stepsDone">
            完成
          </el-button>
        </div>
        <image-detail
          ref="imageDetail"
          @refresh="refreshImageList"
        ></image-detail>
      </app-build-step>

      <template slot="action">
        <el-button @click="deployAction">
          前往部署
        </el-button>
        <el-button type="primary" @click="backToList">
          返回列表
        </el-button>
      </template>
    </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 apassTable from "@/components/apass-table";
import uploadFile from "@/components/general/upload_file";
import apassDialog from "@/components/apass-dialog";
import imageDetail from "@/components/image-detail";

export default {
  components: {
    appBuildSteps,
    appBuildStep,
    apassTable,
    uploadFile,
    apassDialog,
    imageDetail,
  },
  data() {
    var image_name_pass = (rule, value, callback) => {
      var reg = /^[a-z0-9|-]+$/;
      setTimeout(() => {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("只支持小写字母 数字 -"));
        }
      }, 100);
    };

    return {
      dialogInfo: {
        title: "",
        msg: "",
        submit: null,
      },
      step: 0,
      ywlys: [],
      types: [],
      orgs: [],
      logo: [],
      app_info: {
        name: "", // 应用名称
        version: "", // 应用版本
        ywly: "", // 业务领域id
        type: "", // 应用类型id
        logo: "", // 封面图片链接
        org: "", //  所属组织机构id
        yyjj: "", // 应用简介
        gnjj: "", // 功能简介
        cjsl: "", //  应用场景示例
      },
      app_rules: {
        name: [
          { required: true, message: "请输入应用名称", trigger: "blur" },
          { max: 16, message: "长度小于16个字符", trigger: "blur" },
        ],
        version: [
          { required: true, message: "请输入应用版本", trigger: "blur" },
        ],
        ywly: [
          { required: true, message: "请选择业务领域", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择应用类型", trigger: "change" },
        ],
        logo: [
          { required: true, message: "请上传应用封面", trigger: "change" },
        ],
        org: [
          { required: true, message: "请选择所属组织机构", trigger: "change" },
        ],
        yyjj: [
          { required: true, message: "请选择应用简介", trigger: "change" },
        ],
        gnjj: [
          { required: true, message: "请选择功能简介", trigger: "change" },
        ],
        cjsl: [
          { required: true, message: "请选择应用场景示例", trigger: "change" },
        ],
      },
      deploy_info: {
        file: "",
      },
      deploy_rules: {
        file: [
          { required: true, message: "请选择部署文件", trigger: "change" },
        ],
      },
      step2Loading: false,
      app_id: "",
      image_info: {
        image_name: "",
        tag: "",
        file: "",
      },
      image_rules: {
        image_name: [{ validator: image_name_pass, trigger: "blur" }],
        tag: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        file: [
          { required: true, message: "请选择镜像文件", trigger: "change" },
        ],
      },
      addImageLoading: false,
      image_headers: [],
      image_datas: [],
      image_total: 0,
      image_loading: false,
      image_noMore: false,
      image_page: 0,
      done: false,
    };
  },
  methods: {
    getYwlys() {
      this.$http
        .get("/apaas/hubApi/market/businessAreas")
        .then((response) => {
          this.ywlys = response.data.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getTypes() {
      this.$http
        .get("/apaas/hubApi/market/appTypes")
        .then((response) => {
          this.types = response.data.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getOrgs() {
      /* this.$http
        .get("/apaas/hubApi/market/departments")
        .then((response) => {
          this.orgs = response.data.data;
        })
        .catch((error) => {
          console.log(error);
        }); */

      this.$api.user.getNowUser().then(({ data }) => {
        if (data.success == 1) {
          this.orgs = [
            {
              id: data.data.department_id,
              name: data.data.department_name,
            },
          ];
          this.app_info.org = data.data.department_id;
        } else {
          console.log(data.errMsg);
        }
      });
    },
    getNewList(file) {
      this.app_info.logo = file[0].url;
    },
    step1Action() {
      this.$refs.app_info_form.validate((valid) => {
        if (valid) {
          this.step = 1;
        } else {
          return false;
        }
      });
    },
    getFileType(fileName) {
      const startIndex = fileName.lastIndexOf(".");

      if (startIndex != -1) {
        return fileName
          .substring(startIndex + 1, fileName.length)
          .toLowerCase();
      } else {
        return "";
      }
    },
    deployUploadChange(file) {
      const filtType = this.getFileType(file.name);

      if (filtType === "zip" || filtType === "gz" || filtType === "tgz") {
        this.deploy_info.file = file;
        this.$refs.step2_upload_item.clearValidate();
      } else {
        this.$message.error("部署文件格式错误!");
        this.deploy_info.file = "";
        this.$refs.step2_upload.clearFiles();
      }
    },
    deployUploadRemove() {
      this.deploy_info.file = "";
    },
    deployUploadSuccess(response) {
      if (response.success == 1) {
        this.$message({
          message: `提交成功`,
          type: "success",
        });
        this.step = 2;
        this.app_id = response.data;

        this.image_datas = [];
        this.image_page = 1;
        this.initImageList();
      } else {
        this.$message({
          message: response.errMsg || `提交失败`,
          type: "warning",
        });
      }

      this.step2Loading = false;
    },
    deployUploadError() {
      this.$message({
        message: `提交失败`,
        type: "warning",
      });
      this.step2Loading = false;
    },
    step2Action() {
      this.$refs.deploy_info_form.validate((valid) => {
        if (valid) {
          this.step2Loading = true;
          this.$refs.step2_upload.submit();
        } else {
          return false;
        }
      });
    },
    initImageList() {
      this.$http
        .get("/apaas/hubApi/image/imageUpList", {
          params: {
            page: this.image_page,
            size: 10,
            app_id: this.app_id,
          },
        })
        .then(({ data }) => {
          this.image_total = data.total || 0;
          this.image_datas.push(...(data.data || []));
          this.image_loading = false;
          this.image_noMore = false;
        })
        .catch((error) => {
          this.image_loading = false;
          console.log(error);
        });
    },
    loadImageList() {
      if (this.image_datas.length < this.image_total) {
        this.image_page++;
        this.image_loading = true;
        this.initImageList();
      } else if (this.image_total > 0) {
        this.image_noMore = true;
      }
    },
    imageUploadChange(file) {
      /* if (file.raw.type !== "application/x-tar") {
        this.$message.error("镜像文件只能是 TAR 格式!");
        this.image_info.file = "";
        this.$refs.step1_upload.clearFiles();
      } else { */
      this.image_info.file = file;
      this.$refs.step1_upload_item.clearValidate();
      // }
    },
    imageUploadSuccess(response) {
      if (response.success == 1) {
        this.$message({
          message: `上传镜像成功`,
          type: "success",
        });
        this.image_info.image_name = "";
        this.image_info.tag = "";
        this.refreshImageList();
      } else {
        this.$message({
          message: response.errMsg || `上传镜像失败`,
          type: "warning",
        });
      }

      this.image_info.file = "";
      this.$refs.step1_upload.clearFiles();
      this.addImageLoading = false;
    },
    imageUploadError() {
      this.$message({
        message: `上传镜像失败`,
        type: "warning",
      });
      this.addImageLoading = false;
    },
    imageUploadRemove() {
      this.image_info.file = "";
    },
    addImage() {
      this.$refs.image_info_form.validate((valid) => {
        if (valid) {
          this.addImageLoading = true;
          this.$refs.step1_upload.submit();
        } else {
          return false;
        }
      });
    },
    deleteImage(item) {
      this.dialogInfo.title = "";
      this.dialogInfo.msg = "是否删除该镜像？";
      this.dialogInfo.submit = () => {
        this.$http
          .delete(`/apaas/hubApi/image/del/${item.name}?app_id=${this.app_id}`)
          .then((response) => {
            if (response.data.success == 1) {
              this.$message({
                message: `删除成功`,
                type: "success",
              });
              this.refreshImageList();
            } else {
              this.$message({
                message: `删除失败`,
                type: "warning",
              });
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: `删除失败`,
              type: "warning",
            });
          });
      };
      this.$refs.dialog.show();
    },
    showImageDetail(item) {
      this.$refs.imageDetail.showDialog({
        ...item,
        app_id: this.app_id,
      });
    },
    stepsDone() {
      this.done = true;
    },
    deployAction() {
      // 跳转至应用详情进行部署操作
      this.$router.push(`/yygl/0/0/detail/${this.app_id}`);
    },
    backToList() {
      this.$router.push(`/yygl/0/0`);
    },
    refreshImageList() {
      this.image_datas = [];
      this.image_page = 1;
      this.initImageList();
    },
  },
  mounted() {
    this.getYwlys();
    this.getTypes();
    this.getOrgs();

    this.image_headers = [
      {
        label: "镜像名称",
        prop: "name",
        align: "left",
        type: "button",
        callback: this.showImageDetail,
      },
      {
        label: "版本号",
        prop: "tag",
        align: "center",
      },
      {
        label: "操作",
        type: "buttons",
        align: "center",
        actionList: [
          {
            label: "删除",
            class: "warn",
            callback: this.deleteImage,
          },
        ],
      },
    ];
  },
};
</script>

<style scoped>
.app_build-container {
  margin: -157px 40px 20px;
}
.app_build-container > .app_build_steps {
  min-height: calc(100vh - 150px - 43px);
  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;
}
.upload_action {
  margin: 20px 0 25px;
}
.form_line {
  border: 1px solid #f4f7fc;
  margin: 30px 0 24px;
}
.description_info {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  padding: 20px;
  border-radius: 10px;
  background-color: #f8f9fd;
  margin-bottom: 15px;
}
.description_info > * {
  font-size: 12px;
  color: #8890a7;
  line-height: 25px;
}
.description_info > i {
  font-size: 14px;
  margin-right: 10px;
}
.image_list_container {
  height: 284px;
  overflow-y: auto;
}
</style>

<style>
.app_build-container .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.app_build-container .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.app_build-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.app_build-container .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.app_build-container .apass_breadcrumb {
  padding: 0 20px;
}
.app_build-container .apass_breadcrumb > .el-breadcrumb .el-breadcrumb__inner {
  color: #626de9;
}
.app_build-container
  .apass_breadcrumb
  > .el-breadcrumb
  .el-breadcrumb__item:last-child
  .el-breadcrumb__inner {
  color: #b4c0f5;
}
.app_build-container .step_form {
  max-width: 970px;
  margin-top: 20px;
}
.app_build-container .step_form .el-form-item {
  margin: 0 10px 24px;
}
.app_build-container .step_form .el-form-item .el-select {
  width: 100%;
}
.app_build-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>
