<template>
  <div class="widget-form-container"
    :class="`${platform}`"
  >
    <el-form
      :size="formSize"
      :label-position="data.config.labelPosition"
      :label-width="data.config.labelWidth + 'px'"
      :class="{
        [data.config && data.config.customClass]:  (data.config && data.config.customClass) ? true : false,
      }"
      :style="{width: data.config.width, margin: 'auto'}"
      :label-suffix="data.config?.labelSuffix ? ' : ' : ' '"
    >
      <div v-if="data.list.length == 0" class="form-empty">{{$t('fm.description.containerEmpty')}}</div>

      <el-scrollbar style="overflow: hidden;" wrap-class="widget-form-wrapper">
        <draggable class="widget-form-draggable"
          v-model="data.list"
          v-bind="{group:'people', ghostClass: 'ghost',animation: 200, handle: '.drag-widget'}"
          @add="handleWidgetAdd"
          @update="handleWidgetUpdate"
          @start="handleMoveStart"
          @end="handleMoveEnd"
        >

          <transition-group name="fade" tag="div" class="widget-form-list" >

            <template v-for="(element, index) in data.list" v-if="element && element.key">
              <widget-table
                v-if="element.type === 'table'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-table>

              <widget-tab-item
                v-else-if="element.type === 'tabs'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-tab-item>

              <widget-collapse
                v-else-if="element.type === 'collapse'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index"
                :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-collapse>

              <widget-report
                v-else-if="element.type === 'report'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-report>

              <widget-inline
                v-else-if="element.type === 'inline'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-inline>

              <widget-sub-form
                v-else-if="element.type === 'subform'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index"
                :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-sub-form>

              <widget-group
                v-else-if="element.type === 'group'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index"
                :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-group>

              <widget-card
                v-else-if="element.type === 'card'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index"
                :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-card>

              <widget-dialog
                v-else-if="element.type === 'dialog'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index"
                :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-dialog>

              <widget-form-item
                v-else-if="element.type !== 'grid'"
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :form-key="formKey"
              >
              </widget-form-item>

              <widget-col-item
                v-else
                :key="element.key"
                :element="element"
                :select.sync="selectWidget"
                :index="index" :data="data"
                @select-change="handleSelectChange"
                :platform="platform"
                :form-key="formKey"
              >
              </widget-col-item>
            </template>
          </transition-group>

        </draggable>
      </el-scrollbar>
    </el-form>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import WidgetFormItem from './WidgetFormItem'
import WidgetColItem from './WidgetColItem'
import WidgetTable from './WidgetTable'
import WidgetTabItem from './WidgetTabItem'
import WidgetReport from './WidgetReport'
import WidgetInline from './WidgetInline'
import WidgetSubForm from './WidgetSubForm.vue'
import WidgetCollapse from './WidgetCollapse.vue'
import WidgetDialog from './WidgetDialog.vue'
import WidgetCard from './WidgetCard.vue'
import WidgetGroup from './WidgetGroup.vue'
import { EventBus } from '../util/event-bus.js'
import { generateKeyToTD, generateKeyToTH, generateKeyToCol } from '../util'
import _ from 'lodash'
import { Message } from 'element-ui'

