<script setup lang="ts" name="Form">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { Switch } from "view-ui-plus";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import ExpressionEditor from "@/components/EditPop/ExpressionEditor.vue";
import { save } from "@/api/ruleConfig/algorithm";

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

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

const data = reactive({
  form: <any>{
    dataarea_id: "",
    defaluttype: "0",
    expression: "",
    id: "",
    rulename: "",
    rulesource: "",
  },
  rules: {
    expression: [
      {
        required: true,
        message: "请输入表达式",
        trigger: ["blur"],
      },
    ],
  },
});

const { form, rules } = toRefs(data);

const editorShow = ref(false);
const readOnly = ref(true);
const editor = ref({
  rulename: "",
  expression: "",
});
const rulenameList = ref([]);
const formRef = ref<FormInstance>();

// 重置
const reset = () => {
  form.value = {
    dataarea_id: "",
    defaluttype: "0",
    enc_name: "",
    encryption_id: "",
    secretkey_id: "",
  };
};

// 打开编辑器
const openEditor = () => {
  editorShow.value = true;
  editor.value = {
    rulename: form.value.rulename,
    expression: form.value.expression,
  };
};

// 取消
const cancel = () => {
  if (props.type === "edit") {
    readOnly.value = true;
    const data = JSON.parse(JSON.stringify(props.itemData));
    form.value = { ...form.value, ...data };
  } else if (props.type === "add") {
    emit("cancel");
  }
};

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

const saveFunc = () => {
  if (props.type === "edit") {
    form.value = { ...form.value, ...{ id: form.value.id } };
  }
  save(form.value).then((res) => {
    const { flag } = res;
    if (flag) {
      ElMessage.success(
        props.type === "add" || !form.value.id ? "新增成功" : "修改成功"
      );
      if (props.type === "edit") {
        readOnly.value = true;
      } else if (props.type === "add") {
        reset();
      }
      emit("confirm", props.type);
    }
  });
};

// 算法名称验证
const validateRulename = (rule, value, callback) => {
  const state = rulenameList.value.includes(value);
  if (state) {
    callback(new Error("算法名称已存在"));
  } else {
    callback();
  }
};

// 编辑器确认
const formConfirm = (val) => {
  editorShow.value = false;
  form.value.expression = val;
};

watch(
  () => props.type,
  (newVal) => {
    readOnly.value = props.type === "edit" ? true : false;
  },
  { deep: true, immediate: true }
);

watch(
  () => props.itemData,
  (newVal) => {
    if (props.type === "add") {
      reset();
    }
    if (props.itemData) {
      const data = JSON.parse(JSON.stringify(props.itemData));
      form.value = { ...form.value, ...data };
      if (props.type === "edit") {
        rulenameList.value = rulenameList.value.filter(
          (item) => item !== data.rulename
        );
      }
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => props.nameList,
  (newVal) => {
    rulenameList.value = props.nameList;
    const data = JSON.parse(JSON.stringify(props.itemData));
    if (props.type === "edit" && data) {
      rulenameList.value = rulenameList.value.filter(
        (item) => item !== data.rulename
      );
    }
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" :disabled="readOnly">
      <div class="formBox">
        <el-form-item label="算法名称" prop="rulename" required
          :rules="[{ required: true, message: '请输入算法名称', trigger:'blur' },{ required: true, validator: validateRulename, trigger:'blur' }]">
          <el-input v-model="form.rulename"></el-input>
        </el-form-item>
        <el-form-item label="表达式" prop="expression" required>
          <el-input v-model="form.expression"></el-input>
          <el-button class="openEditor" type="text" @click="openEditor" v-if="!readOnly">打开编辑器</el-button>
        </el-form-item>
        <el-form-item label="默认规则">
          <div class="is-disabled" v-if="readOnly" style="width: 100%;height: 100%;">
            <div class="el-input__wrapper" style="height: 100%;">{{ form.defaluttype === '1' ? '是':'否' }}</div>
          </div>
          <el-radio-group v-model="form.defaluttype" v-if="!readOnly" style="margin-left: 10px;">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <div class="btn">
      <el-button type="primary" style="width: 80px;" @click="readOnly = false" v-if="readOnly">编辑</el-button>
      <el-button type="primary" style="width: 80px;" @click="confirm" v-if="!readOnly">确认</el-button>
      <el-button style="width: 80px;" @click="cancel" v-if="!readOnly">取消</el-button>
    </div>

    <ExpressionEditor v-model="editorShow" :editor="editor" @cancel=" editorShow = false" @confirm="formConfirm" />
  </div>
</template>

<style lang="scss" scoped>
.openEditor {
  position: absolute;
  bottom: 0;
  top: 0;
  right: 10px;
  margin: auto;
  text-decoration: underline;
}
.btn {
  padding: 40px 20px 20px 20px;
  display: flex;
  justify-content: center;
}
:deep(.el-input__inner) {
  height: 34px;
}
</style>