<template>
  <sd-form ref="form" :init-values="initValues">
    <template v-slot="{ model }">
      <table class="sd-form-table">
        <tr v-for="field in initValues" :key="field.name">
          <sd-form-item-td :name="field.name">
            <!-- 修改字段 -->
            <sd-list-picker
              v-if="field.name === 'userName'"
              v-model="model[field.name]"
              single
              :load-list-data="loadFieldListPicker"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- 账号字段 -->
            <sd-list-picker
              v-if="field.name === 'userAccount'"
              v-model="model[field.name]"
              single
              :load-list-data="loadFieldListPicker"
              @change="(value) => valueChange(value, field.name)"
            />
            <!-- ID字段 -->
            <sd-list-picker
              v-if="field.name === 'userId'"
              v-model="model[field.name]"
              single
              :load-list-data="loadFieldListPicker"
              @change="(value) => valueChange(value, field.name)"
            />
          </sd-form-item-td>
        </tr>
      </table>
    </template>
  </sd-form>
</template>

<script>
import components from './_import-components/xm-iam-rectify-user-import'

export const metaInfo = {
  name: '设置子表用户信息',
  order: 100,
}

export default {
  name: 'XmIamRectifyUser',
  components: {
    ...components,
  },
  data() {
    return {
      initValues: [
        {
          name: 'userName',
          caption: '姓名字段',
          dataType: 'string',
          required: true,
        },
        {
          name: 'userAccount',
          caption: '账号字段',
          dataType: 'string',
          required: true,
        },
        {
          name: 'userId',
          caption: 'ID字段',
          dataType: 'string',
          required: false,
        },
      ],
    }
  },
  created() {
    // 编辑时
    if (Object.keys(this.dataSource).length > 0) {
      this.initValues.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()
    },
    loadFieldListPicker() {
      return Promise.resolve(
        this.SdEventsManage?.component?.attr?.dync
          ?.filter((f) => f.dataType !== 'attachment')
          ?.map((f) => ({ id: f.name, name: f.caption })) || []
      )
    },
    valueChange(value, field) {
      this.dataSource[field] = value
    },
  },
}
</script>

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