<template>
  <div class="pinyin-area" :style="{ 'text-align': pinyinOverallPosition, padding: pinyinPadding }">
    <div v-for="(paragraph, i) in paragraphList" :key="i" class="pinyin-paragraph">
      <span
        v-for="(sentence, j) in paragraph"
        :key="j"
        class="pinyin-sentence"
        :style="{ 'align-items': pinyinPosition === 'top' ? 'flex-end' : 'flex-start' }"
      >
        <span v-for="(item, k) in sentence" :key="k" class="pinyin-text">
          <span
            :class="{ active: visible && word_index == k && paragraph_index === i && sentence_index === j }"
            :title="isPreview ? '' : '点击校对'"
            :style="{
              cursor: isPreview ? '' : 'pointer',
              'align-items': k == 0 ? 'flex-start' : 'center',
            }"
            @click="correctPinyin(item, i, j, k)"
          >
            <span
              v-if="pinyinPosition === 'top' && hasPinyinInParagraph(i)"
              class="pinyin"
              :style="{ 'font-size': pinyinSize }"
            >
              {{ getPinyinText(item) }}</span
            >
            <span class="py-char" :style="textStyle(item)">{{ convertText(item.text) }}</span>
            <span
              v-if="pinyinPosition !== 'top' && hasPinyinInParagraph(i)"
              class="pinyin"
              :style="{ 'font-size': pinyinSize }"
            >
              {{ getPinyinText(item) }}</span
            >
          </span>
        </span>
      </span>
    </div>

    <CorrectPinyin
      :visible.sync="visible"
      :select-content="selectContent"
      :component-type="componentType"
      @fillTonePinyin="fillTonePinyin"
    />

    <el-dialog
      ref="optimizedDialog"
      title=""
      :visible.sync="noteDialogVisible"
      width="680px"
      :style="dialogStyle"
      :close-on-click-modal="false"
      destroy-on-close
      @close="noteDialogVisible = false"
    >
      <span v-html="sanitizeHTML(note)"></span>
    </el-dialog>
  </div>
</template>

<script>
import CorrectPinyin from '@/views/book/courseware/create/components/base/common/CorrectPinyin.vue';
import { sanitizeHTML } from '@/utils/common';
import { isEnable } from '@/views/book/courseware/data/common';

