<template>
  <div
    class="widget-form-item"
    @click.stop="handleSelectWidget(index)"
    :class="{active: selectWidgetItem.key == element.key}"
  >
    <div
      class="drag-widget"
      title="拖拽"
      v-if="selectWidgetItem.key == element.key"
    >
      <i class="icon-drag"></i>
    </div>
    <div class="widget-view-action" v-if="selectWidgetItem.key == element.key">
      <i
        class="icon-application-delete del-icon"
        title="删除"
        @click.stop="handleWidgetDelete(index)"
      ></i>
    </div>
    <table
      v-if="element && element.key"
      width="100%"
      class="widget-col"
      style="table-layout: fixed"
      border="0"
      cellspacing="0"
      cellpadding="0"
    >
      <tr v-for="(row, rowIndex) in element.rows" :key="rowIndex">
        <td
          v-for="(col, colIndex) in row.cols"
          :key="colIndex"
          :style="{width: getTdWidth(row.cols, col)}"
          :colspan="col.colspan"
        >
          <draggable
            v-model="col.list"
            :no-transition-on-drag="true"
            v-bind="{
              group: 'form',
              ghostClass: 'ghost',
              animation: 200,
              handle: '.drag-widget'
            }"
            @start="handleMoveStart"
            @add="handleWidgetColAdd($event, element, rowIndex, colIndex)"
          >
            <transition-group name="fade" tag="div" class="widget-col-list">
              <widget-form-item
                v-for="(el, i) in col.list.filter(c => c.key)"
                :key="el.key"
                :element="el"
                :select="selectWidgetItem"
                :selectWidgetList.sync="selectWidgetList"
                :index="i"
                :data.sync="col"
              ></widget-form-item>
            </transition-group>
          </draggable>
        </td>
      </tr>
    </table>
  </div>
</template>
<script>
import {mapState, mapMutations} from 'vuex'
import Draggable from 'vuedraggable'
import WidgetFormItem from '@/components/form/WidgetFormItem.vue'
import controlsApi from '@/api/controlsConfig.js'
import deepmerge from 'deepmerge'
import updateSelectControl from '@/mixins/updateSelectControl.js'
export default {
  name: 'widget-main-table-layout',
  components: {Draggable, WidgetFormItem},
  props: ['element', 'index', 'data', 'selectWidgetList'],
  mixins: [updateSelectControl],
  data() {
    return {}
  },
  computed: {
    ...mapState('form', ['selectWidget'])
  },
  methods: {
    ...mapMutations({
      setSelectWidget: 'form/setSelectWidget' // 设置当前选中控件
    }),
    handleMoveStart: function(evt) {
      // 新增控件时  将控件属性切断联系
      evt.item._underlying_vm_ = deepmerge({}, evt.item._underlying_vm_, {
        clone: true
      })
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      evt.item._underlying_vm_.key = key

      evt.item._data_vm_=deepmerge({}, this.data.list, {
        clone: true
      })
      evt.item._p_vm_=this.data
    },
    getTdWidth(cols, col) {
      let colspans = 0
      cols.forEach(item => {
        colspans += item.colspan
      })
      return (100 / colspans) * col.colspan + '%'
    },
    handleSelectWidget(index) {
      this.setSelectWidget(this.data.list[index])
    },
    handleAddBack($event, column, newIndex){
      column.list.splice(newIndex, 1)
      if($event.item._p_vm_){
        $event.item._p_vm_.list=$event.item._data_vm_
      }
    },
    handleWidgetColAdd($event, row, rowIndex, colIndex) {
      const newIndex = $event.newIndex
      const oldIndex = $event.oldIndex
      const item = $event.item
      if (item.innerText == '高德地图') {
        this.handleAddBack($event, row.rows[rowIndex]['cols'][colIndex], newIndex)
        this.$message.warning('表格布局中不允许拖入高德地图')
        return false
      }
      //表格布局一个td中只允许拖入一个控件
      if (
        row.rows[rowIndex]['cols'][colIndex].list &&
        row.rows[rowIndex]['cols'][colIndex].list.length > 1
      ) {
        this.handleAddBack($event, row.rows[rowIndex]['cols'][colIndex], newIndex)
        this.$message.warning('表格布局中每个单元格最多只允许拖入一个控件。')
        return false
      }
      console.log(item, 'item.ctrlType')
      if (item.innerText == 'DIY组件') {
        this.handleAddBack($event, row.rows[rowIndex]['cols'][colIndex], newIndex)
        this.$message.warning('表格布局不支持DIY组件')

        return false
      }
      // 防止布局元素的嵌套拖拽
      if (
        item.className.indexOf('data-grid') >= 0 ||
        item.innerText == '分页符'
      ) {
        // 如果是列表中拖拽的元素需要还原到原来位置
        item.tagName === 'DIV' &&
          this.data.list.splice(
            oldIndex,
            0,
            row.rows[rowIndex]['cols'][colIndex].list[newIndex]
          )
          this.handleAddBack($event, row.rows[rowIndex]['cols'][colIndex], newIndex)
        if (item.innerText == '分页符') {
          this.$message.warning('表格布局中不允许再拖入分页布局')
        }
        return false
      }
      if(!controlsApi.handleLayoutComponents(
        this,
        row,
        row.rows[rowIndex]['cols'][colIndex].list,
        newIndex
      )){
        this.handleAddBack($event, row.rows[rowIndex]['cols'][colIndex], newIndex)
        return false
      }
      if (row.rows[rowIndex].cols[colIndex].list[newIndex]) {
        let params = row.rows[rowIndex].cols[colIndex].list[newIndex]
        params.parentNodeType = row.parentNodeType
        params.boSubEntity = row.boSubEntity
        this.setSelectWidget(params)
      }
    },
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.setSelectWidget({options: {validateType: ''}})
        } else {
          this.setSelectWidget(this.data.list[index - 1])
        }
      } else {
        this.setSelectWidget(this.data.list[index + 1])
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1)
      })
    },
    handleWidgetClone(index) {
      let cloneData = deepmerge({}, this.data.list[index], {clone: true})

      cloneData.key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      cloneData.columns.forEach(v => {
        v.list = []
      })
      this.data.list.splice(index + 1, 0, cloneData)

      this.$nextTick(() => {
        this.setSelectWidget(this.data.list[index + 1])
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/form-editor.scss';

.widget-col {
  padding-bottom: 0;
  padding: 15px 5px;
}

.active {
  outline: 2px solid $--form-design-active-color;
}

.el-col {
  min-height: 50px;
}

.widget-col-list {
  min-height: 50px;
  border: 1px solid #ededed;
  width: 100%;
}

div.widget-view-action {
  .del-icon {
    width: 20px;
    margin-left: 12px;
  }
}

div.widget-view-action i.icon-trash {
  margin: 0 10px;
}
</style>
