<template>
  <div class="mobile-table-container">
    <!-- 移动端卡片式列表 -->
    <div v-if="isMobile" class="mobile-card-list">
      <div 
        v-for="(row, index) in data" 
        :key="getRowKey(row, index)"
        class="mobile-card-item"
        :class="{ 'selected': isSelected(row) }"
        @click="handleCardClick(row, index)"
      >
        <!-- 卡片头部 -->
        <div class="card-header" v-if="showHeader">
          <div class="card-title">
            <slot name="header" :row="row" :index="index">
              {{ getHeaderText(row) }}
            </slot>
          </div>
          <div class="card-actions" v-if="showSelection || showActions">
            <el-checkbox 
              v-if="showSelection"
              :value="isSelected(row)"
              @click.stop="handleSelect(row)"
              @change="handleSelectChange(row, $event)"
            />
            <el-dropdown 
              v-if="showActions"
              trigger="click"
              @command="(cmd) => handleAction(cmd, row)"
              @click.stop
            >
              <span class="action-btn" @click.stop>
                <i class="el-icon-more"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <slot name="actions" :row="row" :index="index">
                  <el-dropdown-item 
                    v-for="action in actions"
                    :key="action.key"
                    :command="action.key"
                    :disabled="action.disabled && action.disabled(row)"
                  >
                    <i :class="action.icon" v-if="action.icon"></i>
                    {{ action.label }}
                  </el-dropdown-item>
                </slot>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        
        <!-- 卡片内容 -->
        <div class="card-content">
          <slot name="content" :row="row" :index="index">
            <div 
              v-for="column in columns" 
              :key="column.prop || column.key"
              class="card-field"
              v-if="column.visible !== false"
            >
              <div class="field-label">{{ column.label }}</div>
              <div class="field-value">
                <slot 
                  :name="`column-${column.prop || column.key}`"
                  :row="row"
                  :column="column"
                  :value="getFieldValue(row, column)"
                >
                  <dict-tag 
                    v-if="column.dictType"
                    :options="getDictOptions(column.dictType)"
                    :value="getFieldValue(row, column)"
                  />
                  <span v-else-if="column.type === 'switch'">
                    <el-switch 
                      :value="getFieldValue(row, column)"
                      :active-value="column.activeValue"
                      :inactive-value="column.inactiveValue"
                      @change="(val) => handleSwitchChange(row, column, val)"
                      disabled
                    />
                  </span>
                  <span v-else>{{ formatValue(getFieldValue(row, column), column) }}</span>
                </slot>
              </div>
            </div>
          </slot>
        </div>
        
        <!-- 卡片底部操作 -->
        <div class="card-footer" v-if="showFooter">
          <slot name="footer" :row="row" :index="index">
            <el-button 
              v-for="btn in footerButtons"
              :key="btn.key"
              :type="btn.type || 'text'"
              :size="btn.size || 'small'"
              :icon="btn.icon"
              :disabled="btn.disabled && btn.disabled(row)"
              @click.stop="handleButtonClick(btn, row)"
            >
              {{ btn.label }}
            </el-button>
          </slot>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="!data || data.length === 0"
        description="暂无数据"
        :image-size="100"
      />
    </div>
    
    <!-- 桌面端表格 -->
    <el-table 
      v-else
      v-bind="$attrs"
      :data="data"
      v-on="$listeners"
    >
      <slot></slot>
    </el-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'MobileTable',
  inheritAttrs: false,
  props: {
    data: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    showSelection: {
      type: Boolean,
      default: false
    },
    showActions: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    showFooter: {
      type: Boolean,
      default: true
    },
    actions: {
      type: Array,
      default: () => []
    },
    footerButtons: {
      type: Array,
      default: () => []
    },
    selectedRows: {
      type: Array,
      default: () => []
    },
    headerField: {
      type: String,
      default: 'name'
    }
  },
  computed: {
    ...mapGetters(['device']),
    isMobile() {
      return this.device === 'mobile' || window.innerWidth < 768
    }
  },
  methods: {
    getRowKey(row, index) {
      if (typeof this.rowKey === 'function') {
        return this.rowKey(row, index)
      }
      return row[this.rowKey] || index
    },
    isSelected(row) {
      if (!this.showSelection || !this.selectedRows) return false
      const key = this.getRowKey(row)
      return this.selectedRows.some(r => this.getRowKey(r) === key)
    },
    handleSelect(row) {
      this.$emit('select', row)
    },
    handleSelectChange(row, selected) {
      this.$emit('selection-change', row, selected)
    },
    handleCardClick(row, index) {
      this.$emit('row-click', row, index)
    },
    handleAction(command, row) {
      this.$emit('action', command, row)
    },
    handleButtonClick(btn, row) {
      if (btn.handler) {
        btn.handler(row)
      }
      this.$emit('button-click', btn.key, row)
    },
    getFieldValue(row, column) {
      if (column.formatter) {
        return column.formatter(row, column, row[column.prop], index)
      }
      if (typeof column.prop === 'function') {
        return column.prop(row)
      }
      return column.prop ? this.getNestedValue(row, column.prop) : ''
    },
    getNestedValue(obj, path) {
      return path.split('.').reduce((o, p) => o && o[p], obj)
    },
    formatValue(value, column) {
      if (value === null || value === undefined) return '-'
      if (column.formatter) {
        return column.formatter(null, column, value)
      }
      return value
    },
    getHeaderText(row) {
      if (this.headerField) {
        return this.getNestedValue(row, this.headerField) || '未命名'
      }
      return row.name || row.title || '未命名'
    },
    getDictOptions(dictType) {
      // 这里需要根据实际的字典获取方式来实现
      // 可以通过 this.$store 或 this.$parent 获取字典数据
      try {
        const dictData = this.$store?.state?.dict?.dict || {}
        return dictData[dictType] || []
      } catch (e) {
        return []
      }
    },
    handleSwitchChange(row, column, value) {
      this.$emit('switch-change', row, column, value)
    }
  }
}
</script>

<style lang="scss" scoped>
.mobile-table-container {
  width: 100%;
}

.mobile-card-list {
  padding: 10px;
  background: #f5f5f5;
  min-height: 200px;
}

.mobile-card-item {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
  }
  
  &.selected {
    border: 2px solid #409eff;
    background: #f0f9ff;
  }
  
  &:last-child {
    margin-bottom: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  
  .card-title {
    flex: 1;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .card-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-shrink: 0;
    
    .action-btn {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: #f5f5f5;
      color: #606266;
      cursor: pointer;
      transition: all 0.3s;
      
      &:active {
        background: #e4e7ed;
      }
      
      i {
        font-size: 18px;
      }
    }
  }
}

.card-content {
  .card-field {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .field-label {
      font-size: 13px;
      color: #909399;
      min-width: 80px;
      flex-shrink: 0;
      margin-right: 12px;
    }
    
    .field-value {
      flex: 1;
      font-size: 14px;
      color: #303133;
      text-align: right;
      word-break: break-all;
      
      ::v-deep .el-tag {
        margin: 0;
      }
    }
  }
}

.card-footer {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  
  ::v-deep .el-button {
    flex: 1;
    min-width: 0;
    padding: 8px 12px;
  }
}

// 桌面端隐藏
@media (min-width: 769px) {
  .mobile-card-list {
    display: none;
  }
}

// 移动端隐藏表格
@media (max-width: 768px) {
  ::v-deep .el-table {
    display: none;
  }
}
</style>

