<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 === 'modifyFields'"
              v-model="model[field.name]"
              :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/sd-batch-modify-import'

export const metaInfo = {
  name: '批量修改',
  order: 100,
}

export default {
  name: 'SdBatchModify',
  components,
  data() {
    return {
      initValues: [
        {
          name: 'modifyFields',
          caption: '修改字段',
          dataType: 'string',
          required: true,
        },
      ],
    }
  },
  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.attrFD?.hidden && 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>
