<template>
  <el-form v-if="form" :model="form" ref="formRef" label-width="80px" :rules="formRules">
    <el-form-item label="流程代码" prop="code">
      <el-input v-model="form.code" :readonly="props.mode !== 'create'" />
    </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="是否分支">
      <el-switch v-model="form.branch" :disabled="props.mode === 'show'" />
    </el-form-item>
    <el-form-item label="过期天数">
      <el-input v-model.number="form.expireDays" :readonly="props.mode === 'show'" />
    </el-form-item>
    <el-form-item label="流程描述">
      <el-input type="textarea" :rows="3" v-model="form.description" :readonly="props.mode === 'show'" />
    </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, ProcessDescriptor } from '@cacp/ui'

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

const formRules: FormRules = {
  code: [
    {
      required: true,
      message: '编码必填'
    }
  ],
  name: [
    {
      required: true,
      message: '名称必填'
    }
  ]
}
const formRef = ref<FormInstance>()
const form = ref<ProcessDescriptor>()

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

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