<template>
  <div class="qa-dialog-config">
    <!-- 互动问答内容设置 header -->
    <div class="config-header">
      <h3>互动问答内容设置</h3>
    </div>

    <!-- 问答对话设置 -->
    <el-form-item label="问答对话">
      <div
        v-for="(msg, index) in localConfig.agentMsg"
        :key="index"
        class="dialog-item"
      >
        <div class="dialog-header">
          <span>对话{{ msg.id }}</span>
          <div class="dialog-actions">
            <el-button type="text" @click="configDialog(msg.id)">设置</el-button>
            <el-button type="text" class="delete-btn" @click="removeDialog(msg.id)">删除</el-button>
          </div>
        </div>
        <div class="dialog-content">
          <div class="question">提问: {{ msg.text }}</div>
        </div>
      </div>

      <div class="add-dialog">
        <el-button type="text" @click="addDialog">
          <i class="el-icon-plus"></i>
          添加对话（还可以添加{{ 6 - localConfig.agentMsg.length }}项）
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="客服头像">
      <div class="avatar-setting">
        <image-upload v-model="localConfig.style.avatar" :file-type='["png", "jpg", "jpeg", "gif"]' :limit="1"/>
      </div>
    </el-form-item>

    <el-form-item label="按钮配色">
      <el-color-picker v-model="localConfig.style.buttonColor"></el-color-picker>
    </el-form-item>

    <el-form-item label="按钮文字颜色">
      <el-color-picker v-model="localConfig.style.btnTextColor"></el-color-picker>
    </el-form-item>

    <!-- 聊天配置对话框-->
    <h5-chat-config-dialog :dialog-index="currentDialogIndex" :dialog="currentMsg" :visible="dialogConfigVisible"
                           @update:visible="dialogConfigVisible=$event"
                           @update:dialog="updateDialogData"
    />
  </div>
</template>

<script>
import H5ChatConfigDialog from '@/components/H5/config-item/h5-chat-config-dialog.vue'
import draggable from 'vuedraggable'

export default {
  name: 'ChatConfigComponent',
  components: {
    draggable,
    H5ChatConfigDialog
  },
  computed: {
  },
  props: {
    config: {
      type: Object,
      default: () => ({
        messages: [{
          id: 1,
          sender: 'agent',
          text: '您好！欢迎报名【中老年健康养生大讲堂】，请仔细答一下问题，便于帮您分配专业的老师进行指导。',
          welcome: true
        },
          {
            id: 2,
            sender: 'agent',
            text: '您的年龄？',
            options: [
              { id: 1, text: '45-55岁', answer: '' },
              { id: 2, text: '55-60岁', answer: '' },
              { id: 3, text: '60-65岁', answer: '' },
              { id: 4, text: '65岁以上', answer: '' }
            ],
            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: [],
        style: {
          avatar: '',
          buttonColor: '#409EFF',
          btnTextColor: ''
        }
      })
    }
  },
  data() {
    return {
      localConfig: {agentMsg:[],...this.config},
      currentMsg: null,
      dialogConfigVisible: false,
      currentDialogIndex: -1
    }
  },
  watch: {
    'localConfig.style.avatar': {
      handler(newVal) {
        if (newVal) {
          this.$emit('update:config', this.localConfig)
        }
      },
      deep: true
    },
    'localConfig.agentMsg':{
      handler(newVal) {
        if (newVal) {
          setTimeout(()=>{
            // 根据agentMsg生成Message列表
            let messages = []
            let id = 0;
            this.localConfig.agentMsg?.forEach((msg)=>{
              id++;
              if(!msg.options || msg.options.length === 0) {
                messages.push({...msg,id: id})
              } else {
                messages.push({...msg,id: id})
                messages.push({
                  id: ++id,
                  sender: 'user',
                  text: msg.options[0].text
                })
              }
            })
            messages.push({
              id: ++id,
              sender: 'agent',
              text: "好的，已经为您分配专业老师。<span style='color:red'>【点击下方按钮】</span>添加老师，获取免费上课链接。!",
              options: []
            })
            this.localConfig.messages = messages;
            this.$emit('update:config', this.localConfig)
          },100)
        }
      },
      deep: true
    }
  },
  methods: {
    addDialog() {
      if ((6 - this.localConfig.agentMsg.length) <= 0) {
        alert('最多只能添加6条对话')
        return
      }
      let maxId = Math.max(0,...this.localConfig.agentMsg.map(msg => msg.id));
      if(!maxId){
        maxId = 0;
      }
      this.localConfig.agentMsg.push({
        id: maxId + 1,
        sender: 'agent',
        text: '新增对话',
        welcome: true
      })
      this.$emit('update:config', this.localConfig)
    },
    removeDialog(id) {
      let index = this.localConfig.agentMsg.findIndex(msg => msg.id === id)
      this.localConfig.agentMsg.splice(index, 1)
      this.$emit('update:config', this.localConfig)
    },
    configDialog(id) {
      // 通过 id 找到对应的消息
      let index = this.localConfig.agentMsg.findIndex(msg => msg.id === id)
      if (index === -1) {
        console.error(`Message with id ${id} not found.`)
        return
      }
      this.currentDialogIndex = index
      this.currentMsg = this.localConfig.agentMsg[index]
      this.dialogConfigVisible = true
      this.$set(this.$data, index, this.currentMsg)
    },
    updateDialogData(data) {
      this.localConfig.agentMsg[this.currentDialogIndex] = data
      this.currentMsg = data
      this.$emit('update:config', this.localConfig)
    }
  }
}
</script>

<style scoped>
.qa-dialog-config {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  position: relative;
}

.config-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.qa-section, .style-section {
  margin-bottom: 20px;
}

h4 {
  font-weight: 500;
  margin-bottom: 15px;
}


.add-dialog {
  color: #409EFF;
  cursor: pointer;
  margin-top: 5px;
}

.dialog-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-actions {
  display: flex;
}

.delete-btn {
  color: #F56C6C;
}

.dialog-content {
  padding: 12px;
}

.avatar-setting, .color-setting {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.setting-label {
  width: 80px;
  font-size: 14px;
}


</style>
