<template>
  <div
    @click.stop="handleSelectWidget(index)"
    class="widget-subtable"
    :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>
    <div style="overflow-x: auto; overflow-y: hidden; padding: 15px">
      <div
        v-if="element.options.showLabel"
        style="font-weight: bold; padding: 10px"
      >
        {{ element.desc_zh || element.desc }}
      </div>
      <table
        class="el-form--label-top"
        style="padding-bottom: 10px; width: 100%"
      >
        <draggable
          v-model="element.list"
          :no-transition-on-drag="true"
          v-bind="{
            group: 'form',
            ghostClass: 'ghost',
            animation: 200,
            handle: '.drag-widget'
          }"
          @start="handleMoveStart"
          @add="handleWidgetColAdd($event, element)"
        >
          <transition-group name="fade" tag="div" class="widget-col-list">
            <div
              class="subtable-item__div"
              v-for="(child, i) in element.list.filter(c => c.key)"
              :key="child.key"
              :class="{active: selectWidgetItem.key == child.key}"
            >
              <widget-suntable-layout
                v-if="child.ctrlType == 'suntable'"
                :key="child.key"
                :data.sync="element"
                :selectWidgetList.sync="selectWidgetList"
                :index="i"
                :select="selectWidgetItem"
                :element.sync="child"
              />

              <widget-sundiv-layout
                v-else-if="child.ctrlType == 'sunDiv'"
                :key="child.key"
                :data.sync="element"
                :select="selectWidget"
                :selectWidgetList.sync="selectWidgetList"
                :index="i"
                :element.sync="child"
              />

              <widget-form-item
                v-else
                :key="child.key"
                :element="child"
                :select="selectWidgetItem"
                :index="i"
                :selectWidgetList.sync="selectWidgetList"
                :data.sync="element"
                style="width: 100%"
              />
              <template v-for="item of element.CombinedColumnList">
                <div v-if="child.name == item.columnField" class="Combined">
                  {{ getSummaries(child.options.defaultValue, item) }}
                </div>
              </template>
            </div>
          </transition-group>
        </draggable>
      </table>
    </div>
  </div>
