<template>
  <div class="flow-drag-container">
    <el-splitter>
      <el-splitter-panel size="30%" class="el-splitter-panel">
        <div class="panel-container">
          <div class="header">组件库</div>
          <div class="left-panel">
            <div class="component-container" v-if="leftActiveName === 'component'">
              <template v-if="!isScript">
                <!-- <div class="components-title">
                    通用组件
                  </div> -->
                <draggable
                  class="components-draggable"
                  :list="selectComponents"
                  ghost-class="ghost"
                  :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                  :clone="cloneComponent"
                  :sort="false"
                  itemKey="id"
                  animation="300"
                  @end="onEnd"
                >
                  <template #item="{ element }">
                    <div class="components-body">
                      <!-- <img class="mr4" width="14" :src="getImage(element.tag as any) " alt="" /> -->
                      <span>{{ element.label }}</span>
                    </div>
                  </template>
                </draggable>
              </template>

              <!-- <div class="components-title">
                <img class="mr5" width="14" src="@/assets/img/form/puzzle.png" />特殊组件
              </div>

              <draggable
                class="components-draggable"
                :list="inputComponentsData"
                ghost-class="ghost"
                :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                :clone="cloneComponent"
                :sort="false"
                item-key="id"
                animation="300"
                @end="onEnd"
              >
                <template #item="{ element }">
                  <div class="components-body move">
                    {{ element.label }}
                  </div>
                </template>
              </draggable> -->
              <!-- <template v-if="!isScript">
                <div class="components-title">
                  模板组件
                </div>
                <draggable
                  class="components-draggable"
                  :list="templateList"
                  ghost-class="ghost"
                  :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                  :clone="cloneTemplateComponent"
                  :sort="false"
                  animation="300"
                  @end="onTemplateEnd"
                >
                  <template #item="{ element }">
                    <div class="components-body">
                      {{ element.label }}
                    </div>
                  </template>
                </draggable>
              </template> -->
            </div>
            <div class="template-container" v-if="leftActiveName === 'template'"></div>
          </div>
        </div>
      </el-splitter-panel>
      <el-splitter-panel :min="200">
        <div class="panel-container">
          <div class="center-panel">
            <!-- <div class="center-panel-head"> -->
            <!-- <el-radio-group v-model="saveType">
                <el-radio value="1">配置节点</el-radio>
                <el-radio value="2">配置模板</el-radio>
              </el-radio-group> -->

            <!-- <el-button @click="clearDrawingList">清空</el-button>
              <el-button @click="addTemplate" v-if="type === '2'">新增模板</el-button>
              <el-button type="danger" v-if="type === '2'" @click="deleteTemplate">删除模板</el-button>
              <el-button @click="setTemplate" v-if="type === '1'">配置模板</el-button>
              <el-button v-if="!isScript" @click="previewForm">预览 </el-button>
              <el-button type="primary" @click="saveTemplate">保存</el-button> -->
            <!-- </div> -->
            <div class="center-panel-content">
              <div class="center-board-row">
                <el-form
                  :label-position="formConf.labelPosition"
                  :disabled="formConf.disabled"
                  :label-width="formConf.labelWidth + 'px'"
                >
                  <draggable
                    :key="draggableKey"
                    class="drawing-board"
                    :list="drawingList"
                    ghost-class="ghost"
                    group="componentsGroup"
                    animation="300"
                    itemKey="id"
                    @start="onStart"
                    @end="onEnd"
                  >
                    <template #item="{ element }">
                      <draggable-item
                        class="center-drag-item"
                        :key="element.renderKey"
                        :drawingList="drawingList"
                        :element="element"
                        :activeId="activeId"
                        :formConf="formConf"
                        @activeItem="activeFormItem"
                        @editItem="drawingItemEdit"
                        @deleteItem="drawingItemDelete"
                        @endDraggable="onEnd"
                      />
                    </template>
                  </draggable>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </el-splitter-panel>
    </el-splitter>

    <!-- <Teleport to="body">
      <vxe-modal width="70%" height="70%" v-model="previewFormVisible" destroy-on-close title="预览" show-zoom resize>
        <template #default>
          <div style="width: 100%; height: 100%">
            <PreviewForm :formConfigData="drawingList"></PreviewForm>
          </div>
        </template>
      </vxe-modal>
    </Teleport> -->
    <!-- <properties-review
      v-if="previewFormVisible"
      :attributeList="previewData"
      @closeWindow="previewFormVisible = false"
    ></properties-review> -->
    <right-panel
      v-model:showDialog="showEditDialog"
      v-model:active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      @tagChange="tagChange"
      @updateActiveData="updateActiveData"
    ></right-panel>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, provide } from 'vue';
