<template>
  <div class="sv-table-wrapper">
    <!-- 用来承载table内容，但是内容需要在组件中处理加工，故此处将其隐藏不予以显示 -->
    <div v-show="false">
      <slot></slot>
    </div>
    <table class="sv-table" :class="{'has-border': border}">
      <thead class="sv-table-head">
        <tr>
          <template v-for="col in cols">
            <th>
              <div :style="colClass(col)">{{col.title}}</div>
            </th>
          </template>
        </tr>
      </thead>
      <tbody class="sv-table-body">
        <tr v-if="!data || data.length === 0">
          <td :colspan="cols.length" align="center">暂无数据</td>
        </tr>
        <tr v-for="tr in data">
          <td v-for="(value, key, index) in tr" :class="{'nowrap': cols[index] && cols[index].nowrap}">
            {{value}}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  export default {
    name: 'svTable',
    props: {
      data: {
        type: Array,
        required: true
      },
      border: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        cols: []
      }
    },
    methods: {
      colClass (col) {
        if (!col.width) return ''
        return {
          width: `${col.width}px`
        }
      },
      processTable () {
        let cols = this.$children
        cols.forEach(col => {
          this.cols.push({
            title: col.title,
            width: col.width,
            nowrap: col.nowrap
          })
        })
      }
    },
    mounted () {
      this.processTable()
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss">
  @import "../../styles/base";
  .sv-table-wrapper{
    width: 100%;
    overflow: auto;
    .sv-table{
      min-width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      &.has-border{
        tr{
          th, td{
            border: 1px solid #ccc;
          }
        }
      }
      tr{
        border-bottom: 1px solid #dfe6ec;
        th, td{
          padding: pxToRem(10);
          color: #1f2d3d;
          /*border: 1px solid red;*/
        }
        th{
          text-align: left;
        }
      }
      .sv-table-head{
        background: #eef1f6;
        tr{
          th{
            white-space: nowrap;
          }
        }
      }
      .sv-table-body{
        tr{
          td{
            &.nowrap{
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
</style>
