<template>
  <el-dialog
    :title="titleText"
    :visible.sync="visible"
    width="600px"
    :close-on-click-modal="false"
    @close="dialogClose()"
  >
    <div class="translate-container">
      <div class="translate-section">
        <div class="section-label">原文：</div>
        <div class="text-content original-text">{{ initText }}</div>
      </div>

      <div class="translate-section lang-selector">
        <span class="section-label">目标语种：</span>
        <el-select v-model="lang" placeholder="请选择语言" size="mini" class="lang-select" @change="handleLangChange">
          <el-option v-for="item in langList" :key="item.type" :label="item.name" :value="item.type" />
        </el-select>
      </div>

      <div class="translate-section">
        <div class="section-label">译文：</div>
        <div class="text-content translated-text" :style="{ lineHeight: lang === 'ZH' ? '1' : '1.5' }">
          {{ translateResultText }}
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetLanguageTypeList, Texttrans } from '@/api/book';

export default {
  name: 'TranslateDialog',
  components: {},
  props: {
    open: {
      type: Boolean,
      default: false,
      required: true,
    },
    initText: {
      type: String,
      default: '',
    },
    titleText: {
      type: String,
      default: '翻译',
    },
    bookId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      visible: false,
      lang: 'ZH',
      langList: [],
      translateResultList: [],
    };
  },
  computed: {
    // 计算最终显示的译文字符串
    translateResultText() {
      if (!this.translateResultList || this.translateResultList.length === 0) {
        return '';
      }
      let resultText = this.translateResultList.map((item) => item.dst);
      return resultText.join('\n');
    },
  },
  watch: {
    open(newVal) {
      this.visible = newVal;
      if (newVal) {
        this.getLangList();
        this.translateResultList = [];
      }
    },
    visible(newVal) {
      if (!newVal) {
        this.$emit('update:open', false);
        this.translateResultList = [];
        this.lang = 'ZH';
      }
    },
    langList(newVal) {
      if (newVal && newVal.length > 0 && this.initText) {
        this.$nextTick(() => {
          this.fetchTranslation();
        });
      }
    },
  },
  methods: {
    dialogClose() {
      this.visible = false;
    },

    /**
     * 获取语言列表
     */
    getLangList() {
      if (!this.bookId) return;
      GetLanguageTypeList({ book_id: this.bookId, is_contain_zh: 'true' }).then(({ language_type_list }) => {
        this.langList = language_type_list;
      });
    },

    /**
     * 语种改变时触发
     */
    handleLangChange(val) {
      if (!this.initText) {
        this.$message.warning('暂无可翻译内容');
        return;
      }
      this.fetchTranslation();
    },

    /**
     * 调用翻译接口
     */
    fetchTranslation() {
      this.translateResultList = [];
      const params = {
        text: this.initText,
        from: 'zh',
        to: this.lang,
      };
      Texttrans(params)
        .then((res) => {
          if (res.status === 1) {
            this.translateResultList = res.trans_list || [];
          }
        })
        .catch(() => {
          this.$message.error('翻译失败');
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.translate-container {
  padding: 10px;

  .translate-section {
    margin-bottom: 15px;

    .section-label {
      display: block;
      margin-bottom: 8px;
      font-size: 14px;
      font-weight: bold;
      color: #606266;
    }

    // 核心样式：保留换行符，自动换行
    .text-content {
      min-height: 40px;
      max-height: 300px;
      padding: 10px;
      overflow-y: auto;
      font-size: 14px;
      line-height: 1;
      color: #303133;
      word-break: break-all;
      white-space: pre-wrap;

      /* 关键：保留空格和换行符 */
      background-color: #f5f7fa;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }

    .translated-text {
      line-height: 1.5;
    }

    &.lang-selector {
      display: flex;
      align-items: center;

      .section-label {
        margin-right: 10px;
        margin-bottom: 0;
      }
    }
  }
}

.el-dialog {
  :deep &__body {
    display: flex;
    flex-direction: column;
    row-gap: 8px;
    padding: 10px;

    .el-textarea__inner {
      height: 108px;
    }
  }
}
</style>
