<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')"
            />
            <!-- 创建者 -->
            <a-row v-if="field.name === 'creator'" type="flex" :gutter="[4, 0]">
              <a-col :span="9">
                <a-radio-group v-model="dataSource.creatorType" :options="creatorOptions" />
              </a-col>
              <a-col :span="15">
                <sd-field-picker
                  v-if="dataSource.creatorType === '2'"
                  v-model="dataSource.formFieldCreator"
                  :form-id="SdEventsManage.formId"
                  type="user"
                />
              </a-col>
            </a-row>
            <!-- 默认值 -->
            <template
              v-if="field.name === 'defaultValues'"
              v-slot:input-form="{ model: subModel, fields: subFields }"
            >
              <table class="sd-form-table">
                <tr>
                  <sd-form-item-td name="destColumn$Src">
                    <sd-field-picker
                      v-model="subModel.destColumn$Src"
                      :form-id="dataSource.associateForm"
                      :disabled-keys="
                        [...getSubTableFields(field.name), 'id'].filter(
                          (i) => i !== subFields.destColumn.value
                        )
                      "
                      :disabled-types="['OpinionView']"
                      :type="subModel.srcColumn?.[0]?.type"
                      @change="
                        (v) => {
                          subModel.destColumn = v?.[0]?.id
                        }
                      "
                    />
                  </sd-form-item-td>
                </tr>
                <tr>
                  <sd-form-item-td
                    name="opType"
                    @change="
                      () => {
                        subModel.value = undefined
                        subModel.srcColumn = undefined
                        subModel.formulaFD = undefined
                      }
                    "
                  />
                </tr>
                <tr>
                  <sd-form-item-td name="value">
                    <!-- 公式 -->
                    <sd-formula-compute
                      v-if="subModel.opType === 'formula'"
                      v-model="subModel.formulaFD"
                      :load-fields="loadFormulaFields"
                      :data-type="subModel.destColumn$Src?.[0]?.type || undefined"
                      :constants="constants"
                      value-string
                      @update="
                        ($event) => {
                          $set(subModel, 'value', $event)
                        }
                      "
                    />
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 赋表单值 -->
                  <sd-form-item-td name="srcColumn" label="值">
                    <sd-field-picker
                      v-model="subModel.srcColumn"
                      :form-id="SdEventsManage.formId"
                      :type="subModel.destColumn$Src?.[0]?.type"
                      :disabled-types="['OpinionView']"
                      @change="
                        (v) => {
                          subModel.value = v?.[0]?.id
                        }
                      "
                    />
                  </sd-form-item-td>
                </tr>
              </table>
            </template>
            <!-- 子表：字段显示 -->
            <template v-if="field.name === 'defaultValues'" v-slot:input-destColumn$Src="scope">
              <sd-value-display v-bind="scope" type="destColumn" />
            </template>
            <template v-if="field.name === 'defaultValues'" v-slot:input-value="scope">
              <sd-value-display v-bind="scope" />
            </template>
          </sd-form-item-td>
        </tr>
      </table>
    </template>
  </sd-form>
</template>

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

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

export default {
  name: 'SdCreate',
  components: {
    ...components,
    sdValueDisplay,
  },
  data() {
    return {
      fields: [
        {
          name: 'formType',
          caption: '表单类型',
          dataType: 'selectlist',
          sdHidden: true,
          attr: {
            selectListItem: [
              { label: '流程', value: '1' },
              { label: '无流程', value: '0' },
            ],
          },
        },
        {
          name: 'associateForm',
          caption: '目标表单(id)',
          dataType: 'string',
          sdHidden: true,
          attr: {},
        },
        {
          name: 'associateForm$Src',
          caption: '目标表单',
          dataType: 'string',
          required: true,
          attr: {},
        },
        {
          name: 'creator',
          caption: '创建者',
          dataType: 'string',
          attr: {
            displayExpr: '#bean.formType == "1"',
          },
        },
        {
          name: 'defaultValues',
          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: {},
              },
            ],
          },
        },
      ],
      creatorOptions: [
        { label: '当前处理人', value: '1' },
        { label: '表单字段', value: '2' },
      ],
      formulaFieldsMap: [],
      constants: [],
    }
  },
  created() {
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      this.fields.forEach((f) => {
        const value =
          f.name === 'defaultValues' ? this.dataSource.methodItems : this.dataSource[f.name]
        f.value = value && typeof value === 'object' ? JSON.stringify(value) : value
      })
      // 流程表单，没有创建者属性时，[兼容历史数据]默认为当前处理人
      if (this.dataSource.formType === '1' && this.dataSource.creatorType === undefined) {
        this.$set(this.dataSource, 'creatorType', '1')
      }
      this.updateConstants(this.dataSource.associateForm)
    }
  },
  methods: {
    validate() {
      return this.$refs.form.validateFields()
    },
    getSubTableFields(fieldName) {
      return this.$refs.form.getFieldValue(fieldName)?.map((v) => v.destColumn) || []
    },
    loadOnlineFormListPickerData() {
      return ApplicationService.getOnlFormListData(this.SdEventsManage.appId)
    },
    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])
    },
    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.afterTargetFormChange(value[0])
      } else if (field === 'defaultValues') {
        this.dataSource.methodItems = value
      } else {
        this.dataSource[field] = value
      }
    },
    afterTargetFormChange(oForm) {
      this.$delete(this.dataSource, 'formFieldCreator')
      this.updateConstants(oForm?.id)
      if (oForm) {
        const isFlow = oForm.formType === 1
        // 表单类型
        const formType = isFlow ? '1' : '0'
        this.$refs.form.setFieldValue('formType', formType)
        this.$set(this.dataSource, 'formType', formType)
        if (isFlow) {
          this.$set(this.dataSource, 'creatorType', '1')
        }
      } else {
        this.$refs.form.setFieldValue('formType', undefined)
        this.$delete(this.dataSource, 'formType')
        this.$delete(this.dataSource, 'creatorType')
      }
    },
    updateConstants(formId) {
      ApplicationService.getFormConstants(formId).then((consts) => {
        this.constants = consts
      })
    },
  },
}
</script>

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