<template>
  <div class="root_container">
    <el-dialog title="查看翻译的修改日志" :visible.sync="dialogShow" width="30%">
      <el-timeline v-show="activities.length > 0" style="margin: 18px">
        <el-timeline-item v-for="(activity, index) in activities" :key="index" :timestamp="activity.timestamp">
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
      <div v-show="activities.length == 0" style="padding: 18px">
        暂无更新记录
      </div>
    </el-dialog>


    <el-dialog title="请输入翻译内容" :width="minWidth" :visible.sync="showEditDialog">
      <div class="span_tag">唯一KEY：{{ currentKey }}</div>
      <div class="span_tag">默认语言内容：{{ currentValues }}</div>
      <div class="span_tag">当前语言：{{ currentChannel }}</div>
      <div style="padding-right: 20px;padding-left: 20px;padding-top: 10px;">
        <el-input ref="dialogInput" type="textarea" class="hasContent" placeholder="请输入翻译后的内容"
          @keydown.native="handleEditKeyDown" :autosize="{ minRows: 10, maxRows: 15 }" resize="none" autocomplete="off"
          v-model="currentContent"></el-input>
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex;align-items: center">
        <div style="color: #aaa;">
          <div>
            原来语种<el-select @change="onLanguageSelect" size="small"
              style="width: 130px;margin-left: 10px;margin-right: 10px;" v-model="oriTranslateLan" placeholder="请选择">
              <el-option v-for="item in languageList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            目标语种<el-select @change="onLanguageSelect" size="small" style="width: 130px;margin-left: 10px;"
              v-model="aimTranslateLan" placeholder="请选择">
              <el-option v-for="item in languageList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button plain type="info" style="margin-top: 8px;margin-left: 10px;" @click="onlineTranslate"
              size="small">在线翻译</el-button>
          </div>
          <div style="margin-top: 5px;"></div>
        </div>
        <span
          style="color:#aaa;display: inline-block;padding-right: 10px;line-height: 20px;margin-left: auto;">使用Shift+回车可直接保存数据<br>使用Esc可直接取消编辑</span>
        <div style="display: inline-block;">
          <el-button type="primary" @click="completeTranslate">确 定</el-button>
        </div>
      </div>
    </el-dialog>

    <div class="header">
      <div class="form_container">
        <el-form :inline="true" :model="formData" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="formData.search" placeholder="请搜索内容" @change="onDoSearch" size="small"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formData.translateStatus" placeholder="请选择翻译类型" size="small" @change="onDoSearch"
              style="width: 140px">
              <el-option label="全部内容" value="0"></el-option>
              <el-option label="部分翻译" value="1"></el-option>
              <el-option label="未翻译" value="2"></el-option>
              <el-option label="翻译完成" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button style="margin-left: 10px" type="primary" @click="onDoSearch" size="small">查询</el-button>
          </el-form-item>
          <el-form-item>
            精准搜索
            <el-switch style="margin-left: 5px" v-model="formData.searchType">
            </el-switch>
          </el-form-item>
          <span style="width: 1px;background-color: #ccc;height: 30px;display: inline-block;margin-top: 5px;"></span>
          <el-form-item style="margin-left: 10px;">
            <!-- 筛选模块 -->
            <el-popover v-model="filterPopoverVisible" placement="bottom" style="height: 300px;" trigger="click">
              <el-table @selection-change="onChannelFilterSelectChange" ref="multipleFilterTable" v-model="selectedRows"
                :row-key="row => row.prop" border :data="tableColumnsFilter" max-height=600>
                <el-table-column type="selection" width="40">
                </el-table-column>
                <el-table-column width=150 property="label" label="语言类型"></el-table-column>
              </el-table>
              <el-button plain type="primary" style="margin-top: 10px;" @click="onSaveChannelFilter"
                size="small">保存修改</el-button>
              <el-button slot="reference" plain type="primary" @click="onShowChannelFilter" size="small">筛选</el-button>
            </el-popover>
          </el-form-item>
          <el-form-item>
            

            <el-dropdown @command="handleExportCommand"  trigger="click">
              <!-- @click="exportExcel" -->
              <el-button plain type="primary"  size="small">
                导出翻译 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="0">导出全部内容</el-dropdown-item>
                <el-dropdown-item command="1">导出部分翻译</el-dropdown-item>
                <el-dropdown-item command="2">导出未翻译</el-dropdown-item>
                <el-dropdown-item command="3">导出翻译完成</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
            <el-button style="margin-left: 10px;" size="small" plain type="primary" @click="importExcel"
              :loading="uploadExcel">导入翻译</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="table_container">
      <el-table :data="tableData" :height="tableHeight" :row-class-name="tableRowClassName" border style="width: 100%">
        <el-table-column fixed type="index" width="50" label="编号"></el-table-column>
        <template v-for="(item, index) in tableColumns">
          <el-table-column :prop="item.prop" :label="item.label" :fixed="index < 2" min-width="150">
            <template slot-scope="scope">
              <div style="word-break: break-all!important" :title="scope.row[item.prop].source"
                @click="clickTranslateArea(scope.row[item.prop], item.prop, scope.row['item_key'].source, scope.row[mainChannel].source, index)"
                slot="reference" :style="{
                  color: scope.row[item.prop].source ? '#606266' : '#cccccc',
                }">{{ scope.row[item.prop].source ? scope.row[item.prop].source : "点击翻译" }}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="pager">
      <span style="color: #999999; display: inline-block; padding-top: 9px">共 {{ totalCount }} 条数据，每页 {{ pageSize }}
        条</span>
      <div class="pager_item" style="display: inline-block">
        <el-pagination background :page-size="pageSize" @current-change="pageChange" layout="prev, pager, next"
          :pager-count="5" :total="totalCount" :current-page="currentPage">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid';
