<template>
  <sd-form ref="form" :init-values="fields">
    <template v-slot="{ model }">
      <table class="sd-form-table">
        <tr v-for="field in fields" v-show="!field.sdHidden" :key="field.name">
          <sd-form-item-td
            :name="field.name"
            :label="field.dataType === 'collection' ? null : undefined"
            :colspan="field.dataType === 'collection' ? 2 : 1"
            @change="(value) => valueChange(value, field.name)"
          >
            <!-- 目标表单 -->
            <sd-list-picker
              v-if="field.name === 'associateForm$Src'"
              v-model="model[field.name]"
              single
              :load-list-data="loadOnlineFormListPickerData"
              @change="(value) => valueChange(value, 'associateForm')"
            />
            <!-- 关联条件 -->
            <sd-associate-conditions
              v-if="field.name === 'associateConditions'"
              v-model="dataSource.associateConditions"
              :dest-form-id="dataSource.associateForm"
              :src-form-id="SdEventsManage.formId"
              :disabled-types="['attachment', 'OpinionView']"
              multiple
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 字段赋值 -->
            <sd-fields-map-form
              v-if="field.name === 'fieldsMap'"
              slot="input-form"
              slot-scope="scope"
              v-bind="scope"
              :dest-form-id="dataSource.associateForm"
              :src-form-id="SdEventsManage.formId"
              :load-formula-fields="loadFormulaFields"
              :get-configured-fields="getConfiguredFields"
              :constants="constants"
            />
            <!-- 子表：字段显示 -->
            <template v-if="field.name === 'fieldsMap'" v-slot:input-destColumn$Src="scope">
              <sd-value-display v-bind="scope" type="destColumn" />
            </template>
            <template v-if="field.name === 'fieldsMap'" v-slot:input-value="scope">
              <sd-value-display v-bind="scope" />
            </template>
            <template v-slot:input-validateRepeat="scope">
              <sd-value-display v-bind="scope" type="repeat" />
            </template>
            <template v-slot:input-mode="scope">
              <sd-value-display v-bind="scope" type="mode" />
            </template>
          </sd-form-item-td>
        </tr>
      </table>
    </template>
  </sd-form>
</template>

<script>
import ApplicationService from '@/application-manage/application-service'
import sdFieldsMapForm from './child-table/sd-fields-map-form.vue'
import sdValueDisplay from './child-table/sd-value-display.vue'
import components from './_import-components/sd-create-update-import'

export const metaInfo = {
  name: '新建或更新',
  order: 300,
  // 标签：对事件处理器进行描述
  tags: ['create'],
}

export default {
  name: 'SdCreateUpdate',
  components: {
    ...components,
    sdFieldsMapForm,
    sdValueDisplay,
  },
  data() {
    return {
      fields: [
        {
          name: 'associateForm',
          caption: '目标表单(id)',
          dataType: 'string',
          sdHidden: true,
          attr: {},
        },
        {
          name: 'associateForm$Src',
          caption: '目标表单',
          dataType: 'string',
          required: true,
          attr: {},
        },
        {
          name: 'associateConditions',
          caption: '关联条件',
          dataType: 'string',
          required: true,
          attr: {},
        },
        {
          name: 'fieldsMap',
          caption: '字段赋值',
          dataType: 'collection',
          attr: {
            dync: [
              {
                name: 'destColumn',
                caption: '表单字段(id)',
                dataType: 'string',
                sdHidden: true,
                attr: {},
              },
              {
                name: 'destColumn$Src',
                caption: '表单字段',
                dataType: 'string',
                required: true,
                attr: {},
              },
              {
                name: 'opType',
                caption: '赋值方式',
                dataType: 'selectlist',
                attr: {
                  defaultValue: 'direct',
                  selectListItem: [
                    { label: '赋表单值', value: 'direct' },
                    { label: '手动输入', value: 'manual' },
                    { label: '公式', value: 'formula' },
                  ],
                },
              },
              {
                name: 'value',
                caption: '值',
                dataType: 'string',
                attr: {
                  displayExpr: '#bean.opType != "direct"',
                },
              },
              {
                name: 'srcColumn',
                caption: '目标表单(字段)',
                dataType: 'string',
                sdHidden: true,
                attr: {
                  displayExpr: '#bean.opType == "direct"',
                },
              },
              {
                name: 'formulaFD',
                caption: '公式',
                dataType: 'string',
                sdHidden: true,
                attr: {},
              },
              {
                name: 'mode',
                caption: '数据变更模式',
                dataType: 'string',
                attr: {
                  defaultValue: 'update',
                  selectListItem: [
                    { label: '变更', value: 'update' },
                    { label: '新增', value: 'insert' },
                  ],
                },
              },
              {
                name: 'validateRepeat',
                caption: '去除重复',
                dataType: 'selectlist',
                attr: {
                  defaultValue: '0',
                  displayExpr: '#bean.mode == "insert"',
                  selectListItem: [
                    { label: '是', value: '1' },
                    { label: '否', value: '0' },
                  ],
                },
              },
            ],
          },
        },
      ],
      formulaFieldsMap: [],
      constants: [],
    }
  },
  created() {
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      this.fields.forEach((f) => {
        const value = f.name === 'fieldsMap' ? this.dataSource.methodItems : this.dataSource[f.name]
        f.value = value && typeof value === 'object' ? JSON.stringify(value) : value
      })
      this.updateConstants(this.dataSource.associateForm)
    } else {
      // 新建时，赋默认值，表单类型：无流程表单
      this.$set(this.dataSource, 'formType', '0')
    }
  },
  methods: {
    validate() {
      return this.$refs.form.validateFields()
    },
    getConfiguredFields() {
      return this.$refs.form.getFieldValue('fieldsMap')?.map((v) => v.destColumn) || []
    },
    loadFormulaFields() {
      const formId = this.SdEventsManage.formId
      if (!this.formulaFieldsMap[formId]) {
        return ApplicationService.getFormulaFields(formId).then((fields) => {
          this.formulaFieldsMap[formId] = fields
          return fields
        })
      }
      return Promise.resolve(this.formulaFieldsMap[formId])
    },
    loadOnlineFormListPickerData() {
      return ApplicationService.getOnlFormListData(this.SdEventsManage.appId, 0)
    },
    valueChange(value, field) {
      if (field === 'associateForm') {
        const vid = value[0]?.id
        this.$refs.form.setFieldValue(field, vid)
        this.dataSource[field] = vid
        this.dataSource[field + '$Src'] = value
        this.updateConstants(vid)
      } else if (field === 'fieldsMap') {
        this.dataSource.methodItems = value
      } else if (field === 'associateConditions') {
        const v = value?.filter((c) => c.destColumn?.[0] && c.srcColumn?.[0])
        this.$refs.form.setFieldValue(field, v?.length > 0 ? v : undefined)
      } else {
        this.dataSource[field] = value
      }
    },
    updateConstants(formId) {
      ApplicationService.getFormConstants(formId).then((consts) => {
        this.constants = consts
      })
    },
  },
}
</script>

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