export default {
  name: 'PinyinText',
  components: {
    CorrectPinyin,
  },
  inject: ['convertText'],
  props: {
    paragraphList: {
      type: Array,
      required: true,
    },
    pinyinPosition: {
      type: String,
      required: true,
    },
    fontFamily: {
      type: String,
      default: '',
    },
    fontSize: {
      type: String,
      default: '12pt',
    },
    pinyinSize: {
      type: String,
      default: '12pt',
    },
    pinyinOverallPosition: {
      type: String,
      default: 'left',
    },
    isPreview: {
      type: Boolean,
      default: false,
    },
    componentType: {
      type: String,
      default: '',
    },
    pinyinPadding: {
      type: String,
      default: '0px 0px 0px 0px',
    },
  },
  data() {
    return {
      isEnable,
      sanitizeHTML,
      visible: false,
      selectContent: {},
      paragraph_index: 0,
      sentence_index: 0,
      word_index: 0,
      noteDialogVisible: false,
      note: '',
      dialogStyle: {
        position: 'fixed',
        top: '0',
        left: '0',
        margin: '0',
      },
      isAllSetting: false,
    };
  },
  computed: {
    styleWatch() {
      return {
        fontSize: this.fontSize,
        fontFamily: this.fontFamily,
      };
    },
  },
  watch: {
    styleWatch: {
      handler() {
        this.isAllSetting = true;
      },
      immediate: true,
      deep: true,
    },
  },

  methods: {
    textStyle(item) {
      const styles = { ...item.activeTextStyle };
      styles['font-size'] = styles.fontSize;
      styles['font-family'] = styles.fontFamily;

      // if (this.fontSize) styles['font-size'] = this.fontSize;
      // if (this.fontFamily) styles['font-family'] = this.fontFamily;
      if (this.isAllSetting || !styles.fontSize) styles['font-size'] = this.fontSize;
      if (this.isAllSetting || !styles.fontFamily) styles['font-family'] = this.fontFamily;
      this.isAllSetting = false;
      return styles;
    },
    // 校对拼音
    correctPinyin(item, i, j, k) {
      if (this.isPreview) {
        if (item.note) {
          this.note = item.note;

          this.noteDialogVisible = true;
          this.$nextTick(() => {
            const dialogElement = this.$refs.optimizedDialog;
            // 确保对话框DOM已渲染
            if (!dialogElement) {
              return;
            }
            // 获取对话框内容区域的DOM元素
            const dialogContent = dialogElement.$el.querySelector('.el-dialog');
            if (!dialogContent) {
              return;
            }
            const dialogRect = dialogContent.getBoundingClientRect();
            const dialogWidth = dialogRect.width;
            const dialogHeight = dialogRect.height;
            const padding = 10; // 安全边距

            const clickX = event.clientX;
            const clickY = event.clientY;

            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;

            // 水平定位 - 中心对齐
            let left = clickX - dialogWidth / 2;
            // 边界检查
            left = Math.max(padding, Math.min(left, windowWidth - dialogWidth - padding));

            // 垂直定位 - 点击位置作为下边界中心
            let top = clickY - dialogHeight;
            // 上方空间不足时，改为向下展开
            if (top < padding) {
              top = clickY + padding;
              // 如果向下展开会超出屏幕，则贴底部显示
              if (top + dialogHeight > windowHeight - padding) {
                top = windowHeight - dialogHeight - padding;
              }
            }

            this.dialogStyle = {
              position: 'fixed',
              top: `${top - 20}px`,
              left: `${left}px`,
              margin: '0',
              transform: 'none',
            };
          });
        }
        return;
      } // 如果是预览模式，不操作
      if (item) {
        this.visible = true;
        this.selectContent = item;
        this.paragraph_index = i;
        this.sentence_index = j;
        this.word_index = k;
      }
    },
    // 回填校对后的拼音
    fillTonePinyin(dataContent) {
      this.$emit('fillCorrectPinyin', {
        selectContent: dataContent,
        i: this.paragraph_index,
        j: this.sentence_index,
        k: this.word_index,
      });
    },
    // 如段落有拼音，则返回true ，否则不显示拼音行
    hasPinyinInParagraph(paragraphIndex) {
      const paragraph = this.paragraphList[paragraphIndex];
      return paragraph.some((sentence) => sentence.some((item) => this.checkShowPinyin(item.showPinyin)));
    },
    // 兼容历史数据，没有showPinyin字段的，则默认为true
    checkShowPinyin(showPinyin) {
      if (showPinyin === undefined || showPinyin === null) {
        return true;
      }
      return this.isEnable(showPinyin);
    },
    getPinyinText(item) {
      return this.checkShowPinyin(item.showPinyin) ? item.pinyin.replace(/\s+/g, '') : '';
    },
  },
};
</script>

<style lang="scss" scoped>
.pinyin-area {
  .pinyin-paragraph {
    .pinyin-sentence {
      .pinyin-text {
        padding: 0 2px;
        font-size: 16px;
        text-wrap: pretty;
        hanging-punctuation: allow-end;

        > span {
          display: inline-flex;
          flex-direction: column;
          align-items: center;
        }

        .py-char {
          ruby-align: center;
        }

        .pinyin {
          display: inline-block;
          min-height: 12px;
          font-family: 'PINYIN-B';
          font-size: 12px;
          font-weight: lighter;
          line-height: 12px;
          color: $font-color;
        }
      }
    }
  }

  .active {
    color: rgb(242, 85, 90) !important;
  }
}
</style>

<style lang="scss">
.pinyin-area + .pinyin-area {
  margin-top: 4px;
}
</style>