import {
  translateList,
  translateContent,
  translateEdit,
  translateLog,
  translateMerge,
  translateSplit,
  translateDelete,
  translateModules,
  translateConfirm,
} from "../../api/log/translate";
import {
  v2TranslateListV2,
  channelSelect,
  editTranslate,
  onlineConvert,
  excelExport,
  excelImport
} from './../../api/log/translate_v2'
import { Message } from "element-ui";
import LangUtils from './../../utils/translate_language'
import localStore from './../../utils/localstorage.js'
import GlobalConstants from './../../utils/constants.js'
export default {
  data() {
    return {
      activities: [],
      //记录高度
      tableHeight: -1,

      //项目数据
      appId: 1,

      translate_temp: "",
      visible_temp: false,

      //模块数据
      moduleList: [
        {
          key: "",
          value: "所有模块",
        },
      ],

      uploadExcel: false,

      formData: {
        search: "",
        searchType: false,
        translateStatus: '0'
      },

      dialogShow: false,
      formLabelWidth: "100px",

      //处理编辑翻译的内容
      currentKey: "", //对话框提示中的key
      mainChannel: "", //对话框提示中的主要渠道
      currentChannel: "", //对话框中当前需要翻译的渠道
      currentValues: "",//当前对话框中的内容
      currentContent: "",
      showEditDialog: false,
      currentData: undefined,
      minWidth: '900px',

      //处理筛选
      tableColumnsFilter: [],
      selectedRows: [{ prop: 'values-sv-rSE' }],
      multipleChannelSelection: [],
      filterPopoverVisible: false,

      //在线翻译
      languageList: [],
      oriTranslateLan: '',//原来语种
      aimTranslateLan: "",//目标语种


      //分页数据
      totalCount: 0,
      currentPage: 1,
      pageSize: 50,
      pagerCount: 3,

      //处理核心表格
      tableData: [],
      tableColumns: [],


      dataPlaceHolder: '{"name":"穆仙念"}',

      //当前的数据
      currentData: {
        dialogTitle: "",
        title: "",
        path: "",
        request_url: "",
        response: "",
        type: -1, // 1 新增 2 修改
        id: -1,
      },



    };
  },
  watch: {
    "$store.state.screenHeight": function (val) {
      this.tableHeight = val - 98 - 50;
    },
  },
  mounted: function () {
    this.tableHeight = this.$store.state.screenHeight - 98 - 30 - 32;
    this.appId = this.$route.query.id;

    this.languageList = LangUtils.Language
    //获取本地存储的语言类型
    this.oriTranslateLan = localStore.getStorage(GlobalConstants.LOCAL_KEY_CURRENT_FROM_LAN) || ''
    this.aimTranslateLan = localStore.getStorage(GlobalConstants.LOCAL_KEY_CURRENT_TO_LAN) || ''

    this.currentPage = 1;
    // this.onObtainTranslateModules();
    this.onObtainData();
  },
  methods: {
    //筛选内容发生变化
    onChannelFilterSelectChange(selections) {
      this.multipleChannelSelection = selections.map(item => item.prop);
    },

    //导出
    handleExportCommand(command){
      this.exportExcel(command)
    },

    //点击筛选按钮
    onShowChannelFilter() {
      let arr = this.tableColumnsFilter.filter((item) => { return item.show; });

      arr.forEach(item => {
        this.$refs.multipleFilterTable.toggleRowSelection(item);
      })
    },

    importExcel() {
      this.$confirm('导入翻译前请先导出翻译，然后在导出的Excel文档基础上进行翻译，最后再导入该文件，请不要修改导出Excel中文档的格式，否则将无法识别', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.fileInput.click();
      }).catch(() => {

      });
    },

    //选择文件
    handleFileChange(event) {
      this.uploadExcel = true
      // 获取用户选择的文件
      const selectedFile = event.target.files[0];
      // 在这里可以执行一些文件选择后的逻辑
      excelImport(selectedFile, this.appId).then(res => {
        this.uploadExcel = false
        this.onObtainData()
        this.$refs.fileInput.value = null;
      }).catch(e => {
        this.uploadExcel = false
        this.onObtainData()
        this.$refs.fileInput.value = null;
      })
    },

    //导出表格
    exportExcel(command) {
      excelExport(this.appId,command).then(res => {
        console.log(res);
        // 创建 Blob 对象
        const blob = new Blob([res.data], { type: res.headers['content-type'] });
        // 创建一个 <a> 元素，设置下载链接
        const link = document.createElement('a');
        const href = window.URL.createObjectURL(blob);
        link.href = href
        // 指定下载文件的名称
        link.download = decodeURIComponent(res.headers['filename']);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(href)
      }).catch(e => {
        console.log(e);
      })
    },

    //在线翻译
    onlineTranslate() {
      if (!this.currentValues) {
        Message.warning("源翻译内容不能为空")
        return
      }
      if (!this.oriTranslateLan) {
        Message.warning("源语种未选择")
        return
      }
      if (!this.aimTranslateLan) {
        Message.warning("目标语种未选择")
        return
      }
      onlineConvert(this.currentValues, this.oriTranslateLan, this.aimTranslateLan).then(res => {
        Message.success("翻译成功")
        this.currentContent = res.data.data.result;
      }).catch(e => { })
    },

    //监听对话框中编辑内容时候的按键
    handleEditKeyDown(event) {
      if (event.shiftKey && event.key === "Enter") {
        // 执行你的逻辑

        this.completeTranslate()
      }
    },

    //语种被选择
    onLanguageSelect() {
      localStore.saveStorage(GlobalConstants.LOCAL_KEY_CURRENT_FROM_LAN, this.oriTranslateLan)
      localStore.saveStorage(GlobalConstants.LOCAL_KEY_CURRENT_TO_LAN, this.aimTranslateLan)
    },

    //保存筛选内容
    onSaveChannelFilter() {
      let arr = this.tableColumnsFilter.filter((item) => { return this.multipleChannelSelection.indexOf(item.prop) == -1; }).map(item => item.prop);
      channelSelect(this.appId, arr).then(res => {
        this.filterPopoverVisible = false;
        this.tableData = [];
        this.rowClassName = [];
        this.onObtainData()
      }).catch(e => {

      })
    },

    //点击翻译确定按钮
    completeTranslate() {
      this.currentData.source = this.currentContent
      this.showEditDialog = false
      //appId,key,content,currentChannel
      editTranslate(this.appId, this.currentKey, this.currentContent, this.currentChannel).then(res => {
        Message.success("编辑成功")
      }).then(res => { })

      this.currentContent = ""
    },

    //点击翻译内容区域
    clickTranslateArea(data, currentChannel, currentKey, currentValues, index) {
      console.log(currentValues);
      if (index < 2) {
        return
      }
      this.currentKey = currentKey
      this.currentValues = currentValues
      this.currentChannel = currentChannel

      this.currentData = data
      this.currentContent = data.source
      this.showEditDialog = true
      setTimeout(() => {
        this.$refs.dialogInput.focus();
      }, 300)
    },

    //页面发生变化
    pageChange(page) {
      this.currentPage = page;

      this.onObtainData();
    },
    //获取module列表
    onObtainTranslateModules() {
      translateModules()
        .then((result) => {
          if (result.data.code == 200) {
            this.moduleList = result.data.data;
          }
        })
        .catch((err) => { });
    },
    //双击事件
    onDoubleClick(item) {
      var that = this;
      this.$confirm(
        "是否要删除ID为" + item.id + "，内容为【" + item.content + "】的记录",
        "删除翻译【慎重】",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          translateDelete(item.id)
            .then((result) => {
              if (result.data.code == 200) {
                Message.success("删除成功");

                that.currentPage = 1;
                that.onObtainData();
              }
            })
            .catch((err) => { });
        })
        .catch(() => { });
    },
    //关闭pop
    closePop(item) {
      item.pop_visable = false;
    },
    //点击查看日志
    onLog(item) {
      translateLog(item.id)
        .then((result) => {
          if (result.data.code == 200) {
            this.activities = [];
            result.data.data.forEach((item) => {
              this.activities.push({
                content: item.log,
                timestamp: item.time,
              });
            });
            this.dialogShow = true;
          }
        })
        .catch((err) => { });
    },
    //点击 merge
    onMerge(item) {
      var that = this;
      this.$prompt("请输入你希望与之合并的翻译ID", "合并内容", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          if (!parseInt(value)) {
            Message.warning("请输入数字");
            return;
          }
          translateMerge(item.id, value)
            .then((result) => {
              if (result.data.code == 200) {
                Message.success("合并成功");
                that.currentPage = 1;
                that.onObtainData();
              }
            })
            .catch((err) => { });
        })
        .catch(() => { });
    },
    onDoConfirm(item) {
      this.$confirm(
        "确定将该翻译标记为【" +
        (item.isConfirm ? "取消确认翻译" : "确认翻译") +
        "】",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          translateConfirm(item.id, !item.isConfirm)
            .then((result) => {
              if (result.data.code == 200) {
                Message.success("操作成功");
                this.onObtainData();
              }
            })
            .catch((err) => { });
        })
        .catch(() => { });
    },
    //点击翻译拆分
    onSplit(item) {
      var that = this;
      this.$confirm(
        "是否需要将该条翻译拆分成两条独立的未合并的翻译记录，拆分之后如果需要合并需要手动再次合并",
        "翻译拆分",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          translateSplit(item.id)
            .then((result) => {
              if (result.data.code == 200) {
                Message.success("拆分成功");

                that.currentPage = 1;
                that.onObtainData();
              }
            })
            .catch((err) => { });
        })
        .catch(() => { });
    },
    //pop点击确定
    okPop(item) {
      item.pop_visable = false;
      if (!item.translate_temp) return;
      translateEdit(item.id, item.translate_temp)
        .then((res) => {
          if (res.data.code == 200) {
            item.originTranslateEn = res.data.data.translate;
            item.translateEn = res.data.data.translate;
            item.updateTime = res.data.data.update_time;
            Message.success("保存成功");
          }
        })
        .catch((e) => { });
    },
    //智能翻译
    onAutoTranslate(item) {
      if (!item.content) return;
      translateContent(item.content)
        .then((res) => {
          item.translate_temp = res.data.data.result;
          item.pop_visable = true;
        })
        .catch((e) => { });
    },
    //保存翻译
    onEditTranslate(item) {
      if (!item.translateEn) return;
      translateEdit(item.id, item.translateEn)
        .then((res) => {
          if (res.data.code == 200) {
            item.originTranslateEn = res.data.data.translate;
            item.updateTime = res.data.data.update_time;
            Message.success("保存成功");
          }
        })
        .catch((e) => { });
    },
    //动态设置表格背景色
    tableRowClassName({ row, rowIndex }) {
      if (!row.isMerged) {
        return "warning-row";
      }
      return "";
    },
    //获取数据
    onObtainData() {
      v2TranslateListV2(this.appId, this.currentPage, this.formData.search, this.formData.searchType, this.formData.translateStatus)
        .then(res => {
          this.tableColumns = res.data.data.extra.tabs;
          this.tableColumnsFilter = res.data.data.extra.allTabs
          this.tableData = res.data.data.list;
          this.mainChannel = res.data.data.extra.mainChannel;

          this.totalCount = res.data.data.total;
          this.currentPage = res.data.data.currentPage;
          this.pageSize = res.data.data.pageSize;
        }).catch(e => { })
    },
    //点击搜索
    onDoSearch() {
      this.currentPage = 1;
      this.onObtainData();
    },
    //点击添加用户
    addUserBtn() {
      this.currentData.dialogTitle = "新增接口";
      this.currentData.title = "";
      this.currentData.path = "";
      this.currentData.request_url = "";
      this.currentData.response = "";
      this.currentData.okBtn = "添 加";
      this.currentData.id = -1;
      this.currentData.type = 1;
      this.dialogShow = true;
    },
    //查看详情
    onDetails(item) {
      mockDetails(item.id)
        .then((result) => {
          var data = result.data.data;
          this.currentData.dialogTitle = "接口详情";
          this.dialogShow = true;
          this.currentData.title = data.title;
          this.currentData.path = data.path;
          this.currentData.id = data.id;
          this.currentData.request_url = data.request_url;
          this.currentData.response = data.response;
          this.currentData.okBtn = "确 定";
          this.currentData.type = 2;
        })
        .catch((err) => { });
    },
  },
};
</script>
<style lang="scss" scoped>
.root_container {
  position: relative;
}

.table_container {
  padding-left: 18px;
  padding-right: 18px;
}

.pager {
  padding-left: 18px;
  padding-top: 10px;
  bottom: -50px;
  position: absolute;
  right: 0;
  padding-right: 10px;
  padding-bottom: 10px;
  display: flex;
}

.confirm_tips {
  color: #67c23a;
  padding-left: 10px;
  font-size: 12px;
}

.header {
  padding-top: 10px;
  padding-left: 18px;
}

.tab_tips {
  word-break: break-all;
  width: auto;
  display: block;
  margin-bottom: 6px;
  white-space: pre-wrap;
  word-wrap: break-word;
  height: auto;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-table .warning-row {
  background: oldlace !important;
}

.el-button+.el-button {
  margin-left: 0;
}

.span_tag {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  margin-left: 20px;
  margin-bottom: 5px;
  margin-right: 20px;
  padding: 4px;
}

.el-table .cell {
  word-break: break-all !important;
}
</style>