<template>
  <template v-if="mode === 'DESIGN'">
    <draggable class="l-drag-from" :list="_items" group="form"
               :options="{animation: 300, chosenClass:'choose', sort:true}"
               @start="spanLayoutStart" @end="drag = false">
      <template #item="{ element, index }">
      <div class="l-form-item" @click.stop="selectItem(element)"
           :style="getSelectedClass(element)">
        <div class="l-form-header">
          <p><span v-if="element.props.required">*</span>{{ element.title }}</p>
          <div class="l-option">
            <!--<i class="el-icon-copy-document" @click="copy"></i>-->
            <i class="el-icon-close" @click="delItem(index)"></i>
          </div>
          <form-design-render :config="element"/>
        </div>
      </div>
      </template>
    </draggable>
    <div style="color: #c0bebe;text-align: center; width: 90%; padding: 5px;">☝ 拖拽控件到布局容器内部</div>
  </template>
  <template v-else>
    <el-row :gutter="20" v-for="(rows, rsi) in __items" :key="rsi + '_rows'">
      <el-col :span="24 / rows.length" v-for="(item, ri) in rows" :key="ri + '_row'">
        <el-form-item v-if="item.name !== 'SpanLayout' && item.name !== 'Description'" :prop="item.id"
                      :label="item.title" :key="item.name + ri">
          <form-design-render v-model:value="_value[item.id]" :perm="item.perm" :mode="mode" :config="item"/>
        </el-form-item>
        <form-design-render v-else v-model:value="_value" :perm="item.perm" :mode="mode" :config="item"/>
      </el-col>
    </el-row>

  </template>
</template>

<script setup>
import draggable from "vuedraggable";
import FormDesignRender from '../FormDesignRender.vue'
import {useProcessStore} from '@/stores/processStore.js'
import {ElMessage, ElMessageBox} from "element-plus";

const processStore = useProcessStore()
import {defineProps, defineEmits, computed} from 'vue'

const emit = defineEmits()

const props = defineProps({
  mode: {
    type: String,
    default: 'DESIGN'
  },
  required: {
    type: Boolean,
    default: false
  },
  value: {
    default: null
  },
  items: {
    type: Array,
    default: () => {
      return []
    }
  }
})

const select = ref();
const drag = ref(false);
const formConfig = ref({
  //数据字段
  data: {},
  //校验规则
  rules: {}
});
const form = ref({
  processDefinitionKey: '',
  deploymentName: "",
  logo: {},
  formItems: [],
  process: {},
  remark: ""
});

const _value = computed({
  get() {
    return props.value;
  },
  set(value) {
    emit('update:value', value)
  }
})
watch(() => props.value, (value) => {
  _value.value = value
})

const _items = computed({
  get() {
    return props.items;
  },
  set(value) {
    emit('update:value', value)
  }
})
watch(() => props.items, (value) => {
  _items.value = value
})

const __items = computed(() => {
  let result = []
  for (let i = 0; i < props.items.length; i++) {
    if (i > 0 && i % 2 > 0) {
      result.push([props.items[i - 1], props.items[i]])
    }
  }
  if (result.length * 2 < props.items.length) {
    result.push([props.items[props.items.length - 1]])
  }
  return result
})


const selectFormItem = computed({
  get() {
    return processStore.getSelectedFormItem()
  },
  set(val) {
    processStore.setSelectedFormItem(val)
  },
})

const spanLayoutStart = () => {
  drag.value = true;
  selectFormItem.value = null
}
const selectItem = (cp) => {
  selectFormItem.value = cp
}
const getSelectedClass = (cp) => {
  return processStore.getSelectedFormItem() && processStore.getSelectedFormItem().id === cp.id ?
      'border-left: 4px solid #f56c6c' : ''
}

const delItem = (index) => {
  ElMessageBox.confirm('删除组件将会连带删除包含该组件的条件以及相关设置，是否继续?', '提示', {
    confirmButtonText: '确 定',
    cancelButtonText: '取 消',
    type: 'warning'
  }).then(() => {
    if (_items.value[index].name === 'SpanLayout') {
      //删除的是分栏则遍历删除分栏内所有子组件
      _items.value[index].props.items.forEach(item => {
        removeFormItemAbout(item)
      })
      _items.value[index].props.items.length = 0
    } else {
      removeFormItemAbout(_items[index])
    }
    _items.value.splice(index, 1)
  })
}
const removeFormItemAbout = async (item) => {
  processStore.nodeMap.forEach(node => {
    //搜寻条件，进行移除
    if (node.type === 'CONDITION') {
      node.props.groups.forEach(group => {
        let i = group.cids.remove(item.id)
        if (i > -1) {
          //从子条件移除
          group.conditions.splice(i, 1)
        }
      })
    }
    //搜寻权限，进行移除
    if (node.type === 'ROOT' || node.type === 'APPROVAL' || node.type === 'CC') {
      node.props.formPerms.removeByKey('id', item.id)
    }
  })
}
</script>

<style lang="scss" scoped>


.choose {
  border: 1px dashed #1890FF !important;
}

.l-drag-from {
  min-height: 50px;
  background-color: rgb(245, 246, 246);

  .l-form-item, li {
    cursor: grab;
    background: #ffffff;
    padding: 10px;
    border: 1px solid #ebecee;
    margin: 5px 0;
  }
}

.l-form-header {
  font-size: small;
  color: #818181;
  text-align: left;
  position: relative;
  background-color: #fff;

  p {
    position: relative;
    margin: 0 0 10px 0;

    span {
      position: absolute;
      left: -8px;
      top: 3px;
      color: rgb(217, 0, 19);
    }
  }

  .l-option {
    position: absolute;
    top: -10px;
    right: -10px;

    i {
      font-size: large;
      cursor: pointer;
      color: #8c8c8c;
      padding: 5px;

      &:hover {
        color: #1890FF;
      }
    }
  }
}

</style>
