<script>
import Draggable from 'vuedraggable';
import FormRender from '@/views/workFlow/designer/common/form/FormRender.vue';
import FormComponentConfig from '@/views/workFlow/designer/common/form/FormComponentConfig.vue';
import FormDesignRender from '@/views/workFlow/designer/common/form/FormDesignRender.vue';
import { mapState } from 'vuex';
import { baseComponents } from '@views/workFlow/designer/common/form/ComponentsConfigExport'

export default {
  name: 'FormDesign',
  components: {
    Draggable,
    FormRender,
    FormComponentConfig,
    FormDesignRender
  },
  data() {
    return {
      isStart: false,
      showMobile: false,
      viewFormVisible: false,
      drag: false,
      formData: {},
      componentLib: [],
    };
  },
  computed: {
    ...mapState('workflow', ['design', 'selectFormItem', 'nodeMap']),
    forms() {
      const dform = this.design.formItems;
      if (dform.length === 0) {
        dform.push({ d_anl: true });
      }
      return dform
    }
  },
  created() {
    this.componentLib = this.getBaseComponents();
  },
  methods: {
    getBaseComponents() {
      return baseComponents;
    },
    selectItem(cp) {
      this.$store.dispatch('workflow/updateSelectFormItem', cp);
    },
    handleDragStart() {
      this.drag = true;
      this.selectItem(null);
    },
    handleDragEnd() {
      this.drag = false;
    },
    clone(obj) {
      const newObj = JSON.parse(JSON.stringify(obj));
      newObj.id = this.getId(); // ✅在克隆副本上操作
      return newObj;
    },
    getId() {
      return `field${Math.floor(Math.random() * 90000 + 10000)}${Date.now().toString().slice(-5)}`;
    },
    getSelectedClass(cp) {
      return this.selectFormItem && this.selectFormItem.id === cp.id
        ? 'border-left: 4px solid #409eff'
        : '';
    },
    viewForms() {
      this.viewFormVisible = true;
    },
    del(index) {
      this.$confirm({
        title: '确认删除',
        content: '删除组件将会连带删除包含该组件的条件以及相关设置，是否继续？',
        onOk: () => {
          this.removeCondition(this.forms[index]);
          this.design.formItems.splice(index, 1);
          this.$message.success('删除成功');
        }
      });
    },
    removeCondition(item) {
      if (item.name === 'SpanLayout') {
        item.props.items.forEach(sub => this.removeCondition(sub));
        item.props.items.length = 0;
      } else {
        this.nodeMap.forEach(node => {
          if (node.type === 4) {
            node.conditionNodes.forEach(conditionNode => {
              conditionNode.conditionList.forEach(group => {
                const idx = group.findIndex(cond => cond.field === item.id);
                if (idx !== -1) group.splice(idx, 1);
              });
            });
          }
        });
      }
    },
    validateItem(err, idSet, item) {
      if (idSet.has(item.id) && item.name !== 'SpanLayout') {
        err.push(`表单 ${item.id} 标识重复`);
      }
      idSet.add(item.id);
      if (
        (item.name === 'SelectInput' || item.name === 'MultipleSelect') &&
        item.props.options.length === 0
      ) {
        err.push(`${item.title} 未设置选项`);
      } else if (item.name === 'TableList') {
        if (item.props.columns.length === 0) {
          err.push(`明细表 ${item.title} 内未添加组件`);
        }
      } else if (item.name === 'SpanLayout') {
        if (item.props.items.length === 0) {
          err.push('分栏内未添加组件');
        } else {
          item.props.items.forEach(sub => this.validateItem(err, idSet, sub));
        }
      }
    },
    validate() {
      const err = [];
      const idSet = new Set();
      if (this.forms.length === 0) {
        err.push('表单为空，请添加组件');
      } else {
        this.forms.forEach(item => this.validateItem(err, idSet, item));
      }
      return err;
    }
  }
};
</script>

