<script setup lang="ts" name="Form">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { Switch } from "view-ui-plus";
import ExpressionEditor from '@/components/EditPop/ExpressionEditor.vue'

const props = defineProps<{
  modelValue: boolean;
  type: string;
}>();

const emit = defineEmits(["update:modelValue", 'cancel','confirm']);

const data = reactive({
  rules: {},
});

const { rules } = toRefs(data);

const editorShow = ref(false);
const readOnly = ref(true);
const editor = ref({});

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

// 打开编辑器
const openEditor = () => {
  editorShow.value = true
  editor.value = props.modelValue
}

// 取消
const cancel = () => { 
  if (props.type === 'edit') { 
    readOnly.value = true
  }else if (props.type === 'add') { 
    emit('cancel')
  }
}

const confirm = () => {
  if (props.type === 'edit') { 
    readOnly.value = true
  }
  emit('confirm')
}

// 编辑器确认
const formConfirm = (val) => {
  editorShow.value = false
  props.modelValue.name = val
}


</script>

<template>
  <div>
    <el-form ref="formRef" :model="modelValue" label-width="100px" :disabled="readOnly">
      <el-form-item label="算法名称" required>
        <el-input v-model="modelValue.name"></el-input>
      </el-form-item>
      <el-form-item label="表达式" required>
        <el-input type="textarea" rows="8" v-model="modelValue.name"></el-input>
        <el-button class="openEditor" type="primary" @click="openEditor">打开编辑器</el-button>
      </el-form-item>
      <el-form-item label="默认规则">
        <Switch :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" :data="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>