<template>
  <!-- 无流程表单 -->
  <sd-detail-modal
    ref="detail"
    :record-id="recordId"
    :page-id="pageId"
    :ext-params="extParams"
    @saved="saved"
  >
    <template v-slot="{ formData }">
      <sd-form-by-builder :form-data="formData.pageFormData" />
    </template>
  </sd-detail-modal>
</template>

<script>
import qs from 'qs'
import flowService from '@/webflow/flow-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/sd-create-handler-import'

export default {
  name: 'SdCreateHandler',
  components,
  data() {
    return {
      recordId: undefined,
      pageId: '',
      dataList: undefined,
      extParams: undefined,
    }
  },
  methods: {
    run({ button, eventScript, context }) {
      return new Promise((resolve) => {
        // 新窗口打开
        const isNewWindow = eventScript.newWindow === '1'
        // 获取设置的默认值
        const defaultValues = {}
        const { fieldInfos } = context
        eventScript.defaultValues?.forEach((item) => {
          const fieldName = JSON.parse(item.destColumn || '[]')[0]?.id
          switch (item.opType) {
            // 赋表单值
            case 'direct':
              {
                const srcFieldName = JSON.parse(item.srcColumn || '[]')[0]?.id
                if (srcFieldName) {
                  defaultValues[fieldName] =
                    fieldInfos.find((f) => f.name === srcFieldName)?.value ?? undefined
                }
              }
              break
            // 手动赋值
            case 'manual':
              defaultValues[fieldName] = item.value
              break
            default:
              break
          }
        })
        this.dataList = context.dataList
        // 流程表单新建
        if (eventScript.formType === '1') {
          // 模块表单id
          const appModuleId = eventScript.appModuleId
          // 业务类型
          const businessTypeId = eventScript.businessTypeId?.[0]?.id
          // 有业务类型id，直接以新建对应的业务表单
          if (businessTypeId) {
            flowService
              .startProcessByBusinessTypeId(businessTypeId, defaultValues, {
                newWindow: isNewWindow,
              })
              .then((flag) => {
                if (flag) {
                  this.dataList?.refresh?.()
                }
              })
          } else {
            // 没有选择业务类型，根据表单新建（弹出选择业务类型）
            const url = this.$router.resolve({
              path: '/sd-flow-guide',
              query: { moduleId: appModuleId, ...defaultValues },
            }).route.fullPath
            if (isNewWindow) {
              crossWindowWatcher.waitForChanged(url).then((flag) => {
                if (flag) {
                  this.dataList?.refresh?.()
                }
              })
            } else {
              this.$router.push(url)
            }
          }
        } else {
          // 无流程表单
          this.pageId = 'onl:' + eventScript.targetForm[0].id
          if (isNewWindow) {
            crossWindowWatcher.subscribeChange({
              url:
                '/sd-webform?' +
                qs.stringify({
                  id: this.recordId,
                  pageId: this.pageId,
                  extParams: JSON.stringify(defaultValues),
                }),
              callback: (data) => {
                this.dataList?.refresh?.()
              },
            })
          } else {
            this.extParams = defaultValues
            this.$refs.detail.show()
          }
        }
        resolve()
      })
    },
    saved() {
      this.dataList?.refresh?.()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
