<template>
  <div class="list-wrapper">
    <a-list
      size="large"
      :data-source="data"
      itemLayout="horizontal"
      class="list-container"
      ref="listRef"
      :split="config.split === 'true'"
    >
      <template v-if="config.header" #header>
        <div >{{ config.header }}</div>
      </template>
      <a-list-item
        :class="[{ 'header-row': item.type === 'header','item-split': item.split}]"
        slot="renderItem"
        slot-scope="item, index">
        <div
          class="row-item"
          :style="{ justifyContent: getFlexJustify(item.style) }"
        >
          <template v-for="(column, idx) in item.columns">
            <template v-if="column.type === 'selectionBox'">
              <a-checkbox @change="handleChange($event,column)" v-model="column.value" :key="`row-${index}-item-${idx}`" :class="['column-item']"></a-checkbox>
            </template>
            <template v-else-if="column.type === 'input'">
              <a-input :size="column?.customize?.size || 'default'" @change="handleChange($event,column)" :key="`row-${index}-item-${idx}`" :class="['column-item','item-input']" v-model="column.value" />
            </template>
            <template v-else-if="column.type === 'time'">
              <x-time-select :key="`row-${index}-item-${idx}`" :value="column.value" :class="['column-item']" @change="handleChange($event,column)" :queryParamsName="column.configName"/>
            </template>
            <template v-else-if="column.type === 'text'">
              <span :key="`row-${index}-item-${idx}`" :class="['column-item','item-text']"> {{ column.value }} </span>
            </template>
            <template v-else-if="column.type === 'describe'">
              <span :key="`row-${index}-item-${idx}`" :class="['column-item','item-describe']"> {{ column.value }} </span>
            </template>
            <template v-else-if="column.type === 'header'">
              <span :key="`row-${index}-item-${idx}`" :class="['item-header']"> {{ column.value }} </span>
            </template>
            <template v-else-if="column.type === 'radio'">
              <x-radio
                :class="['column-item']"
                :value="column.value"
                :key="`row-${index}-item-${idx}`"
                :queryParamsName="column.configName"
                @change="handleChange($event,column)">
              </x-radio>
            </template>
            <template v-else-if="column.type === 'button'">
              <a-button
                :class="['column-item']"
                :key="`row-${index}-item-${idx}`"
                :disabled="column.customize.disabled"
                :icon="column.customize.icon"
                :loading="column.customize.loading"
                :type="column.customize.buttonType || 'default'"
                @click="handleButtonClick(column)"
              >
                {{ column.value }}
              </a-button>
            </template>
            <template v-else>
              <span :key="`row-${index}-item-${idx}`" :class="['column-item','item-text']"> {{ column.value }} </span>
            </template>
          </template>
        </div>
      </a-list-item>
    </a-list>
  </div>
</template>

<script>

