import { router } from '@/common/router-ready'
import flowService from '@/webflow/flow-service'

export default function({ button, eventScript, context }) {
  return new Promise((resolve) => {
    // 流程表单新建
    if (eventScript.formType === '1') {
      // 模块表单id
      const appModuleId = eventScript.appModuleId
      // 业务类型
      const businessTypeId = eventScript.businessTypeId?.[0]?.id
      // 新窗口打开
      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
              }
            }
            break
          // 手动赋值
          case 'manual':
            defaultValues[fieldName] = item.value
            break
          default:
            break
        }
      })
      // 有业务类型id，直接以新建对应的业务表单
      if (businessTypeId) {
        flowService.startProcessByBusinessTypeId(businessTypeId, defaultValues, {
          newWindow: isNewWindow,
        })
      } else {
        // 没有选择业务类型，根据表单新建（弹出选择业务类型）
        const oRoute = router.resolve({
          path: '/sd-flow-guide',
          query: { moduleId: appModuleId, ...defaultValues },
        })
        if (isNewWindow) {
          window.open(oRoute.href, '_blank')
        } else {
          router.push(oRoute.route.fullPath)
        }
      }
      resolve()
    }
  })
}