<template>
  <div class="form-design">
    <a-row type="flex">
      <!-- 左侧组件库 -->
      <a-col :span="5" class="form-design-component-list">
        <div class="components-nav"><span>组件库</span></div>
        <div v-for="(group, i) in componentLib" :key="i" class="components">
          <p style="font-size: 16px">{{ group.name }} ({{ group.components.length }})</p>
          <draggable
            class="fdrag"
            :list="group.components"
            :sort="false"
            :group="{ name: 'form', pull: 'clone', put: false }"
            :clone="clone"
            @start="isStart = true"
            @end="isStart = false"
          >
            <li
              v-for="(element, index) in group.components"
              :key="index"
              class="fdrag-li"
            >
              <i :class="element.icon" class="x-iconfont"></i>
              <span>{{ element.title }}</span>
            </li>
          </draggable>
        </div>
      </a-col>

      <!-- 中间设计区 -->
      <a-col :span="14" class="form-design-component-render">
        <div class="tool-nav">
<!--          <a-tooltip title="撤销"><i class="x-icon-refresh-left x-iconfont icon-style"></i></a-tooltip>-->
<!--          <a-tooltip title="恢复"><i class="x-icon-refresh-right x-iconfont icon-style"></i></a-tooltip>-->
          <a-tooltip title="预览"><i class="x-icon-view x-iconfont icon-style" @click="viewForms"></i></a-tooltip>
<!--          <a-tooltip title="移动端"><i class="x-icon-mobile x-iconfont icon-style" @click="showMobile = true"></i>-->
<!--          </a-tooltip>-->
<!--          <a-tooltip title="PC端"><i class="x-icon-monitor x-iconfont icon-style" @click="showMobile = false"></i>-->
<!--          </a-tooltip>-->
        </div>
<!--        <div class="work-form" :class="showMobile ? 'mobile' : 'pc'">-->
        <div class="work-form" >
          <div class="drag-wrapper">
            <draggable
              class="drag-from"
              :list="forms"
              :options="{ animation: 300, chosenClass: 'choose', sort: true }"
              :group="{ name: 'form', pull: true, put: true }"
              @start="handleDragStart"
              @end="handleDragEnd"
            >
                <div
                  v-for="(element, index) in forms"
                  :key="index"
                  class="form-item"
                  v-if="!element.d_anl"
                  :style="getSelectedClass(element)"
                  @click="selectItem(element)"
                >
                  <div class="form-header">
                    <p>
                      <span v-if="element.props && element.props.required">*</span>
                      {{ element.title }}
                    </p>
                    <div class="option">
                      <i class="x-icon-close x-iconfont" @click.stop="del(index)"></i>
                    </div>
                    <FormDesignRender :config="element" />
                  </div>
                </div>
            </draggable>
            <div v-if="(forms.length === 0 || forms[0].d_anl) && !isStart" class="n-tip">
              请在左侧选择控件并拖至此处
            </div>
          </div>
        </div>
      </a-col>

      <!-- 右侧配置项 -->
      <a-col :span="5" class="form-design-component-config">
        <div v-if="selectFormItem" class="tool-nav-r">
          <i :class="selectFormItem.icon" class="x-iconfont" style="margin-right: 5px;"></i>
          <span>{{ selectFormItem.title }}</span>
        </div>
        <div v-if="!selectFormItem || forms.length === 0" class="tip">选中控件后在这里进行编辑</div>
        <div v-else class="config-area">
          <FormComponentConfig />
        </div>
        <a-modal v-model="viewFormVisible" title="表单预览" width="45%">
          <FormRender ref="form" :value="formData" :forms="forms" />
        </a-modal>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped lang="less">
.form-design {
  width: 100%;
  height: calc(100vh - 220px);
  background-color: #f5f6f6;
}

.form-design-component-list {
  .components-nav {
    display: flex;
    align-items: center;
    margin: 12px 12px 0;
    height: 30px;
    box-shadow: 0 2px 4px 0 rgba(17, 31, 44, 0.04);
    border: 1px solid #ecedef;
    border-radius: 16px;
    background-color: #fff;
    span {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      font-size: 18px;
      color: rgba(17, 31, 44, 0.72);
      cursor: pointer;
      &:hover {
        color: @primaryColor;
      }
    }
  }

  .components {
    overflow-x: hidden;
    overflow-y: scroll;
    //margin-top: 20px;
    //padding: 0 20px;
    font-size: 12px;
    width: 100%;
    color: rgba(17, 31, 44, 0.85);
    & > p {
      padding: 0 20px;
    }
  }

  .fdrag {
    margin-left: 20px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .fdrag-li {
      text-align: center;
      display: flex;
      align-items: center;
      width: 124px;
      height: 38px;
      margin-bottom: 12px;
      border-radius: 8px;
      cursor: grab;
      background-color: #fff;
      border: 1px solid transparent;

      &:hover {
        border: 1px solid @primaryColor;
        color: @primaryColor;
      }

      i {
        margin: 0 12px;
      }
    }

    li:nth-child(odd) {
      margin-right: 8px;
    }
  }
}

