<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: "",
    defaulttype: "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="100px" :disabled="readOnly">
      <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 type="textarea" rows="8" v-model="form.expression"></el-input>
        <el-button class="openEditor" type="primary" @click="openEditor">打开编辑器</el-button>
      </el-form-item>
      <el-form-item label="默认规则">
        <Switch true-value="1" false-value="0" v-model="form.defaluttype" :disabled="readOnly">
          <template #open>
            <span>是</span>
          </template>
          <template #close>
            <span>否</span>
          </template>
        </Switch>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button type="primary" style="width: 150px;" @click="readOnly = false" v-if="readOnly">编辑</el-button>
      <el-button type="info" style="width: 150px;" @click="cancel" v-if="!readOnly">取消</el-button>
      <el-button type="primary" style="width: 150px;" @click="confirm" 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;
  right: 0;
}
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>