<template>
  <el-dialog
    :title="'通过服务构建应用'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :fullscreen="true"
    :append-to-body="true"
    destroy-on-close
  >
    <el-steps :active="active" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="服务组件"></el-step>
    </el-steps>
    <el-form
      ref="applicationsForm"
      :model="applicationsForm"
      :rules="dataRule"
      label-width="40px"
    >
      <el-form-item v-show="active == 1">
        <h3 style="margin-left: 200px; line-height: 0.6">基本信息</h3>
        <div style="margin-left: 200px; line-height: 0.2">
          对应用的名称描述信息等基本的信息定义
        </div>
        <br />
        <el-form-item label="应用名称" prop="applicationName" labelWidth="25%">
          <el-input
            v-model="applicationsForm.applicationName"
            style="width: 400px"
            clearable
          ></el-input>
          <div style="width: 400px; line-height: 1">
            最长 253
            个字符，只能包含小写字母、数字及分隔符("-")，且必须以小写字母或数字开头及结尾
          </div> </el-form-item
        ><br />
        <el-form-item label="应用类型" prop="applicationType" labelWidth="25%">
          <el-select
            v-model="applicationsForm.applicationType"
            placeholder="请选择"
          >
            <el-option label="水文" value="水文"></el-option>
            <el-option label="采矿" value="采矿"></el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item
          label="应用版本(可选)"
          prop="applicationVersion"
          labelWidth="25%"
        >
          <el-input
            v-model="applicationsForm.applicationVersion"
            style="width: 400px"
            clearable
          ></el-input>
          <div style="width: 400px; line-height: 1">
            最长 16 个字符，只能包含小写字母及数字
          </div> </el-form-item
        ><br />
        <!-- <el-form-item
          label="描述信息"
          prop="applicationDescription"
          labelWidth="25%"
        >
          <el-input
            v-model="applicationsForm.applicationDescription"
            style="width: 400px"
            maxlength="256"
            show-word-limit
            type="textarea"
            placeholder="描述信息不超过 256 个字符"
            :rows="4"
          ></el-input>
        </el-form-item> -->
      </el-form-item>
      <el-form-item v-show="active == 2">
        <h3 style="margin-left: 100px">根据应用设置相应的组件</h3>
        <el-form-item v-for="(item, index) in service" :key="index">
          <el-card
            shadow="hover"
            style="font-size: 20px; width: 600px; margin-left: 140px"
            ><i class="el-icon-service"></i> {{ item.serviceData.name }}
            <el-button
              type="danger"
              icon="el-icon-delete"
              style="position: absolute; right: 500px"
              circle
              @click="deleteService(index)"
            ></el-button
          ></el-card>
          <add-service
            ref="addService"
            v-if="item.visible"
            @submitServiceData="
              (serviceData) => {
                item.serviceData = serviceData;
              }
            "
            @cancel="deleteService"
          ></add-service> </el-form-item
        ><br />
        <el-button
          plain
          style="margin-left: 100px; width: 600px"
          @click="addService"
          >添加服务</el-button
        >
      </el-form-item>
    </el-form>
    <div
      style="
        position: fixed;
        bottom: 0;
        text-align: right;
        right: 40px;
        bottom: 40px;
      "
    >
      <el-button style="margin-top: 12px" @click="cancel">取消</el-button>
      <el-button
        type="primary"
        plain
        style="margin-top: 12px"
        @click="pre"
        v-if="active == 2"
        >上一步</el-button
      >
      <el-button
        type="primary"
        plain
        style="margin-top: 12px"
        @click="next"
        v-if="active == 1"
        >下一步</el-button
      >
      <el-button
        type="primary"
        round
        style="margin-top: 12px"
        @click="submit"
        v-if="active == 2"
        >创建</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import AddService from "./applications-add-service.vue";
export default {
  data() {
    return {
      visible: false,
      active: 1,
      service: [],
      applicationsForm: {
        applicationName: "",
        applicationAlias: "",
        applicationId: 0,
        applicationVersion: "v1",
        lastUpdateTime: "",
        parentClusterId: "",
        applicationStatus: "",
        parentProjectId: "",
        createTime: "",
        creatorId: "",
        applicationDescription: "",
        applicationType: "",
      },
      dataRule: {
        applicationName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        applicationVersion: [],
        applicationType: [
          { required: true, message: "应用类型不能为空", trigger: "blur" },
        ],
        applicationDescription: [],
      },
    };
  },
  components: {
    AddService,
  },
  methods: {
    init(id) {
      this.applicationsForm.applicationId = id || 0;
      this.visible = true;
      this.active = 1;
      this.service = [];
      this.$nextTick(() => {
        this.$refs["applicationsForm"].resetFields();
      });
    },
    // 表单提交
    submit() {
      this.$refs["applicationsForm"].validate((valid) => {
        if (valid) {
          // 如果没有添加服务则提示添加至少一个服务
          if (this.service.length === 0) {
            this.$message({
              message: "请至少添加一个服务",
              type: "error",
              duration: 2000,
            });
            return;
          }
          this.$http({
            url: this.$http.adornUrl("/kubeSphereApi/applicationBuild"),
            method: "post",
            data: {
              service: this.service,
              applicationName: this.applicationsForm.applicationName,
              applicationVersion: this.applicationsForm.applicationVersion,
              applicationDescription:
                this.applicationsForm.applicationDescription,
              creator: this.$store.state.user.name,
            },
          })
            .then((res) => {
              console.log("后端的返回值", res);
              if (res.data && res.data.code !== 500) {
                this.$http({
                  url: this.$http.adornUrl("/generator/applications/save"),
                  method: "post",
                  data: this.$http.adornData({
                    applicationName: this.applicationsForm.applicationName,
                    applicationType: this.applicationsForm.applicationType,
                    applicationVersion:
                      this.applicationsForm.applicationVersion,
                    applicationStatus: "运行中",
                    parentProjectName: "mkcloud",
                    createTime: new Date().getTime(),
                    creatorName: this.$store.state.user.name,
                    applicationDescription:
                      this.applicationsForm.applicationDescription,
                  }),
                }).then(({ data }) => {
                  console.log(data);
                  if (data && data.code !== 500) {
                    this.$message({
                      message: "操作成功",
                      type: "success",
                      duration: 1500,
                      onClose: () => {
                        this.visible = false;
                        this.$emit("refreshDataList");
                      },
                    });
                  } else {
                    this.$message.error(data.msg);
                  }
                });
              } else {
                console.log("创建应用失败", error);
                this.$message.error("创建应用失败");
              }
            })
            .catch((error) => {
              console.log("创建应用失败", error);
              this.$message.error("创建应用失败");
            });
        } else {
          this.active = 1;
          this.$message({
            message: "请填写必填字段",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    // 前进
    next() {
      this.active++;
    },
    // 后退
    pre() {
      this.active--;
    },
    // 取消
    cancel() {
      this.visible = false;
    },
    // 添加服务
    addService() {
      const index = this.service.length;
      this.service.push({
        index,
        visible: true,
        serviceData: {},
      });
      this.$nextTick(() => {
        this.$refs.addService[index].init(index);
      });
    },
    // 删除服务
    deleteService(index) {
      console.log("index", index);
      this.service.splice(index, 1);
    },
  },
};
</script>
