<template>
  <div class="h5-editor-container">
    <div class="h5-editor">
    </div>
    <el-row :gutter="24">
      <el-col :span="2" class="button-body">
        <div v-for="item in componentList">
          <p/>
          <div>
            {{ item.groupName }}
          </div>
          <el-button class="button-tag" @click="add(item)" v-for="item in item.comps">
            <!-- 添加图标和文字 -->
            <i :class="item.icon" style="margin-right: 5px"></i>
            {{ item.label }}
          </el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="parent-container">
          <div class="view-body">
            <draggable v-model="list" @end="end">
              <div v-for="(item, index) in list" :key="index" @click="select(index)" class="view-item">
                <component :is="item.type" :config="item"/>
              </div>
            </draggable>
          </div>
        </div>
      </el-col>
      <el-col :span="10" style="overflow-y: auto;height:80vh;">
        <form-wrapper
          :form="form"
          :index="index"
          :list="list"
          @update:form="updateForm"
          @delete="del"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import H5Text from '@/components/H5/h5-text.vue'
import H5Image from '@/components/H5/h5-image.vue'
import H5Button from '@/components/H5/h5-button.vue'
import H5Sep from '@/components/H5/h5-sep.vue'
import H5Countdown from '@/components/H5/h5-countdown.vue'
import FormWrapper from '@/components/H5/FormWrapper.vue'
import H5Chat from '@/components/H5/h5-chat.vue'
import AgentAvatar from '@/assets/images/customer.png?inline'

export default {
  components: {
    draggable, // 对应模板中的<h5-text>
    H5Text, // 对应模板中的<h5-text>
    H5Button, // 对应模板中的<h5-text>
    H5Image,// 对应模板中的<h5-image>
    H5Sep,// 对应模板中的<h5-sep>
    H5Countdown,// 对应模板中的<h5-countdown>
    FormWrapper,
    H5Chat
  },
  mounted() {
    this.initData(this.json)
  },
  props: {
    json: {
      type: String,
      default: '[]'
    }
  },
  data() {
    return {
      componentList: [{
        groupName: '基础控件',
        comps: [
          {
            type: 'h5-text',
            label: '文本',
            icon: 'el-icon-document'         // 文档图标更符合文本语义
          },
          {
            type: 'h5-image',
            label: '图片',
            icon: 'el-icon-picture'          // 明确的图片图标
          },
          {
            type: 'h5-sep',
            label: '分割线',
            icon: 'el-icon-minus'            // 减号图标模拟分割线效果
          }
        ]
      }, {
        groupName: '营销控件',
        comps: [
          {
            type: 'h5-countdown',
            label: '倒计时',
            icon: 'el-icon-timer'            // 计时器图标表示倒计时
          },
          {
            type: 'h5-chat',
            label: '互动问答',
            icon: 'el-icon-chat-square'     // 购物袋表示购买相关
          }
        ]
      }],
      list: [],
      index: 0,
      form: {}
    }
  },
  methods: {
    initData(json) {
      this.list = JSON.parse(json)
    },
    end() {

    },
    add(item) {
      let data = {
        type: item.type,
        active: false,
        name: item.label,
        fixe: false,
        classText: ['parent-div'],
        addWxFun: false,
        workUrl: ''
      }
      if (item.type === 'h5-text') {
        data.content = '默认文本'
        data.style = {
          textAlign: 'left',
          fontSize: 20,
          background: '#FFF',
          color: '#000',
          fontWeight: 'none',
          fontStyle: 'none',
          textDecoration: 'none'
        }
      } else if (item.type === 'h5-image') {
        data.url = null
      } else if (item.type === 'h5-button') {
        data.content = '默认文本'
      } else if (item.type === 'h5-sep') {
        data.classText = [...data.classText, 'divider']
        data.style = {
          height: '10px',
          background: 'rgb(228, 231, 237)'
        }
      } else if (item.type === 'h5-countdown') {
        data.days = 0
        data.hours = 0
        data.minutes = 0
        data.seconds = 0
        data.countdownMode = 1
      } else if (item.type === 'h5-chat') {
        data = {...data,
          ...{
            messages: [
              {
                id: 1,
                sender: "agent",
                text: "您好！欢迎报名【中老年健康养生大讲堂】，请仔细答一下问题，便于帮您分配专业的老师进行指导。",
                welcome: true
              },
              {
                id: 2,
                sender: "agent",
                text: "您的年龄？",
                options: [
                  { id: 1, text: "45-55岁" },
                  { id: 2, text: "55-60岁" },
                  { id: 3, text: "60-65岁" },
                  { id: 4, text: "65岁以上" }
                ],
                userSelection: null
              },
              {
                id: 3,
                sender: "user",
                text: '45-55岁',
                userSelection: { id: 1, text: "45-55岁" }
              },
              {
                id: 4,
                sender: "agent",
                text: "更想通过课程学习到哪些知识？",
                options: [
                  { id: 1, text: "食疗食补" },
                  { id: 2, text: "经络疏通" },
                  { id: 3, text: "脏腑调养" },
                  { id: 4, text: "启蒙养生" },
                  { id: 5, text: "以上所有" }
                ],
                userSelection: null
              },
              {
                id: 5,
                sender: "user",
                text: '食疗食补',
                userSelection: { id: 1, text: "食疗食补" }
              }
            ],
            agentMsg:[{
              id: 1,
              sender: "agent",
              text: "您好！欢迎报名【中老年健康养生大讲堂】，请仔细答一下问题，便于帮您分配专业的老师进行指导。",
              welcome: true
            },
              {
                id: 2,
                sender: "agent",
                text: "您的年龄？",
                options: [
                  { id: 1, text: "45-55岁" },
                  { id: 2, text: "55-60岁" },
                  { id: 3, text: "60-65岁" },
                  { id: 4, text: "65岁以上" }
                ],
                userSelection: null
              },
              {
                id: 4,
                sender: "agent",
                text: "更想通过课程学习到哪些知识？",
                options: [
                  { id: 1, text: "食疗食补" },
                  { id: 2, text: "经络疏通" },
                  { id: 3, text: "脏腑调养" },
                  { id: 4, text: "启蒙养生" },
                  { id: 5, text: "以上所有" }
                ],
                userSelection: null
              }
              ],
            style: {
              avatar: window.location.origin+AgentAvatar,
              buttonColor: '#409EFF',
              textColor: ''
            }
          }
        }
        console.log(data)
        let h5chat = this.list.some(item => item.type && item.type.includes('h5-chat'))
        if (h5chat) {
          alert('全局只能允许有一个互动问答!')
          return
        }
      }
      console.log(this.list)

      if (this.index !== null && this.index >= 0 && this.index < this.list.length) {
        this.list.splice(this.index + 1, 0, data)
      } else {
        this.list.push(data)
      }
    },
    select(index) {
      this.index = index
      let className = 'active'
      this.clearClass(className)
      this.addClass(className)
      this.$set(this.list[index], 'active', true)  // 确保响应式更新
      // 直接绑定list中的对象（关键修改）
      this.form = this.list[index]
    },
    clearClass(classText) {
      this.list.forEach(item => {
        // 推荐使用 $set
        this.$set(item, 'classText', item.classText.filter(c => c !== classText))
      })
    },
    addClass(classText) {
      this.list[this.index].classText.push(classText)
    },

    del() {
      this.list.splice(this.index, 1)
      this.form = {}
    },
    updateForm(newForm) {
      // 更新表单数据
      if (this.index === undefined || !this.list[this.index]) {
        console.error('Invalid index or list item')
        return
      }

      console.log('newForm:', newForm) // 检查 newForm 数据
      Object.assign(this.form, newForm)

      // 更新列表中的数据
      for (const key in newForm) {
        if (Object.hasOwnProperty.call(newForm, key)) {
          // 如果是嵌套对象，递归更新
          if (typeof newForm[key] === 'object' && newForm[key] !== null) {
            for (const nestedKey in newForm[key]) {
              this.$set(this.list[this.index][key], nestedKey, newForm[key][nestedKey])
            }
          } else {
            this.$set(this.list[this.index], key, newForm[key])
          }
        }
      }

      console.log('Updated list:', this.list[this.index])
    }
  }
}
</script>
<style lang="scss" scoped>
.button-body {
  text-align: center;
  margin: 0 auto;

  .button-tag:first-child {
    margin-top: 0 !important;
  }

  .button-tag {
    margin-left: 0;
    margin-top: 10px;
  }
}

