import axios from '@/common/services/axios-instance'
import asyncComponent from '@/common/services/async-component'
const formMap = {}

const formByDesigner = asyncComponent(
  // 设计器画的form
  () =>
    import(
      /* webpackChunkName: "src-form-designer-form" */ '@/form-designer/sd-form-by-designer.vue'
    )
)

class FormService {
  getData(data) {
    const { pageId, id, extParams } = data
    return axios({
      url: 'api/framework/v1/page/wp/' + pageId,
      method: 'post',
      // 新建时，传extParams，用于设置默认值
      data: { id, extParams: !id ? extParams : undefined },
    }).then((res) => res.data)
  }

  addForm(pageId, component) {
    formMap[pageId] = component
  }

  getWebForm(formData) {
    if (!formMap[formData.pageFormData.pageId]) {
      // 设计器画的form
      if (formData.pageFormData.attrFD) {
        return formByDesigner
      }
      formMap[formData.pageFormData.pageId] = asyncComponent(
        // 默认form
        () =>
          import(
            /* webpackChunkName: "src-webform-common-form" */ '@/webform/sd-common-subform.vue'
          )
      )
    }
    return formMap[formData.pageFormData.pageId]
  }

  hasWebForm(pageId) {
    // Builder画的表单 或 代码开发的表单注册了form
    return pageId.startsWith('onl:') || !!formMap[pageId]
  }

  save(data) {
    return axios({
      url: 'api/framework/v1/page/handleData',
      method: 'post',
      data,
    })
  }

  // 获取修改记录
  getOperationLog(params) {
    return axios({
      url: `api/framework/v1/operation-log/log-list/${params.beanId}`,
      data: {
        expressions: [],
        startPosition: 0,
        maxResults: -1,
        orderBy: 'createdTime desc',
        formId: params.formId,
      },
      method: 'post',
    }).then((res) => res?.data?.data)
  }
}

export default new FormService()