import Draggable from 'vuedraggable';
import DraggableItem from './DraggableItem.vue';
import RightPanel from './RightPanel.vue';
// import propertiesReview from '@/views/pages/flowCreate/components/properties/propertiesReview.vue';
// import { ElMessageBox, ElMessage } from 'element-plus';
import { selectComponents, formConf } from './formConfig';
import { cloneDeep } from 'lodash';
import { queryApplicationConfigApi } from '@/api/system/application';

// import { WIDGET_IDS } from '@/views/pages/flowCreate/components/enum';
// 1是节点配置，2是模板配置
const props = withDefaults(
  defineProps<{
    // type: string;
    // templateSettingInfo?: any;
    nodeAttribute: any;
  }>(),
  {
    // type: '1',
    // templateSettingInfo: [],
    nodeAttribute: {},
  }
);

// const emits = defineEmits([
//   'showAddTemplate',
//   'saveTemplate',
//   'deleteTemplate',
//   'templateSettingClose',
//   'saveNodeData',
// ]);
// const drawingList = ref([props.nodeAttribute.pageConfigList]);

const getAppConfigListFun = async (uuid: any, name: any) => {
  if (!uuid) {
    return [];
  }
  try {
    const res: any = await queryApplicationConfigApi({
      appId: uuid,
    });
    if (res && res.code === 200) {
      let list: any = [];
      if (name) {
        const data = res.data.find((item: any) => {
          return item.configName === name;
        })?.configValue;

        list = data ? JSON.parse(data) : [];
        return list;
      } else {
        return list;
      }
    } else {
      return [];
    }
  } catch {
    return [];
  }
};

