<!--
 * @Description: 添加/编辑人工标签弹出框组件
 * @Author: liusheng
 * @Date: 2024-07-08 14:30:56
-->
<template>
  <div>
    <el-form :ref="formName" :model="manualTagForm" :rules="manualTagRules" label-width="100px">
      <el-form-item label="标签名称：" prop="name">
        <el-input v-model="manualTagForm.name" style="width:175px" size="small" clearable placeholder="请输入标签名称" />
      </el-form-item>
    </el-form>
    <div style="text-align:center; margin:0">
      <el-button type="text" size="mini" @click="handleCancel">取消</el-button>
      <el-button type="primary" size="mini" @click="handleConfirm">确定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'EditManualTagForm',
  props: ['mode', 'visible', 'tagSetIndex', 'tagSet', 'tagIndex'],
  
  data() {
    return {
      formName: 'manualTagForm',

      dataTypelist: ['INT', 'DOUBLE', 'STRING'],
      manualTagForm: {},
			manualTagRules: {
				name: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { type: 'string', pattern: /^([a-zA-Z0-9]|[\u4e00-\u9fa5])+$/, message: '只能输入汉字、字母或数字', trigger: 'blur' },
					{ min: 1, max: 20, message: '最大长度不超过20个字符', trigger: 'blur' },
				],
			}
    }
  },

  methods: {
    handleConfirm() {
      this.$refs[this.formName].validate((valid) => {
        if (!valid) return false;
        this.$emit("confirm", this.tagSet, this.manualTagForm);
      });
    },
    
    handleCancel() {
      this.$emit("close", this.tagSetIndex);
    },

    handleKeyDown(event) {
      if (event.key === 'Escape') {
        this.handleCancel();
      }
    }
  },

  watch: {
    visible(newVal) {
      if (!newVal) return;
      this.$refs[this.formName].clearValidate();
      this.manualTagForm = (this.mode === 'add') ? {}
        : JSON.parse(JSON.stringify(this.tagSet.tagList[this.tagIndex]));
    }
  },

  mounted() {
    // 添加全局键盘监听事件
    window.addEventListener('keydown', this.handleKeyDown);
  },

  beforeDestroy() {
    // 移除全局键盘监听事件
    window.removeEventListener('keydown', this.handleKeyDown);
  },
}
</script>

<style scoped>
.text {
  padding: 12px 0 15px 5px;
  font-size: 15px;
}
</style>