/* 外层容器 (父级div) */
.parent-container {
  background: #eff3f5;
  padding: 40px 0;
  width: 100%;

  /* 关键设置 */
  height: 80vh;
  overflow-y: auto; /* 滚动条出在这里 */
  border: 1px solid #DCDEE2;
}
/* 定制滚动条样式 */
.parent-container::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}

.parent-container::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道背景色 */
  border-radius: 3px; /* 轨道圆角 */
}

.parent-container::-webkit-scrollbar-thumb {
  background: #888; /* 滚动条滑块颜色 */
  border-radius: 3px; /* 滑块圆角 */
}

.parent-container::-webkit-scrollbar-thumb:hover {
  background: #555; /* 滑块悬停颜色 */
}
.view-body {
  width: 375px; /* 明确具体值（会覆盖下面的width:100%） */
  height: auto; /* 改掉height:100%，否则会根据父级高度计算*/

  /* 清除非必须设置 */
  overflow-y: visible; /* 保持默认 */

  /* 其他属性 */
  margin: 0 auto; /* 代替外层flex的justify-content */
  background: #fff;
  position: relative;
  padding: 0;
}

.icon.svg {
  cursor: pointer;
  margin-left: 20px;
  width: 20px;
  height: 20px;
}

.icon.svg.active {
  color: #02ff9b;
}

.icon-span {
}

.divider {
  width: 100%;
  background: #DCDEE2;
  height: 10px;
}

.button-tag {
  /* 新增图标样式 */
  .el-icon {
    margin-right: 6px; /* 图标与文本间距 */
    font-size: 16px; /* 统一图标大小 */
    vertical-align: -2px; /* 垂直居中补偿 */
  }

  &.is-plain .el-icon {
    color: #666; /* 浅色主题下保持可视性 */
  }
}


</style>
