<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    :title="modalTitle"
    :canFullscreen="true"
    :maxHeight="600"
    width="50%"
    :showOkBtn="false"
    cancelText="关闭"
    @cancel="handleCancel"
  >
    <Card :bordered="false" class="form-modal-card">
      <!-- 加载状态 -->
      <div v-show="loading" class="loading-container">
        <div class="loading-content">
          <a-spin size="large" tip="表单加载中..." />
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-show="hasError" class="error-container">
        <a-result
          status="error"
          :title="errorTitle"
          :sub-title="errorMessage"
        >
          <template #extra>
            <a-button type="primary" @click="retryLoad">重新加载</a-button>
          </template>
        </a-result>
      </div>

      <!-- 内容区域 -->
      <div  class="form-content-container">
        <!-- 外部表单（iframe类型） -->
        <div v-show="formType == 2">
          <!-- <div class="iframe-header">
            <a-alert
              type="info"
              show-icon
              message="外部表单"
              description="此表单通过外部链接加载，请确保网络连接正常"
              class="iframe-alert"
            />
          </div> -->
          <div class="iframe-container">
            <iframe
              v-if="formUrl"
              :src="formUrl"
              class="responsive-iframe"
              :title="'表单-' + formTitle"
              frameborder="0"
              @load="handleIframeLoad"
              @error="handleIframeError"
            ></iframe>
          </div>
        </div>

        <div v-show="formType == 1" class="inner-form-wrapper">
          <div class="form-body">
            <FlowInnerForm ref="refInnerForm"/>
          </div>
        </div>
       
        <div v-show="formType == 0 || !formType" class="unsupported-container">
          <a-result
            status="warning"
            title="暂不支持的表单类型"
            sub-title="当前表单类型配置有误或暂不支持"
          >
            <template #extra>
              <a-space>
                <a-button type="primary" @click="closeModal">关闭</a-button>
                <a-button @click="handleReport">报告问题</a-button>
              </a-space>
            </template>
          </a-result>
        </div>
      </div>
    </Card>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, onUnmounted, nextTick, watch } from 'vue';
import { Card, message } from 'ant-design-vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import FlowInnerForm from './FlowInnerForm.vue';
import { findFlowFormVal} from "/@/components/Process/api/todo"

// 状态定义
const loading = ref(false);
const submitLoading = ref(false);
const hasError = ref(false);
const errorTitle = ref('');
const errorMessage = ref('');
const showInnerForm = ref(false); // 控制内部表单显示

// 表单相关
const formType = ref<number>(0);
const formUrl = ref<string>('');
const formTitle = ref<string>('节点表单');
const formContent = ref<string>('');
const refInnerForm = ref<InstanceType<typeof FlowInnerForm> | null>(null);

// 计算属性
const modalTitle = computed(() => {
  return formTitle.value || '节点表单';
});

// 监听 formType 变化
watch(() => formType.value, (newVal) => {
  if (newVal == 1) {
    // 当表单类型变为内部表单时，显示组件
    showInnerForm.value = true;
    // 等待组件渲染完成后再初始化数据
    nextTick(() => {
      //if (refInnerForm.value && formContent.value) {
        initializeInnerForm();
      //}
    });
  } else {
    // 其他表单类型时隐藏
    showInnerForm.value = false;
  }
});

// 初始化内部表单数据
const initializeInnerForm = async () => {
  
  if (!refInnerForm.value) {
    console.warn('Inner form ref is not available');
    return;
  }
  
  try {
    
    await refInnerForm.value.iniData(formContent.value);
    console.log('Inner form initialized successfully');
  } catch (error) {
    console.error('Failed to initialize inner form:', error);
    handleError('表单初始化失败', error);
  }
};

// 表单准备就绪的回调
const handleFormReady = () => {
  console.log('Inner form component is ready');
  // 如果已经有数据，可以在这里初始化
  if (formContent.value && refInnerForm.value) {
    initializeInnerForm();
  }
};

