<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">
      <app-build-step
        title="上传应用镜像"
        :step="0"
        :active-icon="require('@/assets/imgs/progress_ic_jingxiang.png')"
      >
        <el-form
          ref="step1_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="{
                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="apass_button upload_action">
            <el-button
              type="primary"
              @click="submitImage('step1_form')"
              :loading="step1UplaodLoading"
            >
              确认
            </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-if="image_noMore && image_datas.length > 0"
              >
                没有更多了
              </p>
            </div>
          </el-form-item>
        </el-form>
        <div class="apass_button step_action">
          <el-button type="primary" @click="goToStep1">
            下一步
          </el-button>
        </div>
        <image-detail ref="imageDetail"></image-detail>
      </app-build-step>
      <app-build-step
        title="上传部署文件"
        :step="1"
        :active-icon="require('@/assets/imgs/progress_ic_bushudata.png')"
      >
        <el-form
          ref="step2_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="apass_button step_action" style="margin-top: 120px;">
          <el-button type="primary" plain @click="preStep">
            上一步
          </el-button>
          <el-button type="primary" @click="goToStep2('step2_form')">
            下一步
          </el-button>
        </div>
      </app-build-step>
      <app-build-step
        title="应用基础信息填写"
        :step="2"
        :active-icon="require('@/assets/imgs/progress_ic_xinxitx.png')"
      >
        <el-form
          ref="step3_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="请选择所属组织">
              <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="apass_button step_action">
          <el-button
            type="primary"
            plain
            :loading="submitLoading"
            @click="preStep"
          >
            上一步
          </el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="sunbmitAction('step3_form')"
          >
            提交
          </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 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: () => ({
    step: 0,
    image_info: {
      image_name: "",
      tag: "",
      file: "",
    },
    image_rules: {
      image_name: [
        { required: true, message: "请输入镜像名称", trigger: "blur" },
      ],
      tag: [{ required: true, message: "请输入版本号", trigger: "blur" }],
      file: [{ required: true, message: "请选择镜像文件", trigger: "change" }],
    },
    step1UplaodLoading: false,
    image_headers: [],
    image_datas: [],
    image_total: 0,
    image_loading: false,
    image_noMore: false,
    image_page: 0,
    deploy_info: {
      file: "",
    },
    deploy_rules: {
      file: [{ required: true, message: "请选择部署文件", trigger: "change" }],
    },
    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" },
      ],
    },
    ywlys: [],
    types: [],
    orgs: [],
    logo: [],
    submitLoading: false,
    dialogInfo: {
      title: "",
      msg: "",
      submit: null,
    },
  }),
  methods: {
    preStep() {
      this.step--;
    },
    nextStep() {
      this.step++;
    },
    initImageList() {
      this.image_loading = true;
      this.$http
        .get("/apaas/hubApi/image/imageUpList", {
          params: {
            page: this.image_page,
            size: 10,
          },
        })
        .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.initImageList();
      } else {
        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) {
      this.$message({
        message: `上传镜像成功`,
        type: "success",
      });
      this.image_info.image_name = "";
      this.image_info.tag = "";
      this.image_info.file = "";
      this.$refs.step1_upload.clearFiles();
      this.step1UplaodLoading = false;
      this.image_datas = [];
      this.image_page = 1;
      this.initImageList();
    },
    imageUploadRemove() {
      this.image_info.file = "";
    },
    imageUploadError(response) {
      this.$message({
        message: `上传失败`,
        type: "warning",
      });
      this.step1UplaodLoading = false;
    },
    submitImage(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.step1UplaodLoading = true;
          this.$refs.step1_upload.submit();
        } else {
          return false;
        }
      });
    },
    deleteItem(item) {
      this.dialogInfo.title = "";
      this.dialogInfo.msg = "是否删除该镜像？";
      this.dialogInfo.submit = () => {
        this.$http
          .delete(`/apaas/hubApi/image/del/${item.name}`)
          .then((response) => {
            if (response.data.success == 1) {
              this.$message({
                message: `删除成功`,
                type: "success",
              });
              this.image_datas = [];
              this.image_page = 1;
              this.initImageList();
            } else {
              this.$message({
                message: `删除失败`,
                type: "warning",
              });
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: `删除失败`,
              type: "warning",
            });
          });
      };
      this.$refs.dialog.show();
    },
    goToStep1() {
      // if (this.image_total > 0) {
      this.nextStep();
      /* } else {
        this.$message({
          message: `您尚未上传任何镜像`,
          type: "warning",
        });
      } */
    },
    goToStep2(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.nextStep();
        } else {
          return false;
        }
      });
    },
    getNewList(file) {
      this.app_info.logo = file.url;
    },
    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);
        });
    },
    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) {
      this.$message({
        message: `提交成功`,
        type: "success",
      });
      this.submitLoading = false;
      this.$router.push("/yygl/2/0");
    },
    deployUploadError() {
      this.$message({
        message: `提交失败`,
        type: "warning",
      });
    },
    sunbmitAction(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.$refs.step2_upload.submit();
        } else {
          return false;
        }
      });
    },
    getFileType(fileName) {
      const startIndex = fileName.lastIndexOf(".");

      if (startIndex != -1) {
        return fileName
          .substring(startIndex + 1, fileName.length)
          .toLowerCase();
      } else {
        return "";
      }
    },
    showImageDetail(item) {
      this.$refs.imageDetail.showDialog(item);
    },
  },
  mounted() {
    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.deleteItem,
          },
        ],
      },
    ];
    this.image_datas = [];
    this.image_page = 1;
    this.initImageList();
    this.getYwlys();
    this.getTypes();
    this.getOrgs();
  },
};
</script>

<style scoped>
.app_build-container {
  margin: -157px 40px 20px;
}
.app_build-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;
}
.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>
