<template>
  <confirm-dialog
    ref="confirmDialg"
    :size="sizeClassName"
    v-bind="$attrs"
    @confirm="onConfirm"
  >
    <template #default>
      <schema-table
        ref="table"
        :schema="tableSchema"
        :row-key="rowKey"
        :current-row-key="selectedKey"
        highlight-current-row
        @row-click="onClickRow"
      >
        <template
          v-if="hasHeader"
          #header="scope"
        >
          <slot
            name="header"
            :item="selectedRow"
            v-bind="scope"
          />
        </template>
      </schema-table>
    </template>
  </confirm-dialog>
</template>

<script>
export default {
  name: 'RadioTableDialog',
  props: {
    schema: {
      type: Object,
      required: true
    },
    size: {
      type: String,
      default: 'medium'
    },
    message: {
      type: String,
      default: '请选择内容'
    },
    rowKey: {
      type: String,
      default: 'id'
    }
  },
  data () {
    return {
      selectedRow: null
    }
  },
  computed: {
    hasHeader () {
      return !!this.$scopedSlots.header
    },
    selectedKey () {
      return this.selectedRow?.[this.rowKey]
    },
    tableSchema () {
      const { cols, ...data } = this.schema
      return {
        ...data,
        cols: [
          { render: (data, h) => h(
            'span',
            { staticClass: `el-radio__input ${data[this.rowKey] === this.selectedKey ? 'is-checked' : ''}` },
            [h('span', { staticClass: 'el-radio__inner' })]
          ), width: 60, align: 'center' },
          ...cols
        ]
      }
    },
    sizeClassName () {
      return `table ${this.size} fixed`
    }
  },
  methods: {
    show (current) {
      this.selectedRow = current
      this.$refs.confirmDialg.show()
    },
    onConfirm (done) {
      if (!this.selectedKey) {
        this.$message({
          type: 'warning',
          message: this.message
        })
        return
      }
      this.$emit('confirm', {
        value: this.selectedRow,
        done
      })
    },
    onClickRow (row) {
      this.selectedRow = row
    }
  }
}
</script>
