<template>
  <div v-loading="loading" class="check-article">
    <HeaderPage />
    <div class="main">
      <div class="main-top">
        <div style="display: flex">
            <a class="go-back" @click="$router.go(-1)">
                <i class="el-icon-arrow-left"></i>
                返回
            </a>
            <b>校对拼音</b>
        </div>
        <div class="btn-box">
            <el-button type="info" @click="$router.go(-1)">取消</el-button>
            <el-button type="primary" @click="savePinyin(id)">保存</el-button>
        </div>
      </div>
      <div class="article">
        <div class="paragraph" v-for="(item, index) in indexArr" :key="index + 'paragraph'" >
            <div class="sentence-box" v-for="(items, indexs) in item" :key="indexs + 'words'">
                <div class="sentence" @click="selectItem(items,index)" :style="{marginRight:items.marginRight?'8px':'',color: activeIndex === index+'_'+items.sentenceIndex+'_'+items.wordIndex?'#F2555A':''}">
                    <span class="pinyin">{{items.pinyin_lt?items.pinyin_lt:items.pinyin}}</span>
                    <span class="words" :class="[/^[0-9]*$/.test(items.text)]?/^[\u4e00-\u9fa5]/.test(items.text)?'hanzi':'en':''">
                        {{items.text}}
                    </span>
                </div>
            </div>
        </div>
      </div>
    </div>
    <el-dialog
        :visible.sync="dialogFlag"
        :show-close="false"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :modal="false"
        width="250px"
        class="login-dialog"
        v-if="dialogFlag">
        <div class="check-box">
            <div class="content">
                <template v-if="itemActive.pinyin_lt">
                    <div class="words-box">
                        <span class="pinyin">
                            {{itemActive.pinyin_lt}}
                        </span>
                        <span class="words">
                            {{itemActive.text}}
                        </span>
                    </div>
                </template>
                <template v-else>
                    <div class="words-box">
                        <span class="pinyin">
                            {{itemActive.pinyin}}
                        </span>
                        <span class="words">
                            {{itemActive.text}}
                        </span>
                    </div>
                </template>
            </div>
            <el-input v-model="checkPinyinInput" type="text" class="checkPinyinInput" />
            <p class="tips">
                一到四声分别用数字1-4表示，轻声用0表示。拼音间用空格隔开，例如“北语社”，输入“bei3 yu3 she4”；若需要连在一起显示，用_隔开，例如“哪儿”，输入“na3_er”
            </p>
            <div class="btn-box">
                <el-button type="info" size="small" @click="cancleDialog">取消</el-button>
                <el-button type="primary" size="small" @click="surePinyin">保存</el-button>
            </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import HeaderPage from '@/components/Header.vue';
import { publicMethods, reparse } from '@/api/api';
import th from 'element-ui/lib/locale/lang/th';

