<template>
  <div class='default-main'>
    <content-wrap>
      <!-- 表单设计器 -->
      <FcDesigner ref='designer' height='780px'>
        <template #handle>
          <el-button round size='small' type='primary' @click='handleSave' class='ml10' :icon='Plus'>保存
          </el-button>
          <el-button round size='small' @click='go(-1)' class='ml10' :icon='Back'>取消
          </el-button>
        </template>
      </FcDesigner>
    </content-wrap>

    <!-- 表单保存的弹窗 -->
    <el-dialog v-model='dialogVisible' title='保存表单' class='cn-operate-dialog' width="40%">
      <el-scrollbar>
        <el-form ref='formRef' :model='formData' :rules='formRules' label-width='80px'>
          <el-form-item label='表单名' prop='name'>
            <el-input v-model='formData.name' placeholder='请输入表单名' />
          </el-form-item>
          <el-form-item label='状态' prop='status'>
            <el-radio-group v-model='formData.status'>
              <el-radio
                  v-for='dict in options'
                  :key='dict.value'
                  :label='dict.value'
              >
                {{ dict.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label='备注' prop='remark'>
            <el-input v-model='formData.remark' placeholder='请输入备注' type='textarea' />
          </el-form-item>
          <el-form-item label="排序">
                    <el-input-number style="width: 100%" v-model="formData.sort" :min="0" placeholder="请输入排序" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
                <span class='dialog-footer'>
                    <el-button :disabled='formLoading' type='primary' @click='submitForm'>确 定</el-button>
                    <el-button @click='dialogVisible = false'>取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang='ts' setup>
import { onMounted, ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import FcDesigner from '@form-create/designer'
import { encodeConf, encodeFields, setConfAndFields } from '@/utils/formCreate'
import { useNavTabs } from '@/stores/navTabs'
import { useFormCreateDesigner } from '@/components/FormCreate'
import { Plus, Back } from '@element-plus/icons-vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'

const options = ref([
  {
    value: 1,
    name: '开启'
  },
  {
    value: 0,
    name: '关闭'
  }
])

defineOptions({ name: 'BpmFormEditor' })

import { ElMessage } from 'element-plus'
import { addForm, getById, updateForm } from '@/api/bpm-boot/form'

const { push, currentRoute, go } = useRouter() // 路由
const { query } = useRoute() // 路由信息
const navTabs = useNavTabs()

const designer = ref() // 表单设计器
useFormCreateDesigner(designer) // 表单设计器增强
const dialogVisible = ref(false) // 弹窗是否展示
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const formData = ref({
  name: '',
  status: 1,
  remark: '',
  sort:100,
})
const formRules = reactive({
  name: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 处理保存按钮 */
const handleSave = () => {
  dialogVisible.value = true
}

type FormVO = {
  id: number
  name: string
  conf: string
  fields: string[]
  status: number
  remark: string
  createTime: string
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as FormVO
    data.conf = encodeConf(designer) // 表单配置
    data.fields = encodeFields(designer) // 表单字段
    if (!data.id) {
      await addForm(data)
      ElMessage.success('保存成功')
    } else {
      await updateForm(data)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    close()
  } finally {
    formLoading.value = false
  }
}
/** 关闭按钮 */
const close = () => {
    navTabs.closeTab(unref(currentRoute))
    go(-1)
}

/** 初始化 **/
onMounted(async () => {
  // 场景一：新增表单
  const id = query.id as unknown as string
  if (!id) {
    return
  }
  // 场景二：修改表单
  await getById(id).then(res => {
    formData.value = res.data
    setConfAndFields(designer, res.data.conf, res.data.fields)
  })

})
</script>