.form-design-component-render {
  .tool-nav {
    font-size: medium;
    padding: 8px 20px;
    background: #fafafb;
    border-bottom: 1px solid #ebecee;

    div:first-child {
      display: inline-block;
      text-align: left;

      i {
        margin-right: 10px;
      }
    }

    div:last-child {
      float: right;

      i {
        margin-left: 10px;
      }
    }

    i {
      color: #7a7a7a;
      cursor: pointer;

      &:hover {
        color: #4b4b4b;
      }
    }
  }
}

.work-form {
  margin: 0 auto;
  height: calc(100% - 38px);
  overflow-y: auto;
  background: rgb(245, 246, 246);
  border-left: 1px solid rgb(235, 236, 238);
  border-right: 1px solid rgb(235, 236, 238);

  //.pc {
  //  margin-top: 4%;
  //
  //  .drag-from {
  //    height: calc(100vh - 190px);
  //    background-color: rgb(245, 246, 246);
  //
  //    .form-item,
  //    li {
  //      cursor: grab;
  //      background: #ffffff;
  //      padding: 10px;
  //      border: 1px solid #ebecee;
  //      margin: 5px 0;
  //    }
  //  }
  //}

  //.mobile {
  //  margin-left: auto;
  //  margin-right: auto;
  //  width: 360px;
  //  max-height: 640px;
  //  margin-top: 4%;
  //  border-radius: 24px;
  //  box-shadow: 0 8px 40px 0 rgba(17, 31, 44, 0.12);
  //
  //  .bd {
  //    border: 1px solid rgba(17, 31, 44, 0.08);
  //    border-radius: 24px;
  //    padding: 10px 10px;
  //    background-color: #ffffff;
  //
  //    .form-content {
  //      padding: 3px 2px;
  //      border-radius: 14px;
  //      background-color: #f2f4f5;
  //
  //      .drag-from {
  //        width: 100%;
  //        height: calc(100vh - 190px);
  //        min-height: 200px;
  //        max-height: 600px;
  //      }
  //
  //      .form {
  //        overflow-y: auto;
  //        width: 100%;
  //        display: inline-block;
  //        max-height: 640px;
  //
  //        .form-item,
  //        li {
  //          border: 1px solid #ffffff;
  //          list-style: none;
  //          background: #ffffff;
  //          padding: 10px;
  //          margin: 5px 0;
  //          cursor: grab;
  //        }
  //      }
  //    }
  //  }
  //}

}

.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);
    }
  }

  .option {
    position: absolute;
    top: -10px;
    right: -10px;
    i {
      font-size: large;
      cursor: pointer;
      color: #8c8c8c;
      padding: 5px;
      &:hover {
        color: #f56c6c;
      }
    }
  }
}

.form-design-component-config {
  text-align: center;
  font-size: 14px;
  color: rgb(122, 122, 122);

  .tool-nav-r {
    text-align: left;
    font-size: small;
    border-left: 1px solid #ebecee;
    padding: 8px 20px;
    background: #fafafb;
    border-bottom: 1px solid #ebecee;
  }

  .tip {
    margin-top: 150px;
  }
}

.n-tip{
  text-align: center;
  color: #888;
  padding: 20px;
  pointer-events: none;
}
.icon-style {
  margin-left: 10px;
  font-size: 18px;
}
.drag-wrapper {
  min-height: 100%;
  position: relative;
  background: #fff;
  border: 1px dashed #ccc;

  .drag-from {
    min-height: 300px;
    padding: 10px;
  }

  .form-item {
    background: #ffffff;
    margin: 10px 0;
    border: 1px solid #ccc;
    padding: 10px;
  }
}
</style>
