<template>
  <el-dialog
    class="modify-app-config-item"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        v-if="!isEdit && group && group.available && group.available.length"
        prop="selectAvailableKey"
        label="可选配置项："
      >
        <el-select
          v-model="selectAvailableKey"
          placeholder="请选择未配置的配置项"
          class="width-full"
          @change="availableKeyChange"
        >
          <el-option
            v-for="item in group.available"
            :key="item.key"
            :value="item.key"
            :label="item.key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="key" label="配置项：">
        <span v-if="isEdit || isStrictKey">
          {{ modalForm.key }}
        </span>
        <el-input
          v-else
          v-model.trim="modalForm.key"
          placeholder="请输入配置项"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="value" label="配置值：">
        <value-modify
          v-model="modalForm.value"
          :available="available"
        ></value-modify>
      </el-form-item>

      <el-form-item v-if="modalForm.comment" label="注释：">
        {{ modalForm.comment }}
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="danger" @click="cancel" plain>取消</el-button>
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { appConfigItemUpdate } from "../api";
import ValueModify from "./ValueModify.vue";

const initModalForm = {
  appId: "",
  moduleId: "",
  versionId: "",
  envId: "",
  key: "",
  value: "",
  comment: ""
};

export default {
  name: "modify-app-config-item",
  components: {
    ValueModify
  },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    //  name,prefix,available,unvalidKeys
    group: {
      type: Object,
      default: null
    }
  },
  data() {
    const keyValidator = (rule, value, callback) => {
      if (this.isEdit) return callback();

      if (
        this.group &&
        this.group.available &&
        !this.group.available.length &&
        !value.startsWith(this.group.prefix)
      ) {
        return callback(
          new Error(`配置项需要带有${this.group.prefix}的前缀。`)
        );
      }

      if (this.selectAvailableKey.includes(".*.")) {
        const regCont = this.selectAvailableKey
          .split(".")
          .join("\\.")
          .replace("*", ".*");
        const reg = new RegExp(`^${regCont}$`);
        if (!reg.test(value) || value === this.selectAvailableKey) {
          return callback(
            new Error(`配置项需要满足${this.selectAvailableKey}的格式。`)
          );
        }
      }

      if (this.group.unvalidKeys.includes(value)) {
        return callback(new Error("配置项已经存在"));
      }

      callback();
    };

    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        selectAvailableKey: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.selectAvailableKey) {
                callback(new Error("请选择未配置的配置项"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        key: [
          {
            required: true,
            message: "请输入配置项",
            trigger: "change"
          },
          {
            max: 100,
            message: "配置项不能超过100字符",
            trigger: "change"
          },
          {
            validator: keyValidator,
            trigger: "change"
          }
        ],
        value: [
          {
            required: true,
            message: "请设置配置值",
            trigger: "change"
          }
        ]
      },
      available: null,
      selectAvailableKey: "",
      selectAvailable: {},
      isStrictKey: false
    };
  },
  computed: {
    isEdit() {
      return !!this.instance.key;
    },
    title() {
      return this.instance.key ? "编辑" : "添加" + "应用配置配置项";
    }
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      this.$refs.modalFormComp.clearValidate();
    },
    visibleChange() {
      this.selectAvailableKey = "";
      this.selectAvailable = {};
      this.isStrictKey = false;
      this.available = this.instance.available;
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    availableKeyChange() {
      this.selectAvailable = this.group.available.find(
        item => item.key === this.selectAvailableKey
      );
      this.isStrictKey = !this.selectAvailableKey.includes(".*.");
      this.modalForm.key = this.selectAvailableKey;
      this.modalForm.value = this.selectAvailable.defaultValue || null;
      this.available = this.selectAvailable;
      this.$refs.modalFormComp.validate().catch(() => {});
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = { ...this.modalForm };
      const data = await appConfigItemUpdate(datas).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

      this.$message.success("修改成功！");
      this.$emit("modified", data);
      this.cancel();
    }
  }
};
</script>
