import { message } from '@/common/one-ui'
import FlowService from '@/webflow/flow-service'

import { sdLocalStorage } from '@/common/services/storage-service'
export default function({ button }) {
  // 保存操作
  const key = 'key'
  const duration = 1
  return this.checkLock().then(() => {
    return FlowService.save(this.FlowData, this.getFormData(), button.buttonId).then((_) => {
      const content = button.buttonId === 'workflow$adminFormSave' ? '数据维护成功' : '保存成功'
      // @ts-ignore
      return message.success({ content, key, duration }).then(() => {
        // 调用接口更新数据
        if (!this.FlowData.activeStepId) {
          // 未保存的起草状态
          this.$router.replace(`/sd-webflow/pages/draft/${_.activeStepInfo[0].instId}`)
        }
        sdLocalStorage.removeItem(`Lock${this.FlowData.instId}`)
        return this.updateFlow().then(() => {
          // 在这里更新下子表的值，因为保存后的子表数据会加上id，sd-form不会自动更新，所以手动更新下
          this.FlowData.processFormData.processFormPropertyValues.forEach((item) => {
            if (item.dataType === 'collection') {
              this.setFieldValue(item.name, JSON.parse(item.value) || [])
            }
          })
        })
      })
    })
  })
}
