<script setup lang="ts" name="AddValue">
import { onMounted, reactive, ref, toRefs, watch, computed } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";

import { add } from "@/api/ruleConfig/dictionary";

const props = defineProps<{
  itemData: boolean;
  type: string;
  classDict: any;
}>();

const emit = defineEmits(["cancel", "confirm"]);

const data = reactive({
  form: <any>{
    id: null,
    name: "",
    parentid: "",
    parentvalue: "",
    typecode: "",
    typename: "",
    value: "",
  },
  rules: {
    value: [
      {
        required: true,
        message: "请输入值",
        trigger: ["blur"],
      },
    ],
  },
});

const { form, rules } = toRefs(data);
const formRef = ref<FormInstance>();
const classDictList = computed(() => props.classDict);

// 重置
const reset = () => {
  form.value = {
    id: null,
    name: "",
    parentid: "",
    parentvalue: "",
    typecode: "",
    typename: "",
    value: "",
  };
};

// 取消
const cancel = () => {
  emit("cancel");
};

const confirm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      addFunc();
    } else {
    }
  });
};

// 添加数据域
const addFunc = () => {
  add({ dictionary: form.value }).then((res) => {
    const { flag } = res;
    if (flag) {
      ElMessage.success(props.type === "add" ? "新增成功" : "修改成功");
      emit("confirm");
      reset();
    }
  });
};

watch(
  () => props.itemData,
  (newVal) => {
    if (props.itemData) {
      const data = JSON.parse(JSON.stringify(props.itemData));
      form.value = { ...form.value, ...data };
    }
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="70px">
      <el-form-item label="字典分类">
        <el-select v-model="form.typecode" placeholder="请选择字典分类">
          <el-option v-for="item in classDictList" :key="item.value" :label="item.text" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="值" prop="value" required>
        <el-input v-model="form.value" placeholder="请输入值"></el-input>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="父值">
        <el-input v-model="form.parentvalue" placeholder="请输入父值"></el-input>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button type="info" style="width: 150px;" @click="cancel">取消</el-button>
      <el-button type="primary" style="width: 150px;" @click="confirm">确认</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
:deep(.el-form-item__error) {
  left: auto;
  right: 30px;
  top: 24%;
}
</style>