<template>
  <div class="h-full flex flex-col">
    <div class="h-77px bg-hex-F8F8F8 rounded-tl-24px rounded-tr-24px flex items-center text-12px px-15px">
      <div class="flex-1 flex space-x-6 text-center">
        <template v-for="(item, index) in operateData" :key="index">
          <el-popover v-if="item.key==='qjys'" :visible="visible" placement="top" :width="280">
            <div class="px-10px">
              <el-slider v-model="rate" :min="0.5" :max="2" :step="0.1" />
            </div>
            <div class="text-right my-6px px-10px">
              <el-button size="small" text @click="handleConfirm()">取消</el-button>
              <el-button size="small" type="primary" @click="handleConfirm(true)">确定</el-button>
            </div>
            <template #reference>
              <div class="" :class="item.readonly && disabled ? 'cursor-not-allowed' : 'cursor-pointer'" @click="handleOpen">
                <div>
                  <img class="m-auto" :src="item.readonly && disabled ? item.icon_disabled : item.icon" alt="" />
                  <div class="mt-5px" :class="item.readonly && disabled ? 'text-hex-ccc' : 'text-hex-333'">{{ item.name }}</div>
                </div>
              </div>
            </template>
          </el-popover>
          <el-popover v-else placement="bottom" :teleported="false" trigger="hover" :width="130">
            <template v-if="item.key==='crtd'">
              <el-button class="item pl-15px" v-for="(item, index) in pauseData" :key="index" @click="handleInsertPause(item)">{{ item }}</el-button>
            </template>
            <template v-if="item.key==='szfh'">
              <el-button class="item pl-15px" v-for="(item, index) in figureData" :key="index" @click="handleReadDigital(index)">读{{ item.name }}</el-button>
            </template>
            <template #reference>
              <div class="" :class="item.readonly && disabled ? 'cursor-not-allowed' : 'cursor-pointer'">
                <div>
                  <img class="m-auto" :src="item.readonly && disabled ? item.icon_disabled : item.icon" alt="" />
                  <div class="mt-5px" :class="item.readonly && disabled ? 'text-hex-ccc' : 'text-hex-333'">{{ item.name }}</div>
                </div>
              </div>
            </template>
          </el-popover>
        </template>
      </div>
    </div>
    <div class="editor flex-1 p-15px" contenteditable="true" @input="handleChange" @mouseup.stop="handleMouseup" v-html="showContent"></div>
  </div>
</template>

<script setup>
const props = defineProps({
  speech: String,
  showContent: String
})

const emits = defineEmits(['update:speech', 'modify'])

const operateData = ref([
  // {
  //   name: "中英转换",
  //   icon: "/images/szr1.png",
  //   icon_disabled: "/images/szr1-disabled.png"
  // },
  {
    name: "插入停顿",
    key: "crtd",
    icon: "/images/szr2.png",
    icon_disabled: "/images/szr2-disabled.png",
    readonly: true
  },
  {
    name: "全局语速",
    key: "qjys",
    icon: "/images/szr3.png",
    icon_disabled: "/images/szr3-disabled.png"
  },
  // {
  //   name: "多音字",
  //   icon: "/images/szr4.png",
  //   icon_disabled: "/images/szr4-disabled.png"
  // },
  {
    name: "数字符号",
    key: "szfh",
    icon: "/images/szr5.png",
    icon_disabled: "/images/szr5-disabled.png",
    readonly: true
  },
  // {
  //   name: "动作",
  //   icon: "/images/szr6.png",
  //   icon_disabled: "/images/szr6-disabled.png"
  // }
])

const disabled = ref(false);

const visible = ref(false);
const rate = ref("");
const speechRate = ref(Number(props.speech));

watch(
  () => props.speech, (val) => {
    speechRate.value = Number(val);
  }
)

function handleOpen() {
  visible.value = true;
  rate.value = speechRate.value;
}

function handleConfirm(set) {
  visible.value = false;
  if (set) {
    speechRate.value = rate.value;
    emits("update:speech", speechRate.value)
  }
}

function handleChange() {
  emits("modify", true)
}

const pauseData = ref(["0.5s", "1s", "2s"]);
const activeFigure = ref(0);
const figureData = ref([
  {
    name: "数值",
    value: "cardinal"
  },
  {
    name: "数字",
    value: "digits"
  },
  {
    name: "手机号",
    value: "telephone"
  }
])

const selectedParams = ref({});
const selectedText = ref("");
const selectedRange = ref({});
const selectedParentClass = ref("");
const selectedFigure = ref("");
function handleMouseup(el) {
  selectedParams.value = window.getSelection();
  if (selectedParams.value) {
    selectedText.value = selectedParams.value.toString();
    selectedRange.value = selectedParams.value.getRangeAt(0);
    // disabled.value = false;
  }

  selectedParentClass.value = el.target.getAttribute("class") || "";
  selectedFigure.value = el.target.getAttribute("n");
}

const handleRemove = (el, type) => {
  if (type === 1) {
    el.currentTarget.parentNode.remove();
  } else if (type === 2) {
    let parent = el.currentTarget.parentNode.parentNode;
    let text = parent.querySelector(".selectedValue").innerText;
    parent.replaceWith(text);
  } else if (type === 3) {
    el.parentNode.remove();
  }
}

