<template>
  <a-row :gutter="0" class="list-container">
    <a-col
      v-for="config in configs"
      :key="config.tmp_key"
      :span="24 / configs.length"
    >
      <x-questionnaire-item
        class="list-item"
        :fixedQueryForm="conditionsMap[config.tmp_key]"
        :queryParamsName="config"
        :ref="el => setItemRef(el, config)"
        @customizeEvent="customizeEvent"
      />
    </a-col>
  </a-row>
</template>

<script>

import { getConfigByName } from '@vue2-client/services/api/common'
import XQuestionnaireItem from './XQuestionnaireItem.vue'

export default {
  name: 'XQuestionnaire',
  props: {
    queryParamsName: {
      type: String,
      default: null
    }
  },
  inject: ['getComponentByName'],
  components: {
    XQuestionnaireItem
  },
  data () {
    return {
      configs: [],
      questionnaireItemRefs: new Map(), // 存储子组件实例
      conditionsMap: {}
    }
  },
  methods: {
    // 获取配置
    async getData (queryParamsName, conditionData) {
      getConfigByName(queryParamsName, 'af-his', res => {
        // 清空旧数据
        this.configs = []
        this.conditionsMap = { ...this.conditionsMap }
        console.log(res)
        res.configs.forEach(config => {
          this.configs.push(config)
          // 响应式更新条件映射
          this.$set(this.conditionsMap, config.tmp_key,
            conditionData[config.tmp_key] || {}
          )
        })
      })
    },
    customizeEvent (customize, callback) {
      console.log(this.$listeners)
      console.log(customize)
      if (customize.clickEventName && this.$listeners[customize.clickEventName]) {
        // 交由父级处理
        this.$emit(customize.clickEventName, customize, callback)
      } else {
        this.defaultAction(customize.clickEventName, customize, callback)
      }
    },
    defaultAction (clickEventName, item, callback) {
      setTimeout(() => {
        this.$message.warn(`已触发按钮 [${item.key}]，注册事件名 [${clickEventName}]，未实现事件函数`)
        callback()
      }, 200)
    },
    setItemRef (el, config) {
      if (el) {
        this.questionnaireItemRefs.set(config.tmp_key, el)
      } else {
        this.questionnaireItemRefs.delete(config.tmp_key) // 组件卸载时清理
      }
    },
    async init (conditionData) { // 接收完整条件对象
      // this.$emit('init')
      console.log('conditionData===>', conditionData)
      await this.getData(this.queryParamsName, conditionData)
    },

    refreshList (tmpKey, condition) {
      // 更新条件映射
      this.$set(this.conditionsMap, tmpKey, condition)
      // // 调用子组件刷新
      // this.questionnaireItemRefs.get(tmpKey)?.refreshList(condition)
    },
  },
}
</script>
<style scoped>
.list-container{
  width: 100%;
  padding: 10px;
}
.list-item{
  height: 100%;
}
</style>
