<template>
  <el-dialog
    :title="'容器设置'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :append-to-body="true"
    width="80%"
  >
    <el-steps :active="active" finish-status="success">
      <el-step title="基本设置"></el-step>
      <el-step title="高级设置"></el-step>
      <el-step title="外部访问"></el-step>
    </el-steps>
    <el-form
      ref="containerForm"
      :model="containerForm"
      :rules="dataRule"
      label-width="80px"
    >
      <el-form-item v-show="active == 1">
        <el-form-item label="镜像" prop="imageName" labelWidth="15%">
          <el-input
            style="width: 600px"
            class="input-with-select"
            v-model="containerForm.imageName"
            placeholder="请输入名称，如果不加标签默认为latest版本，例如：nginx:latest"
            clearable
          >
            <el-select
              slot="prepend"
              style="width: 120px"
              v-model="imageSource"
            >
              <el-option label="dockerhub" value=""></el-option>
              <el-option label="harbor" value="harbor.od.com/"></el-option>
            </el-select>
          </el-input>
          <div style="width: 400px; line-height: 2">
            可以从dockerhub仓库拉取镜像，也可以拉取harbor的私有镜像
          </div> </el-form-item
        ><br />
        <el-form-item label="容器名称" prop="name" labelWidth="15%">
          <el-input
            v-model="containerForm.name"
            style="width: 400px"
            clearable
          ></el-input>
          <div style="width: 400px; line-height: 1">
            最长 253
            个字符，只能包含小写字母、数字及分隔符("-")，且必须以小写字母或数字开头及结尾
          </div> </el-form-item
        ><br />
        <el-form-item label="容器类型" labelWidth="15%">
          <el-select v-model="containerForm.containerType" style="width: 400px">
            <el-option label="工作容器" value="containers"></el-option>
            <el-option label="初始容器" value="initContainers"></el-option>
          </el-select> </el-form-item
        ><br />
        <el-card
          shadow="always"
          class="box-card"
          style="font-size: 15px; width: 850px"
        >
          <el-form-item class="card-header">
            <el-row :gutter="10">
              <el-col :span="8"> 设置容器的访问策略(至少设置一个端口) </el-col>
              <el-col :span="8">
                <el-button plain style="width: 150px" @click="addPort"
                  >添加端口</el-button
                >
              </el-col>
              <el-col :span="8">
                点击按钮将服务暴露&nbsp;&nbsp;<el-checkbox
                  v-model="containerForm.nodePort"
                  border
                >
                  NodePort
                </el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
          <br />
          <el-form-item
            v-for="(item, index) in containerForm.ports"
            class="text item"
            :key="index"
          >
            <el-form-item prop="ports">
              <el-card shadow="always" style="font-size: 15px; width: 800px">
                <el-row :gutter="50">
                  <el-col :span="8">
                    <el-input
                      style="width: 250px"
                      class="input-with-select"
                      v-model="item.lastName"
                      placeholder="输入端口名称"
                      clearable
                    >
                      <el-select
                        slot="prepend"
                        style="width: 100px"
                        v-model="item.firstName"
                      >
                        <el-option label="HTTP" value="http-"></el-option>
                        <el-option label="HTTPS" value="https-"></el-option>
                        <el-option label="TCP" value="tcp-"></el-option>
                      </el-select>
                    </el-input>
                  </el-col>
                  <el-col :span="6"
                    ><el-input
                      v-model.number="item.containerPort"
                      style="width: 200px"
                      clearable
                    >
                      <div slot="prepend">容器端口</div>
                    </el-input></el-col
                  >
                  <el-col :span="7"
                    ><el-input
                      v-model.number="item.servicePort"
                      style="width: 200px"
                      clearable
                    >
                      <div slot="prepend">服务端口</div>
                    </el-input></el-col
                  ><el-col :span="2">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      v-if="index > 0"
                      @click="deletePort(index)"
                    ></el-button
                  ></el-col>
                </el-row> </el-card
            ></el-form-item>
          </el-form-item>
        </el-card>
      </el-form-item>
      <el-form-item v-show="active == 2">
        <el-card
          shadow="always"
          class="box-card"
          style="font-size: 15px; width: 600px; margin-left: 80px"
        >
          <h3 class="card-header">启动命令(多个参数请使用","分割)</h3>
          <div class="text item">
            <h4 style="line-height: 0">运行命令</h4>
            <el-input
              v-model="containerForm.command"
              style="width: 400px"
              type="textarea"
              placeholder="命令"
              :rows="4"
            ></el-input>
          </div>
          <div class="text item">
            <h4 style="line-height: 0">参数</h4>
            <el-input
              v-model="containerForm.args"
              style="width: 400px"
              type="textarea"
              placeholder="参数"
              :rows="4"
            ></el-input>
          </div>
        </el-card>
        <br />
        <el-card
          class="box-card"
          shadow="always"
          style="font-size: 15px; width: 600px; margin-left: 80px"
        >
          <div class="card-header">
            <h4 style="line-height: 0">环境变量</h4>
            <div style="line-height: 0; font-size: 10px">
              添加容器的环境变量
            </div>
          </div>
          <br />
          <el-form-item
            v-for="(item, index) in containerForm.env"
            :key="index"
            class="text item"
          >
            <el-input
              v-model="item.name"
              style="width: 250px"
              clearable
              placeholder="名称"
            ></el-input>
            <el-input
              v-model="item.value"
              style="width: 250px"
              clearable
              placeholder="值"
            ></el-input>
            <el-button
              type="danger"
              icon="el-icon-delete"
              style="position: absolute; right: 10px"
              circle
              @click="deleteEnv(index)"
            ></el-button>
          </el-form-item>
          <el-button
            type="primary"
            icon="el-icon-edit"
            round
            style="margin-left: 490px; margin-top: 20px"
            @click="addEnv"
          ></el-button>
        </el-card>
      </el-form-item>
      <el-form-item v-show="active == 3">
        <el-card
          class="box-card"
          shadow="always"
          style="font-size: 20px; width: 600px; margin-left: 80px"
        >
          <el-form-item class="card-header"
            ><h3>存储卷挂载设置</h3></el-form-item
          >
          <el-form-item class="text item">
            <h4 style="line-height: 0">若要挂载，请选择现有的存储卷</h4>
            <el-select
              style="width: 500px; height: 60px"
              v-model="containerForm.claimName"
              :disabled="containerForm.mountMode == '' ? true : false"
            >
              <el-option
                v-for="item in volumeList"
                :key="item.volumesId"
                :label="`${item.volumesName}(${
                  item.volumesMount === '未挂载' ? '闲置' : '已使用'
                })\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0${
                  item.volumesSize
                }Gi\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0${item.accessMode}`"
                :value="item.volumesName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="挂载模式" class="text item">
            <el-select v-model="containerForm.mountMode">
              <el-option label="不挂载" value=""></el-option>
              <el-option label="只读" value="true"></el-option>
              <el-option label="读写" value="false"></el-option>
            </el-select>
            <el-input
              placeholder="容器挂载路径，例如：/data"
              style="width: 250px"
              v-model="containerForm.mountPath"
              :disabled="containerForm.mountMode == '' ? true : false"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-card>
        <br />
        <el-card
          class="box-card"
          shadow="always"
          style="font-size: 20px; width: 600px; margin-left: 80px"
        >
          <el-form-item class="card-header">
            <h3 style="line-height: 0">外网访问</h3>
            <div style="line-height: 0">
              可以设置应用的外网访问规则(Ingress)
            </div>
          </el-form-item>
          <br />
          <el-form-item
            class="text item"
            v-for="(item, index) in containerForm.ports"
            :key="index"
          >
            <el-card shadow="nerver" style="font-size: 15px">
              <el-row :gutter="10">
                <el-col :span="4">
                  <el-select v-model="item.rules.protocol" style="width: 80px">
                    <el-option label="无" value=""></el-option>
                    <el-option label="http" value="http"></el-option>
                    <el-option label="https" value="https"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="20">
                  <el-input
                    clearable
                    v-model="item.rules.path"
                    placeholder="路径"
                    :disabled="item.rules.protocol == '' ? true : false"
                  >
                    <div slot="prepend" style="width: 100px">
                      端口号:{{ item.servicePort }}
                    </div>
                  </el-input>
                </el-col> </el-row
              ><br />
              <el-form-item label="域名" labelWidth="10%">
                <el-input
                  clearable
                  v-model="item.rules.host"
                  style="width: 300px"
                  :disabled="item.rules.protocol == '' ? true : false"
                ></el-input>
              </el-form-item>
            </el-card>
          </el-form-item>
        </el-card>
      </el-form-item>
      <div style="text-align: right; margin: 0">
        <el-button style="margin-top: 12px" @click="cancel">取消</el-button>
        <el-button
          type="primary"
          plain
          style="margin-top: 12px"
          @click="pre"
          v-if="active > 1"
          >上一步</el-button
        >
        <el-button
          type="primary"
          plain
          style="margin-top: 12px"
          @click="next"
          v-if="active < 3"
          >下一步</el-button
        >
        <el-button
          type="primary"
          round
          style="margin-top: 12px"
          @click="submit"
          v-if="active == 3"
          >创建</el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  data() {
    const checkPorts = (rule, value, callback) => {
      const index = this.containerForm.ports.length;
      let resdata = JSON.parse(JSON.stringify(value));
      console.log("resdata", resdata);
      let data = resdata[index - 1];
      if (
        data.containerPort == undefined ||
        data.containerPort == "" ||
        data.containerPort == null
      )
        return callback(new Error("请输入容器端口"));
      if (!/^[0-9]*$/.test(data.containerPort))
        return callback(new Error("容器端口必须为数字"));
      return callback();
    };
    return {
      visible: false,
      active: 1,
      index: 0,
      imageSource: "",
      volumeList: [],
      containerForm: {
        // 镜像的名字
        imageName: "",
        // 镜像容器的名字
        name: "",
        // 容器类型， 默认是工作容器
        containerType: "containers",
        // 容器访问策略
        ports: [
          {
            // 名字前缀
            firstName: "http-",
            // 名字后缀
            lastName: "",
            containerPort: undefined,
            servicePort: undefined,
            // 规则
            rules: {
              protocol: "",
              path: "",
              host: "",
            },
          },
        ],
        // 启动命令
        command: "",
        // 启动参数
        args: "",
        // 环境变量
        env: [],
        // 挂载存储卷的名字
        claimName: "",
        // 挂载模式
        mountMode: "",
        // 是否暴露端口
        nodePort: "false",
      },
      dataRule: {
        imageName: [
          {
            required: true,
            message: "请输入名称，例如：nginx:latest",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        ports: [{ validator: checkPorts, trigger: "change" }],
      },
    };
  },
  methods: {
    init(index) {
      this.visible = true;
      this.index = index;
      this.containerForm.name =
        "container-" + Math.random().toString(36).slice(-6);
      this.$nextTick(() => {
        this.$refs["containerForm"].resetFields();
        this.$http({
          url: this.$http.adornUrl("/generator/volumes/list"),
          method: "get",
          params: this.$http.adornParams({
            limit: 100,
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.volumeList = data.page.list;
            console.log(this.volumeList);
          } else {
            this.$message.warning("获取存储卷错误");
          }
        });
      });
    },
    submit() {
      this.$refs["containerForm"].validate((valid) => {
        if (valid) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 3000,
            onClose: () => {
              this.visible = false;
              // 将挂载模式的string转换为boolean
              if (this.containerForm.mountMode !== "") {
                this.containerForm.mountMode =
                  this.containerForm.mountMode === "false" ? false : true;
              }
              console.log("容器镜像数据", this.containerForm);
              this.$emit("submitContainerData", this.containerForm);
            },
          });
        } else {
          this.$message({
            message: "请填入必填项目",
            type: "error",
            duration: 3000,
          });
          this.active = 1;
        }
      });
    },
    cancel() {
      console.log("删除了container窗口");
      this.$nextTick(() => {
        this.visible = false;
        this.$emit("cancel", this.index);
      });
    },
    next() {
      this.active++;
    },
    pre() {
      this.active--;
    },
    // 添加容器端口
    addPort() {
      this.containerForm.ports.push({
        firstName: "http-",
        lastName: "",
        containerPort: undefined,
        servicePort: undefined,
        rules: {
          protocol: "",
          path: "",
          host: "",
        },
      });
    },
    // 删除容器端口
    deletePort(index) {
      console.log("index", index);
      this.containerForm.ports.splice(index, 1);
    },
    // 添加环境变量
    addEnv() {
      this.containerForm.env.push({
        name: "",
        value: "",
      });
    },
    // 删除环境变量
    deleteEnv(index) {
      this.containerForm.env.splice(index, 1);
    },
  },
};
</script>