import { runLogic } from '@vue2-client/services/api/common'
import XRadio from '@vue2-client/base-client/components/his/XRadio/XRadio'
import XTimeSelect from '@vue2-client/base-client/components/his/XTimeSelect/XTimeSelect'
export default {
  name: 'XQuestionnaireItem',
  props: {
    queryParamsName: {
      type: Object,
      default: null
    },
    fixedQueryForm: {
      type: Object,
      default: () => ({ condition: '1=1' })
    }
  },
  inject: ['getComponentByName'],
  components: {
    XTimeSelect,
    XRadio
  },
  data () {
    return {
      data: [],
      config: {
        split: true,
        header: null
      },
      results: {},
      oldFixedQueryForm: null
    }
  },
  created () {
    console.log('queryParamsName', this.queryParamsName)
    this.getData(this.queryParamsName, this.fixedQueryForm)
  },
  methods: {
    // 获取配置
    async getData (config, param) {
      const that = this
      that.config = { ...that.config, ...config }
      runLogic(config.data, param, 'af-his').then(res => {
        that.results = {}
        // 将有返回值的数据创建到results
        for (let i = 0; i < res.length; i++) {
          const fields = res[i]
          if (!fields.columns) {
            continue
          }
          for (let j = 0; j < fields.columns.length; j++) {
            const field = fields.columns[j]
            if (this.results[field.config_id]) {
              console.error(`Config_id 冲突: ${field.config_id} 重复,同一个模板中不能有形同的配置项`)
              return
            }
            let value_
            if (field.type === 'selectionBox') {
              value_ = field.value === 'true' // 将字符串转为布尔值
            } else if (field.type === 'radio') {
              value_ = parseInt(field.value) || 0
            } else if (field.type === 'time') {
              value_ = field.value ? this.parseToArray(field.value) : []
            } else {
              value_ = field.value
            }
            // 将符合条件的字段存入results
            if (['selectionBox', 'input', 'radio', 'time'].includes(field.type)) {
              this.results[field.config_id] = {
                value: value_,
                data_id: field.data_id
              }
            }
            field.value = value_
            console.log(this.results)
          }
        }
        that.data = res || []
      })
    },
    parseToArray (value) {
      try {
        if (Array.isArray(value)) return value
        if (typeof value === 'string') {
          const parsed = JSON.parse(value)
          return Array.isArray(parsed) ? parsed : [parsed]
        }
      } catch (e) {
        return [value]
      }
    },
    refreshList (param) {
      this.getData(this.queryParamsName, param)
    },
    // 行数据排量方式
    getFlexJustify (style) {
      const validStyles = [
        'flex-start', 'flex-end', 'center',
        'space-between', 'space-around'
      ]
      return validStyles.includes(style) ? style : 'flex-start'
    },
    // 数据发生改变--将修改后的值填充到results
    handleChange (e, column) {
      console.log('数据发生改变:', e, column)
      if (column.type === 'selectionBox') {
        this.results[column.config_id].value = e.target.checked
      } else if (column.type === 'input') {
        this.results[column.config_id].value = column.value
      } else if (column.type === 'radio' || column.type === 'time') {
        this.results[column.config_id].value = e
      }
    },
    handleButtonClick (item) {
      item.customize.loading = true
      const callback = () => {
        item.customize.loading = false
      }
      this.$emit('customizeEvent', item.customize, callback)
    }
  },
  watch: {
    fixedQueryForm: {
      deep: true,
      handler (val) {
        this.refreshList(val)
      }
    }
  }
}
</script>

<style scoped>

.list-wrapper {
  border: 1px solid #f0f0f0;
}
.list-container {
  width: 100%;
}
/* header样式 */
.list-wrapper ::v-deep .ant-list-header {
  background-color: #F4F4F4; /* 自定义背景色 */
  display: flex;
  justify-content: center;
}
.list-wrapper ::v-deep .ant-list-item {
  padding-top: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid transparent;
}

.list-wrapper ::v-deep .x-radio-item {
  margin-bottom: 0;
}
.list-wrapper ::v-deep .x-radio-item-container{
  padding: 0;
}
.list-wrapper ::v-deep span.ant-radio + *{
  padding: 0;
}
.list-wrapper ::v-deep .x-time-select {
  width: auto !important;
}
.list-wrapper ::v-deep .header-row {
  background-color: #F4F4F4; /* 自定义背景色 */
  height: 45px !important;
}
/*每一行的整体样式*/
.row-item{
  width: 100%;
  display: flex;
  align-items: center;
  padding: 2px;
  height: 30px;
}
/*行中每一列的数据*/
.column-item{
  margin-left: 10px;
}
.item-text {
  color: black;
}
.item-describe {
  color: #808080 ;
}
.item-input{
  width: auto !important;
}
.item-header {
  color: rgba(0, 0, 0, 0.65)
}
.item-split{
  border-bottom: 1px solid #f0f0f0 !important;
}

</style>
