<template>
  <div class="table-layout">
    <ul class="t-header" :class="{line:showLine}">
      <li v-if="selection" class="check-cls"><span @click="lock=false,selectAll=!selectAll" class="fdcheck" :class="{check_active:selectAll}"></span></li>
      <li v-for="(item,i) in header" :key="i" :style="{textAlign:item.textAlign,width:item.width ?item.width+'px':(100/header.length)+'%'}">
        <slot :data='item' name='header'></slot>
      </li>
    </ul>
    <div class="t-con">
      <ul class="t-item" active-txt :class="{line:showLine}" v-for="(item,i) in fixdata" :key="i">
        <li v-if="selection" class="check-cls" ><span @click="selectItem(item,i)" class="fdcheck" :class="{check_active:item.hasAuth}"></span></li>
        <li :class="{themetxt:sub.fontweight}" v-for="(sub,j) in header" :key='j' :style="{textAlign:item.textAlign,width:sub.width ? sub.width+'px':(100/header.length)+'%'}">
          <slot :data='item[sub.key]' :item="item"  :sub='sub' name='item'></slot>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'

export default {
  props: ['data', 'header', 'selection', 'showLine'],
  data () {
    return {
      innerW: window.innerWidth,
      selectAll: false,
      lock: true
    }
  },
  computed: {
    ...mapState({
      fixdata () {
        let data = this.data && this.data.map(item => {
          item.hasAuth = false
          return item
        })
        return data
      }
    })

  },
  watch: {
    data () {
      this.selectAll = false
    },
    selectAll: function (newVal) {
      if (!this.lock) {
        this.fixdata.forEach(item => {
          item.hasAuth = newVal
        })
        this.handleSelect()
      }
    }
  },
  methods: {
    handleSelect () {
      let arr = this.fixdata.filter(item => {
        return item.hasAuth
      })
      this.$emit('selection-change', arr)
    },
    selectItem (item, i) {
      item.hasAuth = !item.hasAuth
      this.$set(this.fixdata, i, item)
      this.lock = true
      this.selectAll = true
      this.fixdata.forEach(sub => {
        if (!sub.hasAuth) {
          this.selectAll = false
        }
      })
      this.handleSelect()
    }
  },
  mounted () {
  }
}
</script>

<style lang="less" scoped>
@import './style.less';
</style>