export default {
  components: {
    HeaderPage,
  },
  data() {
    return {
      loading: false,
      id: '',
      ArticelData: null,
      indexArr: [], // 索引数组
      activeIndex: null,
      itemActive: null,
      dialogFlag: false,
      checkPinyinInput: '',
      oldInput: '',
      tableData: [
        ["ā", "á", "ǎ", "à", "a"],
        ["ō", "ó", "ǒ", "ò", "o"],
        ["ē", "é", "ě", "è", "e"],
        ["ī", "í", "ǐ", "ì", "i"],
        ["ū", "ú", "ǔ", "ù", "u"],
        ["ǖ", "ǘ", "ǚ", "ǜ", "ü"],
        ["Ā", "Á", "Â", "À", "A"],
        ["Ō", "Ó", "Ô", "Ò", "O"],
        ["Ē", "É", "Ê", "È", "E"],
        ["Ī", "Í", "Î", "Ì", "I"],
        ["Ū", "Ú", "Û", "Ù", "U"],
      ],
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.routerData = JSON.parse(JSON.stringify(this.$route.query));
    this.id = this.routerData.id
    this.getArticleData()
  },
  methods: {
    // 获取分析结果
    getArticleData() {
      this.loading = true;
      publicMethods('/TeachingServer/TextAnalyser/GetParsedTextInfo',{
          analyse_record_id: this.id,
        }
      )
        .then((res) => {
            if(res.status===1){
                let newdata = [];
                res.parsed_text.paragraph_list.forEach((item) => {
                    if (item.length !== 0) {
                        newdata.push(item);
                    }
                });
                // this.ArticelData = JSON.parse(JSON.stringify(newdata));
                let saveArr = []
                let arr = []
                let saveIndex = 0
                // 添加索引
                newdata.forEach((item,index) => {
                    arr.push([])
                    item.forEach((items,indexs) => {
                        items.forEach((itemss,indexss)=>{
                            let str = ''
                            let pinyinStr = ''
                            let pinyinNo = ''
                            itemss.text.forEach((itemT,indexT)=>{
                                str += itemT.word
                                pinyinStr += itemT.pinyin + ','
                                pinyinNo += itemT.pinyin
                            })
                            let obj = {
                                text: str,
                                pinyin: pinyinNo,
                                paraIndex: index,
                                sentenceIndex: indexs,
                                wordIndex: indexss,
                                wordArr: itemss.text,
                                marginRight: true,
                                saveIndex: saveIndex,
                                pinyin_lt: itemss.pinyin_lt
                            }
                            arr[index].push(obj)
                            let saveObj = {
                                word: str,
                                pinyin: pinyinStr.substring(0,pinyinStr.length-1),
                                // pinyin_lt: itemss.pinyin_lt?itemss.pinyin_lt:''
                            }
                            saveArr.push(saveObj)
                            saveIndex++
                        })
                        
                    });
                });
                this.indexArr = arr
                this.ArticelData = saveArr
                this.loading = false;
            }
          
        })
        .catch(() => {
          this.loading = false;
        });
    },
    selectItem(item,index){
        this.activeIndex = index+'_'+item.sentenceIndex+'_'+item.wordIndex
        this.itemActive = item
        this.dialogFlag = true
    },
    cancleDialog(){
        this.activeIndex = null
        this.itemActive = null
        this.checkPinyinInput = ''
        this.oldInput = ''
        this.dialogFlag = false
    },
    surePinyin(){
        this.oldInput = JSON.parse(JSON.stringify(this.checkPinyinInput.trim()))
        this.handleReplaceTone(this.checkPinyinInput.trim())
    },
    handleReplaceTone(e) {
      let _this = this;
      _this.$nextTick(() => {
        let value = e;
        _this.resArr = [];
        if (value) {
            let valueArr = []
            if(value.indexOf('_')>-1){
                value.replace(/_{1,}/g,'_')
                valueArr = value.split('_')
            }else{
                value.replace(/\s+/g, " ")
                valueArr = value.split(' ')
            }
        //   let reg = /\s+/g;
        //   valueArr = value.split(reg);
          valueArr.forEach((item, index) => {
            this.handleValue(item);
          });
          let str = "";
          setTimeout(() => {
            _this.resArr.forEach((item) => {
              str += " ";
              item.forEach((sItem) => {
                if (sItem.number && sItem.con) {
                  let number = Number(sItem.number);
                  let con = sItem.con;
                  let word = _this.addTone(number, con);
                  str += word;
                } else {
                  if (sItem.number) {
                    str += sItem.number;
                  } else if (sItem.con) {
                    str += " " + sItem.con + " ";
                  }
                }
              });
            });
            this.checkPinyinInput = str.trim();
            if(this.oldInput.indexOf('_')>-1){
                this.ArticelData[this.itemActive.saveIndex].pinyin = this.checkPinyinInput.replace(/\s+/g, " ").split(/\s+/).join('_')
                this.checkPinyinInput = this.checkPinyinInput.replace(/\s+/g, " ").split(/\s+/).join('_').replace('_e','').replace('_ē','').replace('_é','').replace('_ě','').replace('_è','')
                this.itemActive.pinyin_lt = this.checkPinyinInput.replace(/\s+/g, "")
            }else{
                this.ArticelData[this.itemActive.saveIndex].pinyin = this.checkPinyinInput.replace(/\s+/g, " ").split(/\s+/).join(',')
                this.itemActive.pinyin = this.checkPinyinInput.replace(/\s+/g, "")
            }
            // this.ArticelData[this.itemActive.saveIndex].pinyin = this.checkPinyinInput
            
            this.loading = true;
            publicMethods('/TeachingServer/TextAnalyser/AddMyPinyinProofread',{
                analyse_record_id: this.id,
                word_list: [this.ArticelData[this.itemActive.saveIndex]]
                }
            )
                .then((res) => {
                    this.loading = false;
                    if(res.status===1){
                        this.$message.success('保存成功')
                        this.activeIndex = null
                        this.itemActive = null
                        this.checkPinyinInput = ''
                        this.oldInput = ''
                        this.dialogFlag = false
                        // this.getArticleData()
                    }
                })
                .catch(() => {
                this.loading = false;
                });
          }, 10);
        }
      });
    },
    handleValue(valItem) {
      let reg = /\d/;
      let reg2 = /[A-Za-z]+\d/g;
      let numList = [];
      let valArr = valItem.split("");
      if (reg2.test(valItem)) {
        for (let i = 0; i < valArr.length; i++) {
          let item = valItem[i];
          if (reg.test(item)) {
            let numIndex =
              numList.length == 0 ? 0 : numList[numList.length - 1].index;
            let con = valItem.substring(numIndex, i);
            con = con.replace(/\d/g, "");
            let obj = {
              index: i,
              number: item,
              con: con,
              isTran: true,
            };
            numList.push(obj);
          }
        }
      } else {
        numList = [];
      }
      if (numList.length == 0) {
        this.resArr.push([{ con: valItem }]);
      } else {
        this.resArr.push(numList);
      }
    },
    addTone(number, con) {
      let _this = this;
      let zmList = ["a", "o", "e", "i", "u", "v", "A", "O", "E", "I", "U"];
      if (number) {
        for (let i = 0; i < zmList.length; i++) {
          let zm = zmList[i];
          if (con.indexOf(zm) > -1) {
            let zm2 = _this.tableData[i][number - 1];
            if (con.indexOf("iu") > -1) {
              zm2 = _this.tableData[4][number - 1];
              con = con.replace("u", zm2);
            } else if (con.indexOf("ui") > -1) {
              zm2 = _this.tableData[3][number - 1];
              con = con.replace("i", zm2);
            } else if (
              con.indexOf("yv") > -1 ||
              con.indexOf("jv") > -1 ||
              con.indexOf("qv") > -1 ||
              con.indexOf("xv") > -1
            ) {
              zm2 = _this.tableData[4][number - 1];
              con = con.replace("v", zm2);
            } else {
              con = con.replace(zm, zm2);
            }

            break;
          }
        }
      }
      return con;
    },
    savePinyin(analyse_record_id){
      this.loading = true;
      reparse({ analyse_record_id })
        .then(({ record }) => {
          this.getArticleData()
        })
        .finally(() => {
          this.loading = false;
        });
    }
  },
};
</script>

<style lang="scss" scoped>
.check-article {
  min-height: 100%;
  background: #f6f6f6;

  .wheader {
    background: #fff;
  }
    .el-button{
        padding: 5px 16px;
        border-radius: 2px;
        border: 1px solid #F2F3F5;
        color: #4E5969;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        background: #F2F3F5;
        &.el-button--primary{
            background: #165DFF;
            border: 1px solid #165DFF;
            color: #FFF;
        }
    }
  .main {
    width: 1200px;
    margin: 23px auto;
    background: #FFF;
    padding: 24px;
    &-top{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24px;
        position: relative;
        b{
            color: #000;
            font-size: 24px;
            font-weight: 500;
            line-height: 34px;
            margin-left: 16px;
        }
    }
    .go-back{
        border-radius: 4px;
        border: 1px solid #D9D9D9;
        background: #FFF;
        box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.02);
        display: flex;
        width: 60px;
        color: #333;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        padding: 5px 8px;
        align-items: center;
        cursor: pointer;
        .el-icon-arrow-left{
            font-size: 16px;
            margin-right: 8px;
        }
    }
    .article{
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.08);
        background: #FCFCFC;
        padding: 8px;
    }
    .paragraph{
        margin-bottom: 24px;
        text-align: center;
        display: flex;
        flex-flow: wrap;
        width: 100%;
        .sentence-box{
            display: flex;
            flex-flow: wrap;
            float: left;
            .sentence{
                margin-top: 8px;
                text-align: center;
                cursor: pointer;
                color: #000;
                .words{
                    display: block;
                    font-size: 20px;
                    line-height: 28px;
                    font-weight: 400;
                }
                .pinyin{
                    font-family: 'League';
                    font-size: 14px;
                    font-weight: 400;
                    line-height: 1;
                    height: 14px;
                    display: block;
                }
            }
        }
    }
  }
}
.check-box{
    padding: 24px;
    border-radius: 4px;
    background: #FFF;
    box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
    .content{
        display: flex;
        align-items: center;
        justify-content: center;
        .words-box{
            text-align: center;
            color: #000;
            .words{
                display: block;
                font-size: 28px;
                line-height: 40px;
                font-weight: 400;
            }
            .pinyin{
                font-family: 'League';
                font-size: 20px;
                font-weight: 400;
                line-height: 1;
                height: 20px;
                display: block;
            }
        }
    }
    .checkPinyinInput{
        margin: 16px 0 8px 0;
    }
    .tips{
        color: #A0A0A0;
        font-size: 12px;
        font-weight: 400;
        line-height: 18px;
        margin: 0 0 24px 0;
    }
    .btn-box{
        text-align: right;
        .el-button{
            font-size: 12px;
            padding: 2px 12px;
            line-height: 20px;
        }
    }
}
</style>
<style lang="scss">
.check-article{
    .login-dialog{
        .el-dialog__header{
            padding: 0;
        }
        .el-dialog__body{
            padding: 0;
        }
        .el-input__inner{
           background: #F3F3F3; 
           text-align: center;
        }
    }
}

</style>

