<template>
  <sd-form ref="form" :init-values="fields">
    <template v-slot="{ model }">
      <table class="sd-form-table">
        <tr v-for="field in fields" :key="field.name">
          <sd-form-item-td :name="field.name">
            <!-- 目标表单 -->
            <sd-list-picker
              v-if="field.name === 'targetForm'"
              v-model="model[field.name]"
              single
              :load-list-data="loadOnlineFormListPickerData"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 关联条件 -->
            <sd-associate-conditions
              v-if="field.name === 'associateConditions'"
              v-model="dataSource.associateConditions"
              :dest-form-id="dataSource.targetForm?.[0]?.id"
              :src-form-id="SdEventsManage.formId"
              dest-column="targetField"
              src-column="curField"
              @change="(value) => valueChange(value, field.name)"
            />
          </sd-form-item-td>
        </tr>
      </table>
    </template>
  </sd-form>
</template>

<script>
import ApplicationService from '@/application-manage/application-service'
import components from './_import-components/sd-open-doc-import'

export const metaInfo = {
  name: '打开文件',
  order: 200,
}

export default {
  name: 'SdOpenDoc',
  components,
  data() {
    return {
      fields: [
        {
          name: 'targetForm',
          caption: '目标表单',
          dataType: 'string',
          required: true,
        },
        {
          name: 'associateConditions',
          caption: '关联条件',
          dataType: 'string',
          required: true,
        },
      ],
    }
  },
  created() {
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      this.fields.forEach((f) => {
        const value = this.dataSource[f.name]
        if (value && typeof value === 'object') {
          f.value = JSON.stringify(value)
        } else {
          f.value = value
        }
      })
    }
  },
  methods: {
    validate() {
      return this.$refs.form.validateFields()
    },
    loadOnlineFormListPickerData() {
      return ApplicationService.getOnlFormListData(this.SdEventsManage.appId)
    },
    valueChange(value, field) {
      if (field === 'targetForm') {
        this.$set(this.dataSource, field, value)
        this.dataSource.formType = value[0].formType
      } else if (field === 'associateConditions') {
        const v = value?.filter((c) => c.targetField?.[0] && c.curField?.[0])
        this.$refs.form.setFieldValue('associateConditions', v?.length > 0 ? v : undefined)
      }
    },
  },
}
</script>

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