<template>
  <div 
    class="widget-table widget-view"
    :class="{
      active: selectWidget.key && selectWidget.key == element.key,
      'is_hidden': element.options.hidden,
      'mobile': platform == 'mobile'
    }"
    @click.stop="handleSelectWidget(index)"
    @mouseover.stop="handleMouseover"
    @mouseout="handleMouseout"
    ref="widgetTable"
  >
    <el-form-item 
      :label="element.options.hideLabel ? '' : element.name"
      :label-width="element.options.hideLabel ? '0px' : (element.options.isLabelWidth ? element.options.labelWidth + 'px' : '')"
      :class="{
        [element.options && element.options.customClass]: element.options.customClass?true: false,
        'fm-label-wrap': element.options.labelWrap
      }"
    >
      <div v-if="element.options.tip" class="fm-item-tooltip" v-html="element.options.tip.replace(/\n/g, '<br/>')"></div>
      <div class="widget-table-wrapper" :class="{'mobile': platform == 'mobile'}">
        <el-table :data="[{}]" class="widget-table-left" :style="{width: widgetTableLeftWidth}" row-class-name="widget-table-row" v-if="platform != 'mobile'">
          <el-table-column v-if="element.options.selection"
            fixed
            type="selection"
            width="50">
          </el-table-column>
          <el-table-column label="#" width="50" fixed v-if="element.options.showControl">
            <template slot-scope="scope">{{scope.$index + 1}}</template>
          </el-table-column>
        </el-table>
        <div class="widget-table-top" v-if="platform == 'mobile'">
          <el-checkbox v-if="element.options.selection" style="margin-right: 10px;"></el-checkbox>
          # 1
        </div>
        <div class="widget-table-content" :class="{'mobile': platform == 'mobile'}">
          <div v-if="element.tableColumns.length == 0" class="table-empty">{{$t('fm.description.tableEmpty')}}</div>
          <draggable
            v-model="element.tableColumns"
            v-bind="{group:{name: 'people', put: handlePut}, ghostClass: 'ghost',animation: 200, handle: '.drag-widget'}"
            :no-transition-on-drag="true"
            @add="handleWidgetTableAdd($event, element)"
            @update="handleWidgetTableUpdate"
            @start="setDragging(true)"
            @end="setDragging(false)"
          >
            <transition-group name="fade" tag="div" class="widget-table-col" :style="{width: platform != 'mobile' ? columnsWidthStyle : '100%'}">

              <widget-table-item 
                v-for="(item, index) in element.tableColumns" v-if="item.key"
                :key="item.key" 
                :element="item"
                :tableElement="element"
                :select.sync="selectWidget" 
                :index="index" :data="element.tableColumns"
                @select-change="handleSelectChange($event, item)"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-table-item>
            </transition-group>
          </draggable>
        </div>
      </div>
    </el-form-item>
    <div class="widget-view-action widget-col-action" v-if="selectWidget.key == element.key">
      <i class="fm-iconfont icon-icon_clone" @click.stop="handleTableClone(index)" :title="$t('fm.tooltip.clone')"></i>
      <i class="fm-iconfont icon-trash" @click.stop="handleWidgetDelete(index)" :title="$t('fm.tooltip.trash')"></i>
    </div>

    <div class="widget-view-drag widget-col-drag" v-if="selectWidget.key == element.key">
      <i class="fm-iconfont icon-drag drag-widget"></i>
    </div>
    <div class="widget-view-model" :style="{'color': element.options.dataBind ? '' : '#666'}">
      <span>{{element.model}}</span>
    </div>
    <div class="widget-view-type ">
      <span>{{element.type ? this.$t('fm.components.fields.' + element.type) : ''}}</span>
    </div>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import WidgetTableItem from './WidgetTableItem'
import _ from 'lodash'
import { CloneLayout } from '../util/layout-clone.js'
import { EventBus } from '../util/event-bus.js'
import { addClass, removeClass } from '../util'

