<template>
  <div class="form-designer-container">
    <v-form-designer 
      ref="vfDesignerRef" 
      @save="saveFormJson" 
      :config="designerConfig"
      class="form-designer"
    >
    </v-form-designer>

    <a-modal
      :title="formTitle"
      :open="formOpen"
      :get-container="false"
      :mask-closable="false"
      :width="600"
      :confirm-loading="loading"
      @cancel="cancelModal"
      @ok="submitForm"
      destroy-on-close
    >
      <a-card :bordered="false" class="form-modal-card">
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 18 }"
        >
          <a-form-item label="表单名称" name="formName">
            <a-input
              v-model:value="formState.formName"
              placeholder="请输入表单名称"
              show-count 
              :maxlength="32"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea
              v-model:value="formState.remark"
              placeholder="请输入备注"
              :auto-size="{ minRows: 4, maxRows: 6 }"
              show-count 
              :maxlength="128"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </a-card>
      <template #footer>
        <a-button @click="cancelModal" :disabled="loading">取消</a-button>
        <a-button 
          type="primary" 
          @click="submitForm" 
          :loading="loading"
        >
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, type FormInstance } from 'ant-design-vue'

import VFormDesigner from '@form-create/antd-designer'

import { addForm, getForm, updateForm } from "@/components/Process/api/form"
import { StrUtil } from '@/components/Process/common/StrUtil'

// 定义类型
interface FormState {
  formId?: number | null
  formName?: string
  formContent?: string
  remark?: string
  formRules?: string
  formOptions?: string
  formTp?: number
}

interface DesignerConfig {
  generateSFCButton: boolean
  exportCodeButton: boolean
  toolbarMaxWidth: number
  toolbarMinWidth: number
  formHeader: boolean
  showSaveBtn: boolean
}

const route = useRoute()
const router = useRouter()

const vfDesignerRef = ref<any>(null)
const formRef = ref<FormInstance>()
const formOpen = ref<boolean>(false)
const formTitle = ref<string>('')
const loading = ref<boolean>(false)
const isMounted = ref<boolean>(false)

const formState = reactive<FormState>({
  formId: null,
  formTp: 1, // 内置表单
  formName: undefined,
  formContent: undefined,
  remark: undefined,
  formRules: undefined,
  formOptions: undefined,
})

const rules = reactive({
  formName: [
    { required: true, message: '表单名称不能为空', trigger: 'blur' },
    { min: 1, max: 32, message: '表单名称长度应在1-32个字符之间', trigger: 'blur' }
  ],
  remark: [
    { max: 128, message: '备注长度不能超过128个字符', trigger: 'blur' }
  ]
})

const designerConfig = reactive<DesignerConfig>({
  generateSFCButton: false,
  exportCodeButton: true,
  toolbarMaxWidth: 320,
  toolbarMinWidth: 300,
  showSaveBtn: true, 
  formHeader: true
})

// 设置空表单
const setEmptyForm = () => {
  if (vfDesignerRef.value && isMounted.value) {
    try {
      const emptyFormJson = {
        "widgetList": [],
        "formConfig": {
          "modelName": "formData",
          "refName": "vForm",
          "rulesName": "rules",
          "labelWidth": 80,
          "labelPosition": "left",
          "size": "",
          "labelAlign": "label-left-align",
          "cssCode": "",
          "customClass": "",
          "functions": "",
          "layoutType": "PC",
          "onFormCreated": "",
          "onFormMounted": "",
          "onFormDataChange": "",
          "onFormValidate": "",
          "onFormSave": ""
        }
      }
      vfDesignerRef.value.setFormJson(emptyFormJson)
      console.log('空表单设置成功')
    } catch (error) {
      console.error('设置空表单失败:', error)
      setTimeout(() => {
        if (vfDesignerRef.value?.setFormJson) {
          vfDesignerRef.value.setFormJson({
            "widgetList": [],
            "formConfig": {
              "modelName": "formData",
              "refName": "vForm",
              "rulesName": "rules",
              "labelWidth": 80,
              "labelPosition": "left",
              "size": "",
              "labelAlign": "label-left-align",
              "cssCode": "",
              "customClass": "",
              "functions": "",
              "layoutType": "PC"
            }
          })
        }
      }, 100)
    }
  }
}

// 初始化表单设计器
const initFormDesigner = async () => {
  const formId = route.query?.formId
  formTitle.value = formId ? '修改表单' : '新增表单'
  
  try {
    // 等待组件完全挂载
    await nextTick()
    
    if (StrUtil.isNotBlank(formId)) {
      // 编辑模式 - 加载现有表单
      const res = await getForm(formId)
      Object.assign(formState, res)
      
      await nextTick()
      if (vfDesignerRef.value && res.formRules && res.formOptions) {
        try {
          const formRules = typeof res.formRules === 'string' ? JSON.parse(res.formRules) : res.formRules
          const formOptions = typeof res.formOptions === 'string' ? JSON.parse(res.formOptions) : res.formOptions
          vfDesignerRef.value.setOptions(formOptions)
          vfDesignerRef.value.setRule(formRules)
          console.log('表单数据加载成功')
        } catch (parseError) {
          console.error('解析表单数据失败:', parseError)
          message.error('表单数据格式错误')
          setEmptyForm()
        }
      }
    } else {
      // 新增模式 - 设置空表单
      console.log('新增模式，设置空表单')
      setEmptyForm()
    }
  } catch (error) {
    console.error('初始化表单设计器失败:', error)
    message.error('加载表单失败')
    setEmptyForm()
  }
}

