<template>
  <div>
    <a-modal
      v-model="visible"
      destroy-on-close
      :title="button.buttonName"
      :width="800"
      ok-text="保存"
      cancel-text="退出"
      :body-style="{ minHeight: '380px' }"
      @ok="save"
      @cancel="() => (visible = false)"
    >
      <sd-form ref="form" :init-values="initValues">
        <sd-table-layout-form :fields="initValues" :form-props="{ columns: 1 }" />
      </sd-form>
    </a-modal>
  </div>
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import sdTableLayoutForm from '@/form-designer/sd-table-layout-form.vue'
import components from './_import-components/sd-batch-modify-handler-import'

export default {
  name: 'SdBatchModifyHandler',
  components: {
    ...components,
    sdTableLayoutForm,
  },
  data() {
    return {
      visible: false,
      button: {},
      initValues: [],
      childTable: undefined,
      selectedRows: [],
    }
  },
  methods: {
    run({ button, eventScript, context: { childTable, selectedRows } }) {
      this.button = button
      this.childTable = childTable
      this.selectedRows = selectedRows
      // 根据需修改的字段，获取字段信息
      const modifyFields = eventScript.modifyFields.map((f) => f.id)
      const fields = cloneDeep(childTable.fields).filter((f) => !f.attrFD?.hidden)
      // 获取非隐藏 且 包含在事件配置修改字段中的字段（字段显示顺序：事件中配置的字段顺序）
      this.initValues =
        modifyFields
          .map((name) => {
            const f = fields.find((_) => _.name === name)
            // 找到字段，判断非子表时，将隐藏label属性删除(高级布局时字段的label会设置隐藏)
            if (f && f.dataType !== 'collection' && f.attrFD) {
              delete f.attrFD.hideLabel
            }
            return f
          })
          .filter((f) => !!f) || []
      this.visible = true
    },
    save() {
      this.$refs.form.validateFields().then((flag) => {
        if (flag) {
          // 先获取修改的数据
          const modifyData = {}
          this.$refs.form.getBackendValues().forEach((item) => {
            modifyData[item.name] = item.value ?? null
          })
          // 将修改的数据更新到记录中
          this.selectedRows.forEach((r) => {
            Object.assign(r, modifyData)
            this.childTable.setRowValueById(r.id, r)
          })
          this.visible = false
        }
      })
    },
  },
}
</script>

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