<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 === 'targetForm'"
              v-model="model[field.name]"
              single
              :load-list-data="loadOnlineFormListPickerData"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 业务类型 -->
            <sd-select
              v-if="field.name === 'businessTypeId'"
              v-model="model[field.name]"
              :options="businessTypeOptions"
              allow-clear
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 子表：默认值 -->
            <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">
                    <sd-field-picker
                      v-model="subModel.destColumn"
                      :form-id="dataSource.targetForm?.[0]?.id"
                      :disabled-keys="
                        [...otherFieldsMap, 'id'].filter(
                          (i) => i !== JSON.parse(subFields.destColumn.value || '[{}]')[0].id
                        )
                      "
                      :disabled-types="['collection', 'OpinionView']"
                      :type="subModel.srcColumn?.[0]?.type"
                    />
                  </sd-form-item-td>
                </tr>
                <tr>
                  <sd-form-item-td
                    name="opType"
                    @change="
                      () => {
                        subModel.value = undefined
                        subModel.srcColumn = undefined
                      }
                    "
                  />
                </tr>
                <tr>
                  <sd-form-item-td name="value" />
                </tr>
                <tr>
                  <!-- 赋表单值 -->
                  <sd-form-item-td name="srcColumn" label="值">
                    <sd-field-picker
                      v-model="subModel.srcColumn"
                      :form-id="SdEventsManage.formId"
                      :disabled-types="['collection', 'OpinionView']"
                      :type="subModel.destColumn?.[0]?.type"
                    />
                  </sd-form-item-td>
                </tr>
              </table>
            </template>
            <!-- 子表：字段显示 -->
            <template v-if="field.name === 'defaultValues'" v-slot:input-destColumn="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 axios from '@/common/services/axios-instance'
import GuideService from '@/guide/guide-service'
import ApplicationService from '@/application-manage/application-service'
import sdValueDisplay from '../../back-end/child-table/sd-value-display.vue'
import components from './_import-components/sd-create-import'

export const metaInfo = {
  name: '新建',
  order: 100,
}

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: 'targetForm',
          caption: '目标表单',
          dataType: 'string',
          required: true,
          attr: {},
        },
        {
          name: 'businessTypeId',
          caption: '业务类型',
          dataType: 'string',
          attr: {
            displayExpr: '#bean.formType == "1"',
          },
        },
        {
          name: 'newWindow',
          caption: '新窗口打开',
          dataType: 'selectlist',
          attr: {
            selectListItem: [
              { label: '是', value: '1' },
              { label: '否', value: '0' },
            ],
          },
        },
        {
          name: 'defaultValues',
          caption: '默认值',
          dataType: 'collection',
          attr: {
            dync: [
              {
                name: 'destColumn',
                caption: '表单字段',
                dataType: 'string',
                required: true,
                attr: {},
              },
              {
                name: 'opType',
                caption: '赋值方式',
                dataType: 'selectlist',
                attr: {
                  defaultValue: 'direct',
                  selectListItem: [
                    { label: '赋表单值', value: 'direct' },
                    { label: '手动输入', value: 'manual' },
                  ],
                },
              },
              {
                name: 'value',
                caption: '值',
                dataType: 'string',
                attr: {
                  displayExpr: '#bean.opType != "direct"',
                },
              },
              {
                name: 'srcColumn',
                caption: '目标表单(字段)',
                dataType: 'string',
                sdHidden: true,
                attr: {
                  displayExpr: '#bean.opType == "direct"',
                },
              },
            ],
          },
        },
      ],
      businessTypeOptions: [],
    }
  },
  computed: {
    otherFieldsMap() {
      return (
        this.dataSource?.defaultValues?.map((item) => JSON.parse(item.destColumn || '[]')[0]?.id) ||
        []
      )
    },
  },
  created() {
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      // 加载表单的业务类型
      if (this.dataSource.appModuleId) {
        GuideService.getYwlxByModuleId(this.dataSource.appModuleId).then((businessTypes) => {
          this.businessTypeOptions = businessTypes.map((v) => ({
            id: v.id,
            name: v.businessTypeName,
          }))
        })
      }
      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 (['targetForm', 'businessTypeId', 'defaultValues'].includes(field)) {
        this.$set(this.dataSource, field, value)
        if (field === 'targetForm') {
          this.afterTargetFormChange(value[0])
        }
      } else if (field === 'newWindow') {
        this.dataSource[field] = value.target.value
      }
    },
    afterTargetFormChange(oForm) {
      this.$refs.form.setFieldValue('businessTypeId', undefined)
      this.$delete(this.dataSource, 'businessTypeId')
      if (oForm) {
        const isFlow = oForm.formType === 1
        // 新窗口打开
        const newWindow = isFlow ? '1' : '0'
        this.$refs.form.setFieldValue('newWindow', newWindow)
        this.dataSource.newWindow = newWindow
        // 表单类型
        const formType = isFlow ? '1' : '0'
        this.$refs.form.setFieldValue('formType', formType)
        this.$set(this.dataSource, 'formType', formType)
        // 获取模块化表单ID（appModuleId）
        axios.get('api/framework/v1/we-app-module/get-module-id?formId=' + oForm.id).then((res) => {
          this.dataSource.appModuleId = res.data.moduleId
          // 获取流程表单对应的业务类型
          if (isFlow) {
            GuideService.getYwlxByModuleId(res.data.moduleId).then((values) => {
              this.businessTypeOptions = values.map((v) => ({ id: v.id, name: v.businessTypeName }))
            })
          }
        })
      } else {
        this.$refs.form.setFieldValue('formType', undefined)
        this.$delete(this.dataSource, 'formType')
        this.$delete(this.dataSource, 'appModuleId')
        this.businessTypeOptions = []
      }
    },
  },
}
</script>

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