// 插入停顿
function handleInsertPause(time) {
  let sel = selectedParams.value;
  if (sel.rangeCount) {
    let range = selectedRange.value;
    let icon = '<img class="closeBtn1 cursor-pointer ml-5px" src="/images/close1.png" alt="" />'
    let str = time + icon;
    range.collapse(false);
    let span = document.createElement("span");
    span.setAttribute('class', 'break-icon mx-3px select-none bg-hex-07c578 h-24px text-white text-sm px-8px rounded-4px inline-flex items-center');
    span.setAttribute('contenteditable', 'false');
    span.innerHTML = str;
    range.insertNode(span);

    range.setStartAfter(span);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);

    span.querySelector(".closeBtn1").addEventListener("click", (el) => {
      handleRemove(el, 1);
    });
  } else {
    ElMessage.warning('请选择插入位置！')
  }
}

// 数字符号
function handleReadDigital(index) {
  activeFigure.value = index;
  let sel = selectedParams.value;
  if (sel.rangeCount) {
    let range = selectedRange.value;
    let text = selectedText.value;
    if (text.indexOf("$nbsp") !== -1) {
      ElMessage.warning('划选内容有误！')
      return
    }
    let flag = isNaN(text);
    if (flag || !text) {
      ElMessage.warning('请选择数字文本！')
      return
    }
    let index = selectedParentClass.value.indexOf("selectedValue");
    if (index === 0) {
      ElMessage.warning(`【${figureData.value[activeFigure.value].name}】不能放在【${selectedFigure.value}】内`);
      return
    }
    range.deleteContents();
    range.collapse(true);

    let span = document.createElement("span");
    span.setAttribute('class', 'digital inline-flex items-center');
    span.setAttribute('contenteditable', 'false');
    span.innerHTML = `
        <span contenteditable="false" class="select-none bg-hex-ffb040 h-24px text-white text-sm px-8px rounded-4px inline-flex items-center">
          读${figureData.value[activeFigure.value].name}
          <img class="closeBtn2 cursor-pointer ml-5px" src="/images/close1.png" alt="" />
        </span>
        <span contenteditable="false" class="text-hex-ffb040 select-none">【</span>
        <span contenteditable="false" style="font-size: 0;">$nbsp;</span>
        <span class="selectedValue" contenteditable="true" v="${figureData.value[activeFigure.value].value}" n="${figureData.value[activeFigure.value].name}">${text}</span>
        <span contenteditable="false" style="font-size: 0;">$nbsp;</span>
        <span contenteditable="false" class="text-hex-ffb040 select-none">】</span>`;
    range.insertNode(span);

    range.setStartAfter(span);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);

    selectedText.value = "";

    span.querySelector(".closeBtn2").addEventListener("click", (el) => {
      handleRemove(el, 2);
    });

    // 控制已选择数字符号的内容只能输入数字
    var lock = false;
    span.querySelector(".selectedValue").addEventListener("compositionstart", function (el) {
      lock = true;
    })
    span.querySelector(".selectedValue").addEventListener("input", (el) => {
      if (!lock) {
        let flag1 = isNaN(el.target.innerText);
        if (flag1) {
          el.target.innerText = el.target.innerText.replace(/[^0-9]/g, '');
          ElMessage.warning('输入数字格式有误!');
        }
      }
    });
    span.querySelector(".selectedValue").addEventListener("compositionend", function (el) {
      let flag1 = isNaN(el.target.innerText);
      if (flag1) {
        el.target.innerText = el.target.innerText.replace(/[^0-9]/g, '');
        ElMessage.warning('输入数字格式有误!');
      }
      lock = false;
    })
    // 已选择数字符号的内容清空后删除数字符号标注
    span.querySelector(".selectedValue").addEventListener("keydown", (el) => {
      if (el.keyCode === 8 || el.keyCode === 46) {
        if (el.target.innerText.length === 1) {
          handleRemove(el.target, 3);
        }
      }
    });
  } else {
    ElMessage.warning('请选择数字文本！')
  }
}

onMounted(() => {
  // 换行标签，待定
  // document.execCommand("defaultParagraphSeparator", false, "p");

  // 只粘贴纯文本内容
  document.querySelector("div[contenteditable]").addEventListener("paste", function (e) {
    e.preventDefault();
    var text = e.clipboardData.getData("text/plain");
    text = text.replace(/\$nbsp;/g, '');
    document.execCommand("insertHTML", false, text);
  });

  // document.addEventListener("mouseup", function(el) {
  //   el.preventDefault();
  //   disabled.value = true;
  // })
})

watch(
  () => props.showContent, (val) => {
    if(val) {
      // 编辑获取焦点，防止编辑删除报错
      document.querySelector(".editor").focus();
      setTimeout(() => {
        let arr1 = document.querySelectorAll(".closeBtn1");
        arr1.forEach(item => {
          item.addEventListener("click", (el) => {
            handleRemove(el, 1);
          });
        })

        let arr2 = document.querySelectorAll(".closeBtn2");
        arr2.forEach(item => {
          item.addEventListener("click", (el) => {
            handleRemove(el, 2);
          });
        })
      }, 0)
    }
  }
)
</script>

<route lang="json">
  {
    "meta": {
      "hidden": true,
      "hideLayout": true
    }
  }
</route>

<style lang="scss" scoped>
.editor {
  outline: none;
  line-height: 28px;
  font-size: 14px;
}
:deep() {
  .el-popover.el-popper {
    min-width: 80px !important;
  }
  .item {
    display: block;
    height: 40px;
    line-height: 40px;
    margin: 0;
    padding: 0;
    padding-left: 15px;
    width: 100%;
    border: none;
    text-align: left;
    color: #606266;
    &:hover {
      background: #e8f7e0;
      border-radius: 8px;
    }
  }
  .el-slider__bar {
    background: #fdcb9e;
  }
  .el-slider__button {
    border-color: #fdcb9e;
  }
  .selectedValue {
    outline: none;
  }
}
</style>