// 模态框注册
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  try {
    resetState();
    loading.value = true;
    // 重置内部表单显示状态
    showInnerForm.value = false;

    const taskId = data.data.taskId
    
    // 设置表单属性
    formType.value = data.data?.formTp || 0;
    formUrl.value = data.data?.formUrl || '';
    formTitle.value = data.data?.formTitle || '节点表单';
    formContent.value = data.data?.formContent || '';
    
    console.log('Modal data received:', {
      formType: formType.value,
      formTitle: formTitle.value,
      hasContent: !!formContent.value
    });
    
    // 根据表单类型处理
    if (formType.value == 1) {
      showInnerForm.value = true;
      await nextTick();
      if (refInnerForm.value) {
        await initializeInnerForm();
        await setNodeVals(taskId)
      } 
    } else if (formType.value == 2) {
      // if (!formUrl.value || !isValidUrl(formUrl.value)) {
      //   throw new Error('表单链接无效');
      // }
    }
    
    // 设置模态框属性
    setModalProps({
      title: modalTitle.value,
      confirmLoading: false,
    });
    loading.value = false;
  } catch (error) {
    handleError('表单加载失败', error);
  }
});

// 方法定义
const isValidUrl = (url: string): boolean => {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
};

const resetState = () => {
  loading.value = false;
  submitLoading.value = false;
  hasError.value = false;
  errorTitle.value = '';
  errorMessage.value = '';
  // 不重置 showInnerForm，由 watch 控制
};

const handleError = (title: string, error: any) => {
  console.error('表单错误:', error);
  loading.value = false;
  hasError.value = true;
  errorTitle.value = title;
  errorMessage.value = error.message || '未知错误，请检查配置或联系管理员';
  message.error(title);
};

const retryLoad = () => {
  resetState();
  window.location.reload();
};

const handleIframeLoad = () => {
  console.log('iframe加载完成');
  loading.value = false;
};

const handleIframeError = () => {
  handleError('外部表单加载失败', new Error('无法加载外部表单，请检查链接或网络连接'));
};


const handleCancel = () => {
  closeModal();
};

const handleReport = () => {
  message.info('问题报告功能开发中...');
};

const setNodeVals = async (taskId)=> {
  if(taskId) {
    await findFlowFormVal({taskId: taskId }).then((resValues) => {
      nextTick(() => {
        if(refInnerForm.value) {
          refInnerForm.value.setFormData(resValues)
        }
      })
    })
  }
}


onUnmounted(() => {
  formUrl.value = '';
  formContent.value = '';
  refInnerForm.value = null;
});
</script>

<style lang="scss" scoped>
.form-modal-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  :deep(.ant-card-body) {
    flex: 1;
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}

.loading-container,
.error-container,
.unsupported-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 500px;
}

.loading-content {
  text-align: center;
  
  :deep(.ant-spin-text) {
    margin-top: 12px;
    font-size: 14px;
    color: #1890ff;
  }
}

.form-content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.iframe-wrapper,
.inner-form-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.iframe-header {
  padding: 16px 24px 0;
  
  .iframe-alert {
    border-radius: 6px;
    
    :deep(.ant-alert-message) {
      font-weight: 500;
    }
  }
}

.iframe-container {
  flex: 1;
  padding: 16px 24px 24px;
  height: calc(100vh - 50px);
  min-height: 400px;
  .responsive-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }
}

.inner-form-wrapper {
  .form-header {
    padding: 20px 24px 0;
    
    .form-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #1f2d3d;
    }
    
    :deep(.ant-divider) {
      margin: 16px 0;
    }
  }
  
  .form-body {
    flex: 1;
    padding: 0 24px 24px;
    overflow-y: auto;
    min-height: 400px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .form-modal-card {
    :deep(.ant-card-body) {
      padding: 0;
    }
  }
  
  .iframe-container {
    height: calc(100vh - 220px);
    padding: 12px;
  }
  
  .inner-form-wrapper {
    .form-header,
    .form-body {
      padding-left: 16px;
      padding-right: 16px;
    }
  }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 滚动条美化
.form-body::-webkit-scrollbar {
  width: 6px;
}

.form-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>