</template>
<script>
import utils from '@/hotent-ui-util.js'
import {mapState, mapMutations} from 'vuex'
import Draggable from 'vuedraggable'
import WidgetFormItem from '@/components/form/WidgetFormItem.vue'
import WidgetSuntableLayout from '@/components/form/WidgetSuntableLayout.vue'
import WidgetSundivLayout from '@/components/form/WidgetSunDivLayout.vue'
import controlsApi from '@/api/controlsConfig.js'
import deepmerge from 'deepmerge'
import updateSelectControl from '@/mixins/updateSelectControl.js'
export default {
  name: 'widget-subtable-layout',
  components: {
    Draggable,
    WidgetFormItem,
    WidgetSuntableLayout,
    WidgetSundivLayout
  },
  mixins: [updateSelectControl],
  props: ['element', 'select', 'index', 'data', 'selectWidgetList'],
  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
    },
    handleSelectWidget(index) {
      this.setSelectWidget(this.data.list[index])
    },
    handleAddBack($event, element, newIndex) {
      element.list.splice(newIndex, 1)
      if ($event.item._p_vm_) {
        $event.item._p_vm_.list = $event.item._data_vm_
      }
    },
    handleWidgetColAdd($event, element) {
      const newIndex = $event.newIndex
      const oldIndex = $event.oldIndex
      const item = $event.item._underlying_vm_
      const pathLength =
        item && item.fieldPath && item.fieldPath.split('.').length
      if (pathLength == 2 && !item.fieldPath.startsWith('item')) {
        this.$message.warning('子表中不允许拖入主表字段')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType == 'QRcode') {
        this.$message.warning('子表不允许存在二维码')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType == 'milepost') {
        this.$message.warning('子表不允许存在里程碑')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'customChart') {
        this.$message.warning('子表不允许存在图表')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType == 'table') {
        this.$message.warning('子表不允许存在表格布局')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType == 'processForecast') {
        this.$message.warning('子表不允许存在审批预测')
        this.handleAddBack($event, element, newIndex)
        return false
      }

      if (['amap','tianditu'].includes(item.ctrlType)) {
        this.$message.warning('子表不允许存在地图')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType == 'related-process') {
        this.$message.warning('子表不允许存在相关流程')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'dataView') {
        this.$message.warning('子表不允许存在数据列表')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'formTable') {
        this.$message.warning('子表不允许存在表单列表')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'divider') {
        this.$message.warning('子表不允许存在分割线')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'signature') {
        this.$message.warning('子表不允许存在签章')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'handSignature') {
        this.$message.warning('子表不允许存在手动签章')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'htCustomComponent') {
        this.$message.warning('子表不允许存在DIY组件')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (item.ctrlType === 'opinion') {
        this.$message.warning('子表不允许存在审批意见组件')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      // 拖动时禁止孙表拖动至子表
      if (this.isSunItem(newIndex, element)) {
        this.$message.warning('子表中不允许拖入孙表字段')
        this.handleAddBack($event, element, newIndex)
        return false
      }

      if (
        !controlsApi.handleLayoutComponents(
          this,
          element,
          element.list,
          newIndex
        )
      ) {
        this.handleAddBack($event, element, newIndex)
        return false
      }
      if (!element.options.boSubEntity) {
        this.$message.warning('请先绑定子表')
        this.handleAddBack($event, element, newIndex)
        return false
      }
      // 防止布局元素的嵌套拖拽
      if ($event.item.isLayout) {
        element.list.list && element.list.list.splice(newIndex, 1)
        return false
      }
      let params = element.list[newIndex]
      params.parentNodeType = 'sub'
      params.boSubEntity = element.options.boSubEntity
      this.setSelectWidget(params)
    },
    // 判断是否孙表拖动过来的字段
    isSunItem(newIndex, element) {
      let obj = element.list[newIndex]
      if (obj.fieldPath) {
        if (obj.fieldPath.split('.').length >= 4) {
          return true
        }
      }
      return false
    },
    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)
      })
    },
    //合计计算
    getSummaries(param = 0, item) {
      let listChange = [item]

      let values = [_.cloneDeep(param)]

      let {addFunc, columnField, name, unit, showType,num} = item
      // const values = data.map(item => Number(item[column.property]))
      var sums = 0
      let units = unit ? unit : ''
      //求和
      if (addFunc === 'add') {
        if (!values.every(value => isNaN(value))) {
          sums = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums = name + ': ' + this.dealWithData(sums, showType, num) + units
        } else {
          sums = ''
        }
      }
      //计数
      if (addFunc === 'count') {
        sums = name + ': ' + this.dealWithData(values.length, showType, num) + units
      }
      //平均值
      if (addFunc === 'average') {
        let sum = 0
        var average = 0
        for (var i = 0; i < values.length; i++) {
          sum += values[i]
        }
        average = sum / values.length

        sums = name + ': ' + this.dealWithData(average, showType, num) + units
      }
      //最大值
      if (addFunc === 'max') {
        let maxNum = Math.max.apply(null, values)
        sums = name + ': ' + this.dealWithData(maxNum, showType, num) + units
      }
      //最小值
      if (addFunc === 'min') {
        let minNum = Math.min.apply(null, values)
        sums = name + ': ' + this.dealWithData(minNum, showType, num) + units
      }

      return sums
    },
    //处理数据
    dealWithData(data, showType, numfix = 0) {
      data=Number(data)
      let list = showType 
      let num = 0
      // 保留小数位
      if (list.includes('keepSmall')) {
        num = data.toFixed(numfix)
      }

      //百分比
      if (list.includes('percentage')) {
        num = Number(data * 100) + '%'
      }
      // 千分位
      if (list.includes('Micrometer')) {
        num = utils.thousandBit(data)
      }
      if (
        list.includes('keepSmall') &&
        list.includes('percentage') &&
        list.includes('Micrometer')
      ) {
        return (num = utils.thousandBit(Number(data * 100).toFixed(numfix)) + '%')
      }
      if (list.includes('keepSmall') && list.includes('percentage')) {
        return (num = Number(data * 100).toFixed(numfix) + '%')
      }
      if (list.includes('Micrometer') && list.includes('percentage')) {
        return (num = utils.thousandBit(Number(data * 100)) + '%')
      }
      if (list.includes('keepSmall') && list.includes('Micrometer')) {
        num = utils.thousandBit(data.toFixed(numfix))
      }

      return num
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/form-editor.scss';

.widget-subtable {
  margin: 30px;
  padding-bottom: 0;
  padding: 10px 5px;
  position: relative;
  ::v-deep .el-radio-group,
  ::v-deep .el-checkbox-group {
    text-align: left;
  }
}

.widget-subtable.active {
  outline: 2px solid $--form-design-active-color !important;
}

.widget-subtable:hover {
  outline: 1px dashed #ccc;
}

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

.widget-col-list {
  min-height: 50px;
  outline: 1px solid #ededed;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.widget-col-list .widget-form-item {
  margin: 0;
  outline: 1px solid #ededed;
  height: 100%;
}

.widget-col-list > .subtable-item__div {
  width: 100%;
  position: relative;
  .Combined {
    text-align: center;
    position: absolute;
    margin: 0 auto;
    left: 0;
    right: 0;

    bottom: 14px;
  }
}

>>> .ht-form-item {
  text-align: center;
  padding: 0;
  margin: 0;
}

>>> .el-form-item__label {
  font-weight: bold;
  min-width: 120px;
  padding: 0;
  text-align: center;
}

>>> .el-form-item__label:after {
  visibility: hidden;
}

>>> .el-form-item__content {
  border-top: 1px solid #ededed;
  padding: 10px;
  height: 50px;
  margin-left: 0px !important;
}
</style>
