<template>
  <el-form v-if="form" :model="form" ref="formRef" label-width="80px" :rules="formRules">
    <el-form-item label="连线代码">
      <el-input v-model="form.code" readonly />
    </el-form-item>
    <el-form-item label="连线名称" prop="name">
      <el-input v-model="form.name" :readonly="props.mode === 'show'" />
    </el-form-item>
    <el-form-item label="连线类型" prop="type">
      <el-select v-model="form.type" :disabled="props.mode === 'show'">
        <el-option label="普通" value="NORMAL" />
        <el-option label="条件" value="CONDITION" />
      </el-select>
    </el-form-item>
    <el-form-item label="条件脚本" v-if="form.type === 'CONDITION'" prop="condition">
      <el-input type="textarea" :rows="3" v-model="form.condition" :readonly="props.mode === 'show'" />
      <div>变量类似{#var}写法，结果为boolean类型，例如判断天数=10的写法是{#days} == 10，人名是张三的写法是'{#personName}' == '张三'</div>
    </el-form-item>
    <el-form-item>
      <el-button type="warning" @click="onSave">
        <template #icon>
          <el-icon><Download /></el-icon>
        </template>
        保存
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import type { OperMode, FlowDescriptor } from '@cacp/ui'

const props = defineProps<{
  mode: OperMode
  info?: FlowDescriptor
}>()
const emits = defineEmits<{
  (e: 'on-save', flow: FlowDescriptor): void
}>()

const formRules: FormRules = {
  type: [
    { required: true, message: '类型必填' }
  ],
  condition: [
    {
      validator: (rule, value, callback) => {
        if (form.value.type === 'CONDITION' && !value) {
          return callback('条件脚本必填')
        }

        return callback()
      }
    }
  ]
}

const formRef = ref<FormInstance>()
const form = ref<FlowDescriptor>()

watchEffect(() => {
  form.value = cloneDeep(props.info)
})

function onSave() {
  formRef.value!.validate((valid) => {
    if (valid) {
      emits('on-save', form.value)
    }
  })
}
</script>