const drawingList = ref(props.nodeAttribute.pageConfigList);
watch(
  () => props.nodeAttribute,
  async (val) => {
    drawingList.value = val.pageConfigList;

    if (!drawingList.value?.length) {
      drawingList.value = await getAppConfigListFun(
        props.nodeAttribute?.uuid,
        props.nodeAttribute?.nodeParamConfigName
      );
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
// const drawingList = computed(() => {
//   return [];
//   // return props.nodeAttribute.drawingList;
// })
// const { userTemplateFile, userTemplatePath } = inject<any>('userTemplateFileAndPath');
// const inputComponentsData = computed(() => {
//   const inputComponentsClone = cloneDeep(inputComponents);
//   let data = inputComponentsClone;
//   if (isScript.value) {
//     data = inputComponentsClone.filter((item: any) => {
//       return item.englishLabel === 'script';
//     });
//   } else {
//     data = inputComponentsClone.filter((item: any) => {
//       return item.englishLabel !== 'script';
//     });
//   }
//   return data;
// });
const leftActiveName = ref('component');
const draggableKey = ref<any>(new Date().getTime());

// 1更新当前，2配置模板
// const saveType = ref<string>('1');
// const formatDrawingList = (arr: any) => {
//   arr.forEach((item: any) => {
//     if (item.isTemplateRoot && item.children?.length) {
//       formatDrawingList(item.children);
//     } else if (item.children?.length && (!item.layoutType || item.layoutType === '1')) {
//       item.children.forEach((item_1: any, index_1: any) => {
//         item_1.isSpecialBox = index_1 === 0;
//         if (!item_1.oldLabel) {
//           item_1.oldLabel = item_1.label;
//         }
//         if (index_1 === 0) {
//           item_1.label = '行容器类型';
//         } else {
//           item_1.label = item_1.oldLabel;
//         }
//       });
//       formatDrawingList(item.children);
//     }
//   });
// };
// const hiddenTemplateRoot = (arr: any) => {
//   const arrClone = cloneDeep(arr);
//   arr.forEach((item: any, index: any) => {
//     if (item.isTemplateRoot) {
//       arrClone.splice(index, 1, ...item.children);
//     } else if (item.children?.length) {
//       item.children = hiddenTemplateRoot(item.children);
//     }
//   });

//   return arrClone;
// };
const refreshDraggable = () => {};

// const originTemplateList = ref<any>([]);

// const leftClick = (val: any) => {};
let tempActiveData: any;
const cloneComponent = (origin: any) => {
  const clone = cloneDeep(origin);
  clone.formId = ++idGlobal.value;
  clone.span = formConf.span;
  clone.renderKey = +new Date();
  if (!clone.layout) clone.layout = 'colFormItem';
  if (clone.layout === 'colFormItem') {
    clone.vModel = `field${idGlobal.value}`;
    if (clone.placeholder !== undefined) {
      clone.placeholder += clone.label;
    }
    tempActiveData = clone;
  } else if (clone.layout === 'rowFormItem') {
    clone.componentName = clone.label;
    delete clone.label;
    clone.gutter = formConf.gutter;
    clone.vModel = `field${idGlobal.value}`;
    tempActiveData = clone;
  }
  activeData.value = tempActiveData;
  activeId.value = tempActiveData.formId;

  return tempActiveData;
};
// const cloneTemplateComponent = (origin: any) => {
//   let clone = null;
//   if (origin.nodeInfo?.length === 1) {
//     clone = cloneDeep(origin.nodeInfo[0]);
//   } else if (origin.nodeInfo?.length > 1) {
//     clone = {
//       children: origin.nodeInfo,
//       isTemplateRoot: true, // 模板组件根节点，不需要显示
//     };
//   }

//   clone.formId = ++idGlobal.value;
//   clone.span = formConf.span;
//   clone.renderKey = +new Date();
//   if (!clone.layout) clone.layout = 'colFormItem';
//   if (clone.layout === 'colFormItem') {
//     clone.vModel = `field${idGlobal.value}`;
//     if (clone.placeholder !== undefined) {
//       (clone.placeholder += clone.label);
//     }
//     tempActiveData = clone;
//   } else if (clone.layout === 'rowFormItem') {
//     if (!clone.componentName) {
//       clone.componentName = clone.label;
//     }
//     delete clone.label;
//     clone.gutter = formConf.gutter;
//     clone.vModel = `field${idGlobal.value}`;
//     tempActiveData = clone;
//   }
//   activeData.value = tempActiveData;
//   activeId.value = tempActiveData.formId;
//   return tempActiveData;
// };

// 拖拽开始的事件
const onStart = () => {};

// 拖拽结束的事件
const onEnd = () => {
  refreshDraggable();
};

// const onTemplateEnd = () => {
//   refreshDraggable(true);
// };
// const clearDrawingList = () => {
// };
const idGlobal = ref<number>(100);
const activeId = ref<any>();
const activeData = ref<any>();

const activeFormItem = (element: any) => {
  activeData.value = element;
  activeId.value = element.formId;
  refreshDraggable();
};
// const drawingItemCopy = (item: any, parent: any) => {
//   let clone = cloneDeep(item);
//   clone = createIdAndKey(clone);
//   parent.push(clone);
//   activeFormItem(clone);
//   nextTick(() => {
//     draggableKey.value = +new Date();
//   });
// };
// const createIdAndKey = (item: any) => {
//   item.formId = ++idGlobal.value;
//   item.renderKey = +new Date();
//   if (item.layout === 'colFormItem') {
//     item.vModel = `field${idGlobal.value}`;
//   } else if (item.layout === 'rowFormItem') {
//     item.componentName = `row${idGlobal.value}`;
//   }
//   if (Array.isArray(item.children)) {
//     item.children = item.children.map((childItem: any) => createIdAndKey(childItem));
//   }
//   return item;
// };
const drawingItemDelete = (formId: any, parent: any) => {
  const idIndex = parent.findIndex((item: any) => {
    return item.formId === formId;
  });
  if (idIndex !== -1) {
    parent.splice(idIndex, 1);
  }
};
const showEditDialog = ref(false);
const drawingItemEdit = (formId: any, parent: any) => {
  showEditDialog.value = true;
  const idIndex = parent.findIndex((item: any) => {
    return item.formId === formId;
  });
  activeData.value = parent[idIndex];
};

const tagChange = (newTag: any) => {
  newTag = cloneComponent(newTag);
  newTag.vModel = activeData.value.vModel;
  newTag.formId = activeId.value;
  newTag.span = activeData.value.span;
  delete activeData.value.tag;
  delete activeData.value.tagIcon;
  delete activeData.value.document;
  Object.keys(newTag).forEach((key) => {
    if (
      activeData.value[key] !== undefined &&
      typeof activeData.value[key] === typeof newTag[key]
    ) {
      newTag[key] = activeData.value[key];
    }
  });
  activeData.value = newTag;
};

// const previewFormVisible = ref<boolean>(false);
// const previewData = ref<any>([]);
// const previewForm = () => {
// };
const updateActiveData = ({ key, data }: any) => {
  activeData.value[key] = data;
};
const isScript = ref<boolean>(false);
const templateList = ref<any>([]);
provide('templateList', templateList);

const formatTemplateList = () => {
  // templateList.value = userTemplateFile.value.map((item: any) => {
  //   const nodeInfoClone = cloneDeep(item.nodeInfo);
  //   convertDragList(nodeInfoClone, '2');
  //   item.nodeInfo = nodeInfoClone;
  //   item.label = item.templateName;
  //   return item;
  // });
};
// 新增模板
// const templateSettingVisible = ref<boolean>(false);
// const setTemplate = () => {
//   templateSettingVisible.value = true;
// };
// // 添加模板
// const addTemplate = () => {
//   // if (props.type === '2') {
//   //   emits('showAddTemplate');
//   // }
// };
// // 保存模板
// const saveTemplate = () => {
// };
// // 删除模板
// const deleteTemplate = () => {
//   // if (props.type === '2') {
//   //   emits('deleteTemplate');
//   // }
// };
// const templateSettingClose = () => {

//   // emits('templateSettingClose', () => {
//   //   return Promise.resolve();
//   // });
//   // return new Error();
// };
// const getImage = (tag: any) => {
//   if (!tag) {
//     return require('../../../../../assets/imgs/dragFlow/dragIcon/table.png');
//   }
//   if (tag === 'el-radio-group') {
//     return require('../../assets/img/dragIcon/el-checkbox.png');
//   }
//   if (tag === 'displayText') {
//     return require('../../assets/img/dragIcon/el-input.png');
//   }
//   return require(`../../assets/img/dragIcon/${tag}.png`);
// };

onMounted(() => {
  formatTemplateList();
});
defineExpose({ drawingList });
</script>
<style lang="scss">
.x6-graph {
  .default-theme {
    height: 100%;
  }
  .el-tabs__content {
    height: calc(100% - 40px);
  }
}
</style>
<style scoped lang="scss">
.default-theme {
  .components {
    width: 200px;
  }
}
.flow-drag-container {
  height: 100%;
  width: 100%;
  :deep(.splitpanes__pane) {
    background-color: unset !important;
  }
  :deep(.splitpanes__splitter) {
    background-color: #f0f4f9 !important;
  }
  .panel-container {
    height: 100%;
    width: 100%;
    .header {
      width: 100%;
      height: 44px;
      text-align: center;
      font-weight: 600;
      font-size: var(--font-size-text-normal);
      padding: var(--padding-medium) 0;
      border-bottom: 1px solid #e7e7e7;
    }

    :deep(.center-tabs) {
      .el-tabs__header {
        margin-bottom: 0 !important;
        padding: 0 !important;
      }
      .el-tabs__content {
        padding: 0 !important;
      }
      .el-tabs__item {
        width: 100%;
        text-align: center;
        margin: 0 !important;
        padding: 0 !important;

        &:not(.is-disabled):hover {
          color: #fff !important;
        }
      }
      .el-tabs__nav {
        width: 100%;
        padding-top: 0 !important;
        border-radius: unset !important;
      }
      .el-tabs__item.is-active {
        background-color: #fff !important;
        // color: #fff !important;
        border-radius: 0 !important;
      }
    }
    .left-panel {
      height: calc(100% - 44px);
      width: 100%;

      .component-container {
        height: 100%;
        width: 100%;
        overflow-y: auto;
        .components-title {
          height: 32px;
          width: 100%;
          display: flex;
          align-items: center;
        }
        .components-draggable {
          width: 100%;
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          grid-gap: 12px 12px;
          // flex-wrap: wrap;
          padding: var(--padding-medium);

          .components-body {
            display: flex;
            align-items: center;
            justify-content: center;
            display: inline-block;
            padding: 8px;
            // margin: 6px;
            // margin: var(--margin-tiny);
            // width: calc(50% - 12px);
            width: 100%;
            transition: transform 0ms !important;
            background: #f7f7f7;

            cursor: move;
            border: 1px dashed #f6f7ff;
            border-radius: 3px;
            span {
              font-size: var(--font-size-text-small);
            }
            &:hover {
              border: 1px dashed #787be8;
              color: #787be8;
              .svg-icon {
                color: #787be8;
              }
            }
            .el-icon {
              cursor: move;
            }
          }
        }
      }
    }
    .center-panel {
      height: 100%;
      width: 100%;
      // padding: 0 12px;
      .center-panel-head {
        height: 40px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      .center-panel-content {
        // height: calc(100% - 40px);
        height: 100%;
        width: 100%;
        background-color: var(--el-bg-color-page);
        // border: 1px solid #e6e6e6;

        .center-board-row {
          height: 100%;
          width: 100%;
          padding: 12px;
          box-sizing: border-box;
          overflow-y: auto;
          & > .el-form {
            width: 100%;
            height: 100%;
          }
          .drawing-board {
            height: 100%;
            width: 100%;
            & > div:last-child {
              margin-bottom: 0 !important;
            }
          }
        }
      }
    }
  }
}
.ghost {
  background: #f6f7ff;
  border-radius: 3px;
  border: 1px dashed #787be8;
}
:deep(.center-drag-item) {
  position: relative;
  border-radius: 3px;
  // border: 1px dashed #787be8;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-top: var(--padding-medium);
  padding-bottom: var(--padding-medium);
  padding-right: var(--padding-medium);
  background-color: #fff;
  &:has(.row-form-container) {
    padding-top: 0;
  }
}
:deep(.el-form-item) {
  width: 100%;
}
:deep(.center-drag-item.active-from-item) {
  // background: #f6f7ff;
  & > .darg-operation-container {
    display: flex;
  }
}
:deep(.row-form-container.active-from-item) {
  background: #f6f7ff;
  & > .darg-operation-container {
    display: flex;
  }
}
:deep(.row-form-container) {
  width: 100%;
  min-height: 100px;
  padding: 12px;
  padding-top: 0;
  .component-name {
    height: 50px;
    width: 100%;
    line-height: 50px;
    text-align: left;
  }
  .drag-wrapper {
    min-height: 100px;
    width: 100%;
    background: #fff;
  }
  // &:hover {
  // & > .darg-operation-container {
  //   display: flex;
  // }
  // }
}
:deep(.center-drag-item):hover {
  // background: #f6f7ff;
  border: 1px dashed #77acff;
  color: #787be8;
  // & > .darg-operation-container {
  //   display: flex;
  // }
}
</style>
