<template>
  <div class="data-info">
    <el-card>
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataFormRef"
        label-width="120px"
      >
        <!--   <el-form-item label="编码:">
          <el-input v-model="dataForm.code"></el-input>
        </el-form-item> -->
        <el-form-item label="名称 :">
          <el-input v-model="dataForm.name"></el-input>
        </el-form-item>
        <el-form-item label="取值类型:">
          <el-select
            v-model="dataForm.value_type"
            placeholder="请选择取值类型"
            size="large"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in valueTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="取值:" v-if="dataForm.value_type == 1">
          <el-input v-model="dataForm.value"></el-input>
        </el-form-item>
        <el-form-item label="取值:" v-if="dataForm.value_type == 2">
          <el-input v-model="dataForm.value"></el-input>
        </el-form-item>
        <el-form-item
          label="取值:"
          v-if="dataForm.value_type == 3"
          prop="value"
        >
          <el-input v-model="dataForm.value"></el-input>
        </el-form-item>
        <el-form-item
          label="取值:"
          v-if="dataForm.value_type == 4"
          prop="value"
        >
          <el-input v-model="dataForm.value">
            <template slot="append">%</template></el-input
          >
        </el-form-item>
        <el-form-item
          label="取值:"
          v-if="dataForm.value_type == 5"
          prop="value"
        >
          <el-input v-model="dataForm.value"></el-input>
        </el-form-item>
        <el-form-item label="取值范围:" v-if="dataForm.value_type == 2">
          <el-select
            ref="categorySelect"
            v-model="dataForm.value_item"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="点击enter创建选择标签"
            style="width: 100%"
            popper-class="custom-select-dropdown"
          >
          </el-select>
          <!-- <el-input type="textarea" v-model="dataForm.value_item"   @keydown.native.enter="createTag"></el-input> -->
        </el-form-item>
        <el-form-item label="介绍:">
          <el-input type="textarea" v-model="dataForm.intro"></el-input>
        </el-form-item>

        <el-form-item label="状态:">
          <el-select
            v-model="dataForm.status"
            placeholder="请选择状态"
            size="large"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="text-align: right; margin-top: 20px">
      <el-button type="warning" @click="btnSave">确认保存</el-button>
    </div>
  </div>
</template>