export default {
  components: {
    Draggable,
    WidgetFormItem,
    WidgetColItem,
    WidgetTable,
    WidgetTabItem,
    WidgetReport,
    WidgetInline,
    WidgetSubForm,
    WidgetCollapse,
    WidgetDialog,
    WidgetCard,
    WidgetGroup
  },
  props: ['data', 'select', 'platform', 'formKey'],
  inject: ['changeConfigTab', 'setDragging'],
  data () {
    return {
      selectWidget: this.select || {}
    }
  },
  computed: {
    formSize () {
      switch (this.data.config.size){
        case 'large': return 'large'
        case 'default': return 'small'
        case 'small': return 'mini'
        default: return 'small'
      }
    }
  },
  mounted () {
    document.body.ondrop = function (event) {
      let isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
      if (isFirefox) {
        event.preventDefault()
        event.stopPropagation()
      }
    }

    EventBus.$on('on-field-add-' + this.formKey, item => {
      console.log('.....')
      console.log(item, this.data, this.select)

      const key = Math.random().toString(36).slice(-8)
      let widgetItem = _.cloneDeep({
        ...item,
        options: {
          ...item.options,
          remoteFunc: 'func_' + key,
          remoteOption: 'option_' + key
        },
        key,
        model: item.type + '_' + key,
        rules: []
      })

      if (widgetItem.type == 'report') {
        widgetItem.rows = generateKeyToTD(widgetItem.rows)
        widgetItem.headerRow = generateKeyToTH(widgetItem.headerRow)
      }

      if (widgetItem.type == 'grid') {
        widgetItem.columns = generateKeyToCol(widgetItem.columns)
      }

      widgetItem.options.subform = this.selectWidget?.options?.subform
      widgetItem.options.tableColumn = this.selectWidget?.options?.tableColumn

      this._addWidget(this.data.list, widgetItem)
    })
  },
  beforeDestroy () {
    EventBus.$off('on-field-add-' + this.formKey)
  },
  methods: {
    _addWidget (list, widget, isTable = false) {
      console.log(list,'=====');
      if (isTable
        && (widget.type == 'subform'
          || widget.type == 'grid'
          || widget.type == 'table'
          || widget.type == 'tabs'
          || widget.type == 'collapse'
          || widget.type == 'divider'
          || widget.type == 'report'
          || widget.type == 'inline'
          || widget.type == 'dialog'
          || widget.type == 'card'
        )) {
        Message.warning(this.$t('fm.message.noPut'))
        return 'table'
      }

      if (this.selectWidget && this.selectWidget.key) {
        const index = list.findIndex(item => item.key == this.selectWidget.key)

        if (index >= 0) {
          list.splice(index + 1, 0, widget)

          this.selectWidget = list[index + 1]

          setTimeout(() => {
            this.scrollTo()
          }, 200)

          this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
        } else {
          for (let l = 0; l < list.length; l++) {
            let item = list[l]

            if (item.type === 'grid') {
              item.columns.forEach(column => {
                this._addWidget(column.list, widget)
              })
            }
            if (item.type === 'table') {
              if ('table' == this._addWidget(item.tableColumns, widget, true)) {
                return 'table'
              }
            }
            if (item.type === 'subform') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }
            if (item.type === 'tabs') {
              item.tabs.forEach(tab => {
                this._addWidget(tab.list, widget)
              })
            }
            if (item.type === 'collapse') {
              item.tabs.forEach(tab => {
                this._addWidget(tab.list, widget)
              })
            }
            if (item.type === 'report') {

              for (let i = 0; i < item.rows.length; i++) {
                for (let j = 0; j < item.rows[i].columns.length; j++) {
                  widget.options.hideLabel = true
                  if ('table' == this._addWidget(item.rows[i].columns[j].list, widget, false)){
                    return 'table'
                  }
                }
              }
            }
            if (item.type === 'inline') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }
            if (item.type === 'dialog') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }

            if (item.type === 'card') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }

            if (item.type === 'group') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }
            if (item.type === '"takeLeaveDate"') {
              if ('table' == this._addWidget(item.list, widget, true)) {
                return 'table'
              }
            }
          }
        }
      } else {
        list.push(widget)

        this.selectWidget = list[list.length - 1]

        setTimeout(() => {
          this.scrollTo()
        }, 200)

        this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
      }
    },
    handleMoveStart () {
      this.setDragging(true)
    },
    handleMoveEnd () {
      this.setDragging(false)
    },
    handleWidgetUpdate (evt) {
      this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
    },
    handleWidgetAdd (evt) {

      const newIndex = evt.newIndex
      const to = evt.to

      this.$set(this.data.list, newIndex, _.cloneDeep(this.data.list[newIndex]))

      //为拖拽到容器的元素添加唯一 key
      const key = Math.random().toString(36).slice(-8)
      this.$set(this.data.list, newIndex, {
        ...this.data.list[newIndex],
        options: {
          ...this.data.list[newIndex].options,
          remoteFunc: this.data.list[newIndex].options.remoteFunc || 'func_' + key,
          remoteOption: this.data.list[newIndex].options.remoteOption || 'option_' + key,
          tableColumn: false,
          subform: false
        },
        key: this.data.list[newIndex].key ? this.data.list[newIndex].key : key,
        // 绑定键值
        model: this.data.list[newIndex].model ? this.data.list[newIndex].model : this.data.list[newIndex].type + '_' + key,
        rules: this.data.list[newIndex].rules ? [...this.data.list[newIndex].rules] : []
      })

      if (this.data.list[newIndex].type == 'report') {
        this.data.list[newIndex].rows = generateKeyToTD(this.data.list[newIndex].rows)
        this.data.list[newIndex].headerRow = generateKeyToTH(this.data.list[newIndex].headerRow)
      }

      if (this.data.list[newIndex].type == 'grid') {
        this.data.list[newIndex].columns = generateKeyToCol(this.data.list[newIndex].columns)
      }

      this.selectWidget = this.data.list[newIndex]

      this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
    },
    handleWidgetDelete (index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {}
        } else {
          this.selectWidget = this.data.list[index - 1]
        }
      } else {
        this.selectWidget = this.data.list[index + 1]
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1)

        this.$nextTick(() => {         EventBus.$emit('on-history-add-' + this.formKey)       })
      })
    },
    handleSelectChange (index) {
      console.log('select-change', index)
      setTimeout(() => {
        index >=0 ? (this.selectWidget = this.data.list[index]) : (this.selectWidget = {})
      })
    },
    scrollTo () {
      let activeTop = document.querySelector('.widget-form-container .active').getBoundingClientRect().top

      let activeHeight = document.querySelector('.widget-form-container .active').offsetHeight

      let containerHeight = document.querySelector('.widget-form-container').offsetHeight

      let containerTop = document.querySelector('.widget-form-container').getBoundingClientRect().top

      let scorllTop = document.querySelector('.widget-form-container .widget-form-wrapper').getBoundingClientRect().top

      let y = activeTop - scorllTop

      let top = scorllTop - containerTop

      if ( y + activeHeight  > -top + containerHeight || y  < -top ) {
        document.querySelector('.widget-form-wrapper').scrollTop = y - 5
      }
    }

  },
  watch: {
    select (val) {
      this.selectWidget = val
      if (Object.keys(val).length) {
        this.changeConfigTab('widget')
      } else {
        this.changeConfigTab('form')
      }
    },
    selectWidget: {
      handler (val) {
        this.$emit('update:select', val)
      },
      deep: false
    }
  }
}
</script>

<style lang="scss">
// .fade-enter-active, .fade-leave-active {
//   transition: opacity .3s;
// }
// .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
//   opacity: 0;
// }
</style>