onMounted(() => {
  isMounted.value = true
  console.log('组件已挂载，开始初始化表单设计器')
  
  // 延迟初始化，确保 VFormDesigner 完全加载
  setTimeout(() => {
    initFormDesigner()
  }, 300)
})

// 保存表单JSON
const saveFormJson = async ({ rule, options }) => {
  if (vfDesignerRef.value) {
    try {
      formState.formRules = typeof rule === 'string' ? rule : JSON.stringify(rule)
      formState.formOptions = typeof options === 'string' ? options : JSON.stringify(options)
      formOpen.value = true
    } catch (error) {
      console.error('保存表单JSON失败:', error)
      message.error('保存表单配置失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    loading.value = true
    
    // 根据是否有formId决定是新增还是修改
    if (formState.formId) {
      await updateForm(formState)
      message.success('修改成功')
    } else {
      await addForm(formState)
      message.success('新增成功')
    }
    
    formOpen.value = false
    await handleSuccess()
    
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error instanceof Error) {
      message.error(error.message || '操作失败')
    }
  } finally {
    loading.value = false
  }
}

// 取消模态框
const cancelModal = () => {
  if (loading.value) return
  formOpen.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
}

// 成功处理
const handleSuccess = async () => {
  await router.push({ 
    path: '/flowable/form/index', 
    query: { t: Date.now() } 
  })
}
</script>

<style lang="scss" scoped>
.form-designer-container {
  height: 80vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
  
  .form-designer {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    
    // 修复滚动条问题的关键样式
    :deep(.main-container) {
      background: #fff;
      margin-left: 0 !important;
      display: flex;
      flex: 1;
      min-height: 0;
      height: 100%;
      overflow: hidden;
      
      // 左侧组件区域
      .left-container {
        overflow-y: auto;
        height: 100%;
        flex-shrink: 0;
        border-right: 1px solid #e8e8e8;
      }
      
      // 中间画布区域
      .center-container {
        overflow-y: auto;
        height: 100%;
        flex: 1;
        min-width: 0;
        
        .form-canvas {
          min-height: 100%;
          padding: 20px;
          background: #f5f5f5;
        }
      }
      
      // 右侧属性区域 - 修复滚动条
      .right-container {
        overflow-y: auto !important;
        height: 100% !important;
        flex-shrink: 0;
        width: 320px !important;
        border-left: 1px solid #e8e8e8;
        
        .property-panel {
          height: auto !important;
          min-height: 100% !important;
          
          // 修复属性面板内部滚动
          .property-group {
            .property-content {
              overflow: visible !important;
              max-height: none !important;
            }
          }
          
          // 修复折叠面板滚动
          .ant-collapse {
            .ant-collapse-item {
              .ant-collapse-content {
                overflow: visible !important;
                max-height: none !important;
                
                .ant-collapse-content-box {
                  overflow: visible !important;
                  max-height: none !important;
                  padding: 16px !important;
                }
              }
            }
          }
        }
      }
    }
    
    // 工具栏样式
    :deep(.toolbar-container) {
      flex-shrink: 0;
      background: #f5f5f5;
      border-bottom: 1px solid #e8e8e8;
      padding: 8px 16px;
      height: 50px;
      display: flex;
      align-items: center;
      
      .toolbar-button {
        display: flex;
        align-items: center;
        
        .ant-btn {
          margin-right: 8px;
        }
      }
    }
  }
}

// 模态框卡片样式
.form-modal-card {
  :deep(.ant-card-body) {
    padding: 16px;
  }
}

// 强制显示滚动条
:deep(::-webkit-scrollbar) {
  width: 8px !important;
  height: 8px !important;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1 !important;
  border-radius: 4px !important;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #c1c1c1 !important;
  border-radius: 4px !important;
  
  &:hover {
    background: #a8a8a8 !important;
  }
}

// 确保所有可滚动区域都有滚动条
:deep(.left-container),
:deep(.center-container),
:deep(.right-container) {
  &::-webkit-scrollbar {
    width: 8px !important;
    height: 8px !important;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1 !important;
    border-radius: 4px !important;
  }
}

@media (max-width: 1200px) {
  .form-designer-container {
    height: 90vh;
  }
}

@media (max-width: 768px) {
  .form-designer-container {
    height: 60vh;
  }
}
</style>