<script>
import { createParams, updateParams, getParamsInfo } from "@/api/params";
import { status } from "nprogress";
export default {
  emits: ["onClose"],
  props: {
    id: {
      type: Number,
      default: 0,
    },
    type: {
      type: Number,
      default: 1,
    },
  },
  watch: {
    type: {
      handler(val) {
        if (val == null && val <= 0) return;
        this.dataForm.type = val;
      },
      immediate: true,
      deep: true,
    },
    id: {
      handler(v) {
        console.log(v);
        let _this = this;
        if (v == null || v <= 0) return;
        _this.getInfo(v);
      },
      immediate: true,
      deep: true,
    },
    hideDropdown(newVal) {
      const dropdown = document.querySelector(".custom-select-dropdown");
      if (dropdown) {
        dropdown.style.display = newVal ? "none" : "";
      }
    },
  },
  data() {
    const validateBucketName = (rule, value, callback) => {
      if (this.dataForm.value_type == 5) {
        const regex = /^\d+$/;
        if (!regex.test(value)) {
          callback(new Error("请输入整数"));
        } else {
          callback();
        }
      } else if (this.dataForm.value_type == 4) {
        const regex = /^(?:100|\d{1,2}(?:\.\d+)?)$/;
        if (!regex.test(value)) {
          callback(new Error("请输入有效的百分数（0-100%）"));
        } else {
          callback();
        }
      } else if (this.dataForm.value_type == 3) {
        const regex = /^\d+(\.\d+)?$/;
        if (!regex.test(value)) {
          callback(new Error("请输入有效的小数"));
        } else {
          callback();
        }
      }
    };
    return {
      activeName: "base",
      currentCategory: [],
      valueTypeList: [
        {
          value: 0,
          name: "请选择取值类型",
        },
        {
          value: 1,
          name: "输入框",
        },
        {
          value: 2,
          name: "下拉选择",
        },
        {
          value: 3,
          name: "小数",
        },
        {
          value: 4,
          name: "百分比",
        },
        {
          value: 5,
          name: "整数",
        },
      ],
      allCategories: [],
      typeList: [
        {
          value: 1,
          name: "变量",
        },
        {
          value: 2,
          name: "常量",
        },
      ],
      dataForm: {
        id: 0,
        type: 1,
        name: "",
        value: "",
        value_type: 0,
        value_item: " ",
        intro: "",
        status: 5,
      },
      statusOptions: [
        {
          value: "",
          label: "请选择状态",
        },
        {
          value: 5,
          label: "使用中",
        },
        {
          value: 6,
          label: "已停用",
        },
      ],
      dataRule: {
        value: [
          { required: true, message: "请输入取值", trigger: "blur" },
          { validator: validateBucketName, trigger: "blur" },
        ],
      },
      tags: [],
      shouldPreventDropdown: true,
      hideDropdown: false,
    };
  },

  mounted() {
    let _this = this;
  },
  methods: {
    handleSelectFocus(event) {
      this.$refs.categorySelect.blur();
    },
    createTag() {
      // Logic to create a tag
      console.log(
        "Enter key pressed, create a tag with:",
        this.dataForm.value_item
      );
      // Example: Add the value to a tags array
      if (this.dataForm.value_item.trim() !== "") {
        this.tags.push(this.dataForm.value_item.trim());
        this.dataForm.value_item = ""; // Clear the input
      }
      console.log(this.tags);
    },
    resetForm() {
      // 重置所有表单字段
      this.dataForm = {
        id: 0,
        type: this.type, // 保留传入的 type
        name: "",
        value: "",
        value_type: 0,
        value_item: "",
        intro: "",
        status: 5,
      };
      // 如果使用 el-form，可以调用其 resetFields 方法
      this.$nextTick(() => {
        if (this.$refs.dataFormRef) {
          this.$refs.dataFormRef.resetFields();
        }
      });
    },
    //保存更新
    btnSave(e) {
      let _this = this;
      _this.$refs.dataFormRef.validate((valid) => {
        if (valid) {
          if (_this.dataForm.value_type == 1) {
            _this.dataForm.value_item = _this.dataForm.value;
          } else if (_this.dataForm.value_type == 4) {
            // 将输入值转换为数字
            const num = parseFloat(_this.dataForm.value);
            // 格式化为百分数，保留两位小数
            const percentage = num.toFixed(2) + "%";
            _this.dataForm.value = percentage;
          } else if (_this.dataForm.value_type == 2) {
            _this.dataForm.value_item = _this.dataForm.value_item.join(",");
          }
          _this.dataForm.code = _this.dataForm.name;
          if (_this.dataForm.id > 0) {
            updateParams(_this.dataForm).then((res) => {
              if (res.status != 200) return;
              _this.resetForm(); // 添加这行
              _this.$alert("信息更新成功");
              _this.$emit("onClose");
            });
          } else {
            createParams(_this.dataForm).then((res) => {
              if (res.status != 200) return;
              _this.resetForm(); // 添加这行
              _this.$alert("信息创建成功");
              _this.$emit("onClose");
            });
          }
          _this.$emit("onClose");
        } else {
          console.log("错误");
        }
      });
    },

    //产品详情
    getInfo(id) {
      let _this = this;
      let par = {
        id: id,
      };
      getParamsInfo(par).then((res) => {
        if (!res) return;
        if (res.status != 200) return;
        _this.dataForm = res.data;
        if (_this.dataForm.value_type == 2 && _this.dataForm.value_item) {
          _this.dataForm.value_item = _this.dataForm.value_item.split(',');
        }
      });
    },

    onChangeStatus(e) {
      this.dataForm.status = e;
    },
    //修改分类信息
    onChangeCategory(e) {
      let _this = this;
      _this.dataForm.categoryId = e;
    },
  },
};
</script>

<style lang="scss">
@import "./dataInfo.scss";
.custom-select-dropdown {
  display: none; /* Initially hide the dropdown */
}
</style>