export default {
  components: {
    Draggable,
    WidgetTableItem
  },
  props: ['element', 'select', 'index', 'data', 'platform', 'formKey'],
  inject: ['setDragging', 'getDragging'],
  data () {
    return {
      selectWidget: this.select || {},
      columnsWidthStyle: '200px'
    }
  },
  computed: {
    widgetTableLeftWidth () {
      let width = 1
      if (this.element.options.showControl) {
        width += 50
      }
      if (this.element.options.selection) {
        width += 50
      }

      return width + 'px'
    }
  },
  mounted () {
    this.calcTableColumnsWidth()
  },
  methods: {
    handleMouseover (e) {
      !this.getDragging() && addClass(this.$refs['widgetTable'], 'is-hover')
    },
    handleMouseout (e) {
      removeClass(this.$refs['widgetTable'], 'is-hover')
    },
    handleSelectWidget (index) {
      this.selectWidget = this.data.list[index]
    },
    handleWidgetDelete (index) {
      if (this.data.list.length == 1) {
        this.$emit('select-change', -1)
      } else {
        if (this.data.list.length - 1 == index) {
          this.$emit('select-change', index - 1)
        } else {
          this.$emit('select-change', index)
        }
      }
      
      this.data.list.splice(index, 1)

      setTimeout(() => {
        EventBus.$emit('on-history-add-' + this.formKey)
      }, 20)
    },
    handleTableClone (index) {
      let cloneData = _.cloneDeep(this.data.list[index])

      this.data.list.splice(index + 1, 0, CloneLayout(cloneData))

      this.$nextTick(() => {
        this.selectWidget = this.data.list[index + 1]

        this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
      })
    },
    handleWidgetTableUpdate (evt) {
      this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
    },
    calcTableColumnsWidth () {
      // this.columnsWidth = (this.element.tableColumns.length+1)*200

      this.columnsWidthStyle = 'calc(200px)'

      let widthArray = []

      for (let i = 0; i < this.element.tableColumns.length; i++) {
        if (!this.element.tableColumns[i].options.width) {
          widthArray.push('200px')
        } else {
          widthArray.push(this.element.tableColumns[i].options.width)
        }
      }

      console.log('calc', widthArray)

      widthArray.length && (this.columnsWidthStyle = `calc(200px + ${widthArray.join(' + ')})`)
    },
    handlePut (a, b, c) {
      
      if (c.className.split(' ').indexOf('widget-col') >=0 || 
        c.className.split(' ').indexOf('widget-table') >= 0 || 
        c.className.split(' ').indexOf('widget-tab') >= 0 ||
        c.className.split(' ').indexOf('widget-report') >= 0 ||
        c.className.split(' ').indexOf('widget-inline') >= 0 ||
        c.className.split(' ').indexOf('widget-subform') >= 0 ||
        c.className.split(' ').indexOf('widget-dialog') >= 0 ||
        c.className.split(' ').indexOf('widget-card') >= 0 ||
        c.className.split(' ').indexOf('widget-group') >= 0 ||
        c.className.split(' ').indexOf('no-put') >= 0 || 
        c.children[0].className.split(' ').indexOf('no-put') >= 0) {
        return false
      }
      return true
    },
    handleWidgetTableAdd ($event, table) {
      const newIndex = $event.newIndex
      const key = Math.random().toString(36).slice(-8)
      this.$set(table.tableColumns, newIndex, _.cloneDeep(table.tableColumns[newIndex]))
      this.$set(table.tableColumns, newIndex, {
        ...table.tableColumns[newIndex],
        options: {
          ...table.tableColumns[newIndex].options,
          remoteFunc: table.tableColumns[newIndex].options.remoteFunc || 'func_'+key,
          remoteOption: table.tableColumns[newIndex].options.remoteOption || 'option_'+key,
          tableColumn: true,
          subform: this.subform ? true : false
        },
        novalid: {
          ...table.tableColumns[newIndex].novalid,
        },
        key: table.tableColumns[newIndex].key ? table.tableColumns[newIndex].key : key,
        model: table.tableColumns[newIndex].model ? table.tableColumns[newIndex].model : table.tableColumns[newIndex].type + '_' + key,
        rules: table.tableColumns[newIndex].rules ? [...table.tableColumns[newIndex].rules] : []
      })

      this.selectWidget = table.tableColumns[newIndex]

      this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
    },
    handleSelectChange (index, item) {
      setTimeout(() => {
        index >=0 ? (this.selectWidget = this.element.tableColumns[index]) : (this.selectWidget = this.data.list[this.index])
      })
    }
  },
  watch: {
    select (val) {
      this.selectWidget = val
    },
    selectWidget: {
      deep: false,
      handler (val) {
        this.$emit('update:select', val)
      }
    },
    element: {
      deep: true,
      handler (val) {
        
        this.calcTableColumnsWidth()
      }
    }
  }
}
</script>
