<template>
  <div>
    <el-dialog
      :title="title"
      :destroy-on-close="true"
      :visible.sync="Visible"
      width="30%"
      @close="handleClose"
      :close-on-click-modal="false"
      top="10vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入资源名称"></el-input>
        </el-form-item>
        <el-form-item label="权限类型" prop="authType">
          <el-select v-model="form.authType">
            <el-option
              v-for="(v, key) in dict.authType"
              :key="key"
              :label="v"
              :value="Number(key)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="url-params-box" label="链接地址">
          <el-form-item
            class="url-params"
            v-for="(v, i) in form.urls"
            :key="i"
            :prop="`urls.${i}.value`"
            :rules="[
              { required: true, validator: validatorUrl, trigger: 'blur' },
            ]"
          >
            <el-input
              style="margin-right: 10px"
              v-model="v.value"
              placeholder="请输入链接地址"
            />
            <div class="flex">
              <el-button type="primary" @click="changeParams(i, 'add')">
                <i class="el-icon-plus"></i>
              </el-button>
              <el-button
                type="danger"
                v-if="i > 0"
                @click="changeParams(i, 'remove')"
                ><i class="el-icon-minus"></i
              ></el-button>
            </div>
          </el-form-item>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleRest">重 置</el-button>
        <el-button
          size="medium"
          type="primary"
          @click="handleOk"
          :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveResource } from "@/api/system";
export default {
  props: {
    title: {
      type: String,
      required: true,
      default: "",
    },
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    dict: {
      type: Object,
      required: true,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      form: {
        name: "",
        authType: "",
        url: "",
        urls: [
          {
            value: "",
          },
        ],
      },
      rules: {
        name: [{ required: true, message: "请输入资源名称", trigger: "blur" }],
        authType: [
          { required: true, message: "请选择权限类型", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    Visible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      },
    },
  },
  created() {},
  methods: {
    // 确定
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let res = await saveResource({
            ...this.form,
            url: this.form.urls.map((v) => v.value).join(","),
          });
          let { code, msg } = res.data;
          if (code == 1) {
            this.$message.success(msg);
            this.$emit("success");
            this.handleClose();
          }
          this.loading = false;
        }
      });
    },
    // 新增
    onAdd() {
      Object.assign(this.form, this.$options.data().form);
      this.form.id && this.$delete(this.form, "id");
    },
    // 编辑
    onEdit(row) {
      setTimeout(() => {
        this.form = { ...row };
        let arr = [];
        if (this.form.url) {
          arr = this.form.url.split(",").map((v) => {
            return {
              value: v,
            };
          });
        }
        this.$set(this.form, "urls", arr);
      }, 10);
    },
    // 重置
    handleRest() {
      this.$resetForm("form");
      this.$set(this.form, "urls", [{ value: "" }]);
    },
    // 关闭
    handleClose() {
      this.$resetForm("form");
      this.Visible = false;
    },
    // 判断是否存在链接
    isRepeat(val) {
      return this.form.urls.filter((v) => v.value == val).length > 1;
    },
    // 校验链接地址
    validatorUrl(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入链接"));
      } else if (this.isRepeat(value)) {
        callback(new Error("重复的链接地址"));
      } else {
        callback();
      }
    },
    changeParams(index, type) {
      if (type == "add") {
        let obj = {
          value: "",
        };
        if (this.form.urls.some((v) => !v.value)) {
          this.$message.warning("请先完成前面地址的填写");
          return;
        }
        this.form.urls.splice(index + 1, 0, obj);
      } else {
        this.form.urls.splice(index, 1);
      }
      // this.$forceUpdate();
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-select) {
  width: 100%;
}
:deep(.url-params) {
  margin-bottom: 22px;
  .el-form-item__content {
    display: flex;
  }
}